1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.7.2.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a one translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% are more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25#ifndef SQLITE_API
26# define SQLITE_API
27#endif
28/************** Begin file sqliteInt.h ***************************************/
29/*
30** 2001 September 15
31**
32** The author disclaims copyright to this source code.  In place of
33** a legal notice, here is a blessing:
34**
35**    May you do good and not evil.
36**    May you find forgiveness for yourself and forgive others.
37**    May you share freely, never taking more than you give.
38**
39*************************************************************************
40** Internal interface definitions for SQLite.
41**
42*/
43#ifndef _SQLITEINT_H_
44#define _SQLITEINT_H_
45
46/*
47** These #defines should enable >2GB file support on POSIX if the
48** underlying operating system supports it.  If the OS lacks
49** large file support, or if the OS is windows, these should be no-ops.
50**
51** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52** system #includes.  Hence, this block of code must be the very first
53** code in all source files.
54**
55** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56** on the compiler command line.  This is necessary if you are compiling
57** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59** without this option, LFS is enable.  But LFS does not exist in the kernel
60** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61** portability you should omit LFS.
62**
63** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64*/
65#ifndef SQLITE_DISABLE_LFS
66# define _LARGE_FILE       1
67# ifndef _FILE_OFFSET_BITS
68#   define _FILE_OFFSET_BITS 64
69# endif
70# define _LARGEFILE_SOURCE 1
71#endif
72
73/*
74** Include the configuration header output by 'configure' if we're using the
75** autoconf-based build
76*/
77#ifdef _HAVE_SQLITE_CONFIG_H
78#include "config.h"
79#endif
80
81/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82/************** Begin file sqliteLimit.h *************************************/
83/*
84** 2007 May 7
85**
86** The author disclaims copyright to this source code.  In place of
87** a legal notice, here is a blessing:
88**
89**    May you do good and not evil.
90**    May you find forgiveness for yourself and forgive others.
91**    May you share freely, never taking more than you give.
92**
93*************************************************************************
94**
95** This file defines various limits of what SQLite can process.
96*/
97
98/*
99** The maximum length of a TEXT or BLOB in bytes.   This also
100** limits the size of a row in a table or index.
101**
102** The hard limit is the ability of a 32-bit signed integer
103** to count the size: 2^31-1 or 2147483647.
104*/
105#ifndef SQLITE_MAX_LENGTH
106# define SQLITE_MAX_LENGTH 1000000000
107#endif
108
109/*
110** This is the maximum number of
111**
112**    * Columns in a table
113**    * Columns in an index
114**    * Columns in a view
115**    * Terms in the SET clause of an UPDATE statement
116**    * Terms in the result set of a SELECT statement
117**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118**    * Terms in the VALUES clause of an INSERT statement
119**
120** The hard upper limit here is 32676.  Most database people will
121** tell you that in a well-normalized database, you usually should
122** not have more than a dozen or so columns in any table.  And if
123** that is the case, there is no point in having more than a few
124** dozen values in any of the other situations described above.
125*/
126#ifndef SQLITE_MAX_COLUMN
127# define SQLITE_MAX_COLUMN 2000
128#endif
129
130/*
131** The maximum length of a single SQL statement in bytes.
132**
133** It used to be the case that setting this value to zero would
134** turn the limit off.  That is no longer true.  It is not possible
135** to turn this limit off.
136*/
137#ifndef SQLITE_MAX_SQL_LENGTH
138# define SQLITE_MAX_SQL_LENGTH 1000000000
139#endif
140
141/*
142** The maximum depth of an expression tree. This is limited to
143** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
144** want to place more severe limits on the complexity of an
145** expression.
146**
147** A value of 0 used to mean that the limit was not enforced.
148** But that is no longer true.  The limit is now strictly enforced
149** at all times.
150*/
151#ifndef SQLITE_MAX_EXPR_DEPTH
152# define SQLITE_MAX_EXPR_DEPTH 1000
153#endif
154
155/*
156** The maximum number of terms in a compound SELECT statement.
157** The code generator for compound SELECT statements does one
158** level of recursion for each term.  A stack overflow can result
159** if the number of terms is too large.  In practice, most SQL
160** never has more than 3 or 4 terms.  Use a value of 0 to disable
161** any limit on the number of terms in a compount SELECT.
162*/
163#ifndef SQLITE_MAX_COMPOUND_SELECT
164# define SQLITE_MAX_COMPOUND_SELECT 500
165#endif
166
167/*
168** The maximum number of opcodes in a VDBE program.
169** Not currently enforced.
170*/
171#ifndef SQLITE_MAX_VDBE_OP
172# define SQLITE_MAX_VDBE_OP 25000
173#endif
174
175/*
176** The maximum number of arguments to an SQL function.
177*/
178#ifndef SQLITE_MAX_FUNCTION_ARG
179# define SQLITE_MAX_FUNCTION_ARG 127
180#endif
181
182/*
183** The maximum number of in-memory pages to use for the main database
184** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185*/
186#ifndef SQLITE_DEFAULT_CACHE_SIZE
187# define SQLITE_DEFAULT_CACHE_SIZE  2000
188#endif
189#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191#endif
192
193/*
194** The 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 30.  The upper bound on 30 is because a 32-bit integer bitmap
204** is used internally to track attached databases.
205*/
206#ifndef SQLITE_MAX_ATTACHED
207# define SQLITE_MAX_ATTACHED 10
208#endif
209
210
211/*
212** The maximum value of a ?nnn wildcard that the parser will accept.
213*/
214#ifndef SQLITE_MAX_VARIABLE_NUMBER
215# define SQLITE_MAX_VARIABLE_NUMBER 999
216#endif
217
218/* Maximum page size.  The upper bound on this value is 65536.  This a limit
219** imposed by the use of 16-bit offsets within each page.
220**
221** Earlier versions of SQLite allowed the user to change this value at
222** compile time. This is no longer permitted, on the grounds that it creates
223** a library that is technically incompatible with an SQLite library
224** compiled with a different limit. If a process operating on a database
225** with a page-size of 65536 bytes crashes, then an instance of SQLite
226** compiled with the default page-size limit will not be able to rollback
227** the aborted transaction. This could lead to database corruption.
228*/
229#ifdef SQLITE_MAX_PAGE_SIZE
230# undef SQLITE_MAX_PAGE_SIZE
231#endif
232#define SQLITE_MAX_PAGE_SIZE 65536
233
234
235/*
236** The default size of a database page.
237*/
238#ifndef SQLITE_DEFAULT_PAGE_SIZE
239# define SQLITE_DEFAULT_PAGE_SIZE 1024
240#endif
241#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242# undef SQLITE_DEFAULT_PAGE_SIZE
243# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244#endif
245
246/*
247** Ordinarily, if no value is explicitly provided, SQLite creates databases
248** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249** device characteristics (sector-size and atomic write() support),
250** SQLite may choose a larger value. This constant is the maximum value
251** SQLite will choose on its own.
252*/
253#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255#endif
256#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259#endif
260
261
262/*
263** Maximum number of pages in one database file.
264**
265** This is really just the default value for the max_page_count pragma.
266** This value can be lowered (or raised) at run-time using that the
267** max_page_count macro.
268*/
269#ifndef SQLITE_MAX_PAGE_COUNT
270# define SQLITE_MAX_PAGE_COUNT 1073741823
271#endif
272
273/*
274** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275** operator.
276*/
277#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279#endif
280
281/*
282** Maximum depth of recursion for triggers.
283**
284** A value of 1 means that a trigger program will not be able to itself
285** fire any triggers. A value of 0 means that no trigger programs at all
286** may be executed.
287*/
288#ifndef SQLITE_MAX_TRIGGER_DEPTH
289# define SQLITE_MAX_TRIGGER_DEPTH 1000
290#endif
291
292/************** End of sqliteLimit.h *****************************************/
293/************** Continuing where we left off in sqliteInt.h ******************/
294
295/* Disable nuisance warnings on Borland compilers */
296#if defined(__BORLANDC__)
297#pragma warn -rch /* unreachable code */
298#pragma warn -ccc /* Condition is always true or false */
299#pragma warn -aus /* Assigned value is never used */
300#pragma warn -csu /* Comparing signed and unsigned */
301#pragma warn -spa /* Suspicious pointer arithmetic */
302#endif
303
304/* Needed for various definitions... */
305#ifndef _GNU_SOURCE
306# define _GNU_SOURCE
307#endif
308
309/*
310** Include standard header files as necessary
311*/
312#ifdef HAVE_STDINT_H
313#include <stdint.h>
314#endif
315#ifdef HAVE_INTTYPES_H
316#include <inttypes.h>
317#endif
318
319/*
320** The number of samples of an index that SQLite takes in order to
321** construct a histogram of the table content when running ANALYZE
322** and with SQLITE_ENABLE_STAT2
323*/
324#define SQLITE_INDEX_SAMPLES 10
325
326/*
327** The following macros are used to cast pointers to integers and
328** integers to pointers.  The way you do this varies from one compiler
329** to the next, so we have developed the following set of #if statements
330** to generate appropriate macros for a wide range of compilers.
331**
332** The correct "ANSI" way to do this is to use the intptr_t type.
333** Unfortunately, that typedef is not available on all compilers, or
334** if it is available, it requires an #include of specific headers
335** that vary from one machine to the next.
336**
337** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339** So we have to define the macros in different ways depending on the
340** compiler.
341*/
342#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351#else                          /* Generates a warning - but it always works */
352# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353# define SQLITE_PTR_TO_INT(X)  ((int)(X))
354#endif
355
356/*
357** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
358** Older versions of SQLite used an optional THREADSAFE macro.
359** We support that for legacy
360*/
361#if !defined(SQLITE_THREADSAFE)
362#if defined(THREADSAFE)
363# define SQLITE_THREADSAFE THREADSAFE
364#else
365# define SQLITE_THREADSAFE 1
366#endif
367#endif
368
369/*
370** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
371** It determines whether or not the features related to
372** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
373** be overridden at runtime using the sqlite3_config() API.
374*/
375#if !defined(SQLITE_DEFAULT_MEMSTATUS)
376# define SQLITE_DEFAULT_MEMSTATUS 1
377#endif
378
379/*
380** Exactly one of the following macros must be defined in order to
381** specify which memory allocation subsystem to use.
382**
383**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
384**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
385**
386** (Historical note:  There used to be several other options, but we've
387** pared it down to just these two.)
388**
389** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
390** the default.
391*/
392#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
393# error "At most one of the following compile-time configuration options\
394 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
395#endif
396#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
397# define SQLITE_SYSTEM_MALLOC 1
398#endif
399
400/*
401** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
402** sizes of memory allocations below this value where possible.
403*/
404#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
405# define SQLITE_MALLOC_SOFT_LIMIT 1024
406#endif
407
408/*
409** We need to define _XOPEN_SOURCE as follows in order to enable
410** recursive mutexes on most Unix systems.  But Mac OS X is different.
411** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
412** so it is omitted there.  See ticket #2673.
413**
414** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
415** implemented on some systems.  So we avoid defining it at all
416** if it is already defined or if it is unneeded because we are
417** not doing a threadsafe build.  Ticket #2681.
418**
419** See also ticket #2741.
420*/
421#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
422#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
423#endif
424
425/*
426** The TCL headers are only needed when compiling the TCL bindings.
427*/
428#if defined(SQLITE_TCL) || defined(TCLSH)
429# include <tcl.h>
430#endif
431
432/*
433** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
434** Setting NDEBUG makes the code smaller and run faster.  So the following
435** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
436** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
437** feature.
438*/
439#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
440# define NDEBUG 1
441#endif
442
443/*
444** The testcase() macro is used to aid in coverage testing.  When
445** doing coverage testing, the condition inside the argument to
446** testcase() must be evaluated both true and false in order to
447** get full branch coverage.  The testcase() macro is inserted
448** to help ensure adequate test coverage in places where simple
449** condition/decision coverage is inadequate.  For example, testcase()
450** can be used to make sure boundary values are tested.  For
451** bitmask tests, testcase() can be used to make sure each bit
452** is significant and used at least once.  On switch statements
453** where multiple cases go to the same block of code, testcase()
454** can insure that all cases are evaluated.
455**
456*/
457#ifdef SQLITE_COVERAGE_TEST
458SQLITE_PRIVATE   void sqlite3Coverage(int);
459# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
460#else
461# define testcase(X)
462#endif
463
464/*
465** The TESTONLY macro is used to enclose variable declarations or
466** other bits of code that are needed to support the arguments
467** within testcase() and assert() macros.
468*/
469#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
470# define TESTONLY(X)  X
471#else
472# define TESTONLY(X)
473#endif
474
475/*
476** Sometimes we need a small amount of code such as a variable initialization
477** to setup for a later assert() statement.  We do not want this code to
478** appear when assert() is disabled.  The following macro is therefore
479** used to contain that setup code.  The "VVA" acronym stands for
480** "Verification, Validation, and Accreditation".  In other words, the
481** code within VVA_ONLY() will only run during verification processes.
482*/
483#ifndef NDEBUG
484# define VVA_ONLY(X)  X
485#else
486# define VVA_ONLY(X)
487#endif
488
489/*
490** The ALWAYS and NEVER macros surround boolean expressions which
491** are intended to always be true or false, respectively.  Such
492** expressions could be omitted from the code completely.  But they
493** are included in a few cases in order to enhance the resilience
494** of SQLite to unexpected behavior - to make the code "self-healing"
495** or "ductile" rather than being "brittle" and crashing at the first
496** hint of unplanned behavior.
497**
498** In other words, ALWAYS and NEVER are added for defensive code.
499**
500** When doing coverage testing ALWAYS and NEVER are hard-coded to
501** be true and false so that the unreachable code then specify will
502** not be counted as untested code.
503*/
504#if defined(SQLITE_COVERAGE_TEST)
505# define ALWAYS(X)      (1)
506# define NEVER(X)       (0)
507#elif !defined(NDEBUG)
508# define ALWAYS(X)      ((X)?1:(assert(0),0))
509# define NEVER(X)       ((X)?(assert(0),1):0)
510#else
511# define ALWAYS(X)      (X)
512# define NEVER(X)       (X)
513#endif
514
515/*
516** Return true (non-zero) if the input is a integer that is too large
517** to fit in 32-bits.  This macro is used inside of various testcase()
518** macros to verify that we have tested SQLite for large-file support.
519*/
520#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
521
522/*
523** The macro unlikely() is a hint that surrounds a boolean
524** expression that is usually false.  Macro likely() surrounds
525** a boolean expression that is usually true.  GCC is able to
526** use these hints to generate better code, sometimes.
527*/
528#if defined(__GNUC__) && 0
529# define likely(X)    __builtin_expect((X),1)
530# define unlikely(X)  __builtin_expect((X),0)
531#else
532# define likely(X)    !!(X)
533# define unlikely(X)  !!(X)
534#endif
535
536/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
537/************** Begin file sqlite3.h *****************************************/
538/*
539** 2001 September 15
540**
541** The author disclaims copyright to this source code.  In place of
542** a legal notice, here is a blessing:
543**
544**    May you do good and not evil.
545**    May you find forgiveness for yourself and forgive others.
546**    May you share freely, never taking more than you give.
547**
548*************************************************************************
549** This header file defines the interface that the SQLite library
550** presents to client programs.  If a C-function, structure, datatype,
551** or constant definition does not appear in this file, then it is
552** not a published API of SQLite, is subject to change without
553** notice, and should not be referenced by programs that use SQLite.
554**
555** Some of the definitions that are in this file are marked as
556** "experimental".  Experimental interfaces are normally new
557** features recently added to SQLite.  We do not anticipate changes
558** to experimental interfaces but reserve the right to make minor changes
559** if experience from use "in the wild" suggest such changes are prudent.
560**
561** The official C-language API documentation for SQLite is derived
562** from comments in this file.  This file is the authoritative source
563** on how SQLite interfaces are suppose to operate.
564**
565** The name of this file under configuration management is "sqlite.h.in".
566** The makefile makes some minor changes to this file (such as inserting
567** the version number) and changes its name to "sqlite3.h" as
568** part of the build process.
569*/
570#ifndef _SQLITE3_H_
571#define _SQLITE3_H_
572#include <stdarg.h>     /* Needed for the definition of va_list */
573
574/*
575** Make sure we can call this stuff from C++.
576*/
577#if 0
578extern "C" {
579#endif
580
581
582/*
583** Add the ability to override 'extern'
584*/
585#ifndef SQLITE_EXTERN
586# define SQLITE_EXTERN extern
587#endif
588
589#ifndef SQLITE_API
590# define SQLITE_API
591#endif
592
593
594/*
595** These no-op macros are used in front of interfaces to mark those
596** interfaces as either deprecated or experimental.  New applications
597** should not use deprecated interfaces - they are support for backwards
598** compatibility only.  Application writers should be aware that
599** experimental interfaces are subject to change in point releases.
600**
601** These macros used to resolve to various kinds of compiler magic that
602** would generate warning messages when they were used.  But that
603** compiler magic ended up generating such a flurry of bug reports
604** that we have taken it all out and gone back to using simple
605** noop macros.
606*/
607#define SQLITE_DEPRECATED
608#define SQLITE_EXPERIMENTAL
609
610/*
611** Ensure these symbols were not defined by some previous header file.
612*/
613#ifdef SQLITE_VERSION
614# undef SQLITE_VERSION
615#endif
616#ifdef SQLITE_VERSION_NUMBER
617# undef SQLITE_VERSION_NUMBER
618#endif
619
620/*
621** CAPI3REF: Compile-Time Library Version Numbers
622**
623** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
624** evaluates to a string literal that is the SQLite version in the
625** format "X.Y.Z" where X is the major version number (always 3 for
626** SQLite3) and Y is the minor version number and Z is the release number.)^
627** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
628** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
629** numbers used in [SQLITE_VERSION].)^
630** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
631** be larger than the release from which it is derived.  Either Y will
632** be held constant and Z will be incremented or else Y will be incremented
633** and Z will be reset to zero.
634**
635** Since version 3.6.18, SQLite source code has been stored in the
636** <a href="http://www.fossil-scm.org/">Fossil configuration management
637** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
638** a string which identifies a particular check-in of SQLite
639** within its configuration management system.  ^The SQLITE_SOURCE_ID
640** string contains the date and time of the check-in (UTC) and an SHA1
641** hash of the entire source tree.
642**
643** See also: [sqlite3_libversion()],
644** [sqlite3_libversion_number()], [sqlite3_sourceid()],
645** [sqlite_version()] and [sqlite_source_id()].
646*/
647#define SQLITE_VERSION        "3.7.2"
648#define SQLITE_VERSION_NUMBER 3007002
649#define SQLITE_SOURCE_ID      "2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3"
650
651/*
652** CAPI3REF: Run-Time Library Version Numbers
653** KEYWORDS: sqlite3_version, sqlite3_sourceid
654**
655** These interfaces provide the same information as the [SQLITE_VERSION],
656** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
657** but are associated with the library instead of the header file.  ^(Cautious
658** programmers might include assert() statements in their application to
659** verify that values returned by these interfaces match the macros in
660** the header, and thus insure that the application is
661** compiled with matching library and header files.
662**
663** <blockquote><pre>
664** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
665** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
666** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
667** </pre></blockquote>)^
668**
669** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
670** macro.  ^The sqlite3_libversion() function returns a pointer to the
671** to the sqlite3_version[] string constant.  The sqlite3_libversion()
672** function is provided for use in DLLs since DLL users usually do not have
673** direct access to string constants within the DLL.  ^The
674** sqlite3_libversion_number() function returns an integer equal to
675** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
676** a pointer to a string constant whose value is the same as the
677** [SQLITE_SOURCE_ID] C preprocessor macro.
678**
679** See also: [sqlite_version()] and [sqlite_source_id()].
680*/
681SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
682SQLITE_API const char *sqlite3_libversion(void);
683SQLITE_API const char *sqlite3_sourceid(void);
684SQLITE_API int sqlite3_libversion_number(void);
685
686/*
687** CAPI3REF: Run-Time Library Compilation Options Diagnostics
688**
689** ^The sqlite3_compileoption_used() function returns 0 or 1
690** indicating whether the specified option was defined at
691** compile time.  ^The SQLITE_ prefix may be omitted from the
692** option name passed to sqlite3_compileoption_used().
693**
694** ^The sqlite3_compileoption_get() function allows iterating
695** over the list of options that were defined at compile time by
696** returning the N-th compile time option string.  ^If N is out of range,
697** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
698** prefix is omitted from any strings returned by
699** sqlite3_compileoption_get().
700**
701** ^Support for the diagnostic functions sqlite3_compileoption_used()
702** and sqlite3_compileoption_get() may be omitted by specifying the
703** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
704**
705** See also: SQL functions [sqlite_compileoption_used()] and
706** [sqlite_compileoption_get()] and the [compile_options pragma].
707*/
708#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
709SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
710SQLITE_API const char *sqlite3_compileoption_get(int N);
711#endif
712
713/*
714** CAPI3REF: Test To See If The Library Is Threadsafe
715**
716** ^The sqlite3_threadsafe() function returns zero if and only if
717** SQLite was compiled mutexing code omitted due to the
718** [SQLITE_THREADSAFE] compile-time option being set to 0.
719**
720** SQLite can be compiled with or without mutexes.  When
721** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
722** are enabled and SQLite is threadsafe.  When the
723** [SQLITE_THREADSAFE] macro is 0,
724** the mutexes are omitted.  Without the mutexes, it is not safe
725** to use SQLite concurrently from more than one thread.
726**
727** Enabling mutexes incurs a measurable performance penalty.
728** So if speed is of utmost importance, it makes sense to disable
729** the mutexes.  But for maximum safety, mutexes should be enabled.
730** ^The default behavior is for mutexes to be enabled.
731**
732** This interface can be used by an application to make sure that the
733** version of SQLite that it is linking against was compiled with
734** the desired setting of the [SQLITE_THREADSAFE] macro.
735**
736** This interface only reports on the compile-time mutex setting
737** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
738** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
739** can be fully or partially disabled using a call to [sqlite3_config()]
740** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
741** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
742** sqlite3_threadsafe() function shows only the compile-time setting of
743** thread safety, not any run-time changes to that setting made by
744** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
745** is unchanged by calls to sqlite3_config().)^
746**
747** See the [threading mode] documentation for additional information.
748*/
749SQLITE_API int sqlite3_threadsafe(void);
750
751/*
752** CAPI3REF: Database Connection Handle
753** KEYWORDS: {database connection} {database connections}
754**
755** Each open SQLite database is represented by a pointer to an instance of
756** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
757** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
758** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
759** is its destructor.  There are many other interfaces (such as
760** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
761** [sqlite3_busy_timeout()] to name but three) that are methods on an
762** sqlite3 object.
763*/
764typedef struct sqlite3 sqlite3;
765
766/*
767** CAPI3REF: 64-Bit Integer Types
768** KEYWORDS: sqlite_int64 sqlite_uint64
769**
770** Because there is no cross-platform way to specify 64-bit integer types
771** SQLite includes typedefs for 64-bit signed and unsigned integers.
772**
773** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
774** The sqlite_int64 and sqlite_uint64 types are supported for backwards
775** compatibility only.
776**
777** ^The sqlite3_int64 and sqlite_int64 types can store integer values
778** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
779** sqlite3_uint64 and sqlite_uint64 types can store integer values
780** between 0 and +18446744073709551615 inclusive.
781*/
782#ifdef SQLITE_INT64_TYPE
783  typedef SQLITE_INT64_TYPE sqlite_int64;
784  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
785#elif defined(_MSC_VER) || defined(__BORLANDC__)
786  typedef __int64 sqlite_int64;
787  typedef unsigned __int64 sqlite_uint64;
788#else
789  typedef long long int sqlite_int64;
790  typedef unsigned long long int sqlite_uint64;
791#endif
792typedef sqlite_int64 sqlite3_int64;
793typedef sqlite_uint64 sqlite3_uint64;
794
795/*
796** If compiling for a processor that lacks floating point support,
797** substitute integer for floating-point.
798*/
799#ifdef SQLITE_OMIT_FLOATING_POINT
800# define double sqlite3_int64
801#endif
802
803/*
804** CAPI3REF: Closing A Database Connection
805**
806** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
807** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
808** successfully destroyed and all associated resources are deallocated.
809**
810** Applications must [sqlite3_finalize | finalize] all [prepared statements]
811** and [sqlite3_blob_close | close] all [BLOB handles] associated with
812** the [sqlite3] object prior to attempting to close the object.  ^If
813** sqlite3_close() is called on a [database connection] that still has
814** outstanding [prepared statements] or [BLOB handles], then it returns
815** SQLITE_BUSY.
816**
817** ^If [sqlite3_close()] is invoked while a transaction is open,
818** the transaction is automatically rolled back.
819**
820** The C parameter to [sqlite3_close(C)] must be either a NULL
821** pointer or an [sqlite3] object pointer obtained
822** from [sqlite3_open()], [sqlite3_open16()], or
823** [sqlite3_open_v2()], and not previously closed.
824** ^Calling sqlite3_close() with a NULL pointer argument is a
825** harmless no-op.
826*/
827SQLITE_API int sqlite3_close(sqlite3 *);
828
829/*
830** The type for a callback function.
831** This is legacy and deprecated.  It is included for historical
832** compatibility and is not documented.
833*/
834typedef int (*sqlite3_callback)(void*,int,char**, char**);
835
836/*
837** CAPI3REF: One-Step Query Execution Interface
838**
839** The sqlite3_exec() interface is a convenience wrapper around
840** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
841** that allows an application to run multiple statements of SQL
842** without having to use a lot of C code.
843**
844** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
845** semicolon-separate SQL statements passed into its 2nd argument,
846** in the context of the [database connection] passed in as its 1st
847** argument.  ^If the callback function of the 3rd argument to
848** sqlite3_exec() is not NULL, then it is invoked for each result row
849** coming out of the evaluated SQL statements.  ^The 4th argument to
850** to sqlite3_exec() is relayed through to the 1st argument of each
851** callback invocation.  ^If the callback pointer to sqlite3_exec()
852** is NULL, then no callback is ever invoked and result rows are
853** ignored.
854**
855** ^If an error occurs while evaluating the SQL statements passed into
856** sqlite3_exec(), then execution of the current statement stops and
857** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
858** is not NULL then any error message is written into memory obtained
859** from [sqlite3_malloc()] and passed back through the 5th parameter.
860** To avoid memory leaks, the application should invoke [sqlite3_free()]
861** on error message strings returned through the 5th parameter of
862** of sqlite3_exec() after the error message string is no longer needed.
863** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
864** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
865** NULL before returning.
866**
867** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
868** routine returns SQLITE_ABORT without invoking the callback again and
869** without running any subsequent SQL statements.
870**
871** ^The 2nd argument to the sqlite3_exec() callback function is the
872** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
873** callback is an array of pointers to strings obtained as if from
874** [sqlite3_column_text()], one for each column.  ^If an element of a
875** result row is NULL then the corresponding string pointer for the
876** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
877** sqlite3_exec() callback is an array of pointers to strings where each
878** entry represents the name of corresponding result column as obtained
879** from [sqlite3_column_name()].
880**
881** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
882** to an empty string, or a pointer that contains only whitespace and/or
883** SQL comments, then no SQL statements are evaluated and the database
884** is not changed.
885**
886** Restrictions:
887**
888** <ul>
889** <li> The application must insure that the 1st parameter to sqlite3_exec()
890**      is a valid and open [database connection].
891** <li> The application must not close [database connection] specified by
892**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
893** <li> The application must not modify the SQL statement text passed into
894**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
895** </ul>
896*/
897SQLITE_API int sqlite3_exec(
898  sqlite3*,                                  /* An open database */
899  const char *sql,                           /* SQL to be evaluated */
900  int (*callback)(void*,int,char**,char**),  /* Callback function */
901  void *,                                    /* 1st argument to callback */
902  char **errmsg                              /* Error msg written here */
903);
904
905/*
906** CAPI3REF: Result Codes
907** KEYWORDS: SQLITE_OK {error code} {error codes}
908** KEYWORDS: {result code} {result codes}
909**
910** Many SQLite functions return an integer result code from the set shown
911** here in order to indicates success or failure.
912**
913** New error codes may be added in future versions of SQLite.
914**
915** See also: [SQLITE_IOERR_READ | extended result codes]
916*/
917#define SQLITE_OK           0   /* Successful result */
918/* beginning-of-error-codes */
919#define SQLITE_ERROR        1   /* SQL error or missing database */
920#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
921#define SQLITE_PERM         3   /* Access permission denied */
922#define SQLITE_ABORT        4   /* Callback routine requested an abort */
923#define SQLITE_BUSY         5   /* The database file is locked */
924#define SQLITE_LOCKED       6   /* A table in the database is locked */
925#define SQLITE_NOMEM        7   /* A malloc() failed */
926#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
927#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
928#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
929#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
930#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
931#define SQLITE_FULL        13   /* Insertion failed because database is full */
932#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
933#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
934#define SQLITE_EMPTY       16   /* Database is empty */
935#define SQLITE_SCHEMA      17   /* The database schema changed */
936#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
937#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
938#define SQLITE_MISMATCH    20   /* Data type mismatch */
939#define SQLITE_MISUSE      21   /* Library used incorrectly */
940#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
941#define SQLITE_AUTH        23   /* Authorization denied */
942#define SQLITE_FORMAT      24   /* Auxiliary database format error */
943#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
944#define SQLITE_NOTADB      26   /* File opened that is not a database file */
945#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
946#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
947/* end-of-error-codes */
948
949/*
950** CAPI3REF: Extended Result Codes
951** KEYWORDS: {extended error code} {extended error codes}
952** KEYWORDS: {extended result code} {extended result codes}
953**
954** In its default configuration, SQLite API routines return one of 26 integer
955** [SQLITE_OK | result codes].  However, experience has shown that many of
956** these result codes are too coarse-grained.  They do not provide as
957** much information about problems as programmers might like.  In an effort to
958** address this, newer versions of SQLite (version 3.3.8 and later) include
959** support for additional result codes that provide more detailed information
960** about errors. The extended result codes are enabled or disabled
961** on a per database connection basis using the
962** [sqlite3_extended_result_codes()] API.
963**
964** Some of the available extended result codes are listed here.
965** One may expect the number of extended result codes will be expand
966** over time.  Software that uses extended result codes should expect
967** to see new result codes in future releases of SQLite.
968**
969** The SQLITE_OK result code will never be extended.  It will always
970** be exactly zero.
971*/
972#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
973#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
974#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
975#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
976#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
977#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
978#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
979#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
980#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
981#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
982#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
983#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
984#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
985#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
986#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
987#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
988#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
989#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
990#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
991#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
992#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
993#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
994#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
995
996/*
997** CAPI3REF: Flags For File Open Operations
998**
999** These bit values are intended for use in the
1000** 3rd parameter to the [sqlite3_open_v2()] interface and
1001** in the 4th parameter to the xOpen method of the
1002** [sqlite3_vfs] object.
1003*/
1004#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1005#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1006#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1007#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1008#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1009#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1010#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1011#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1012#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1013#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1014#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1015#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1016#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1017#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1018#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1019#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1020#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1021#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1022
1023/*
1024** CAPI3REF: Device Characteristics
1025**
1026** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1027** object returns an integer which is a vector of the these
1028** bit values expressing I/O characteristics of the mass storage
1029** device that holds the file that the [sqlite3_io_methods]
1030** refers to.
1031**
1032** The SQLITE_IOCAP_ATOMIC property means that all writes of
1033** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1034** mean that writes of blocks that are nnn bytes in size and
1035** are aligned to an address which is an integer multiple of
1036** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1037** that when data is appended to a file, the data is appended
1038** first then the size of the file is extended, never the other
1039** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1040** information is written to disk in the same order as calls
1041** to xWrite().
1042*/
1043#define SQLITE_IOCAP_ATOMIC                 0x00000001
1044#define SQLITE_IOCAP_ATOMIC512              0x00000002
1045#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1046#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1047#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1048#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1049#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1050#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1051#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1052#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1053#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1054#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1055
1056/*
1057** CAPI3REF: File Locking Levels
1058**
1059** SQLite uses one of these integer values as the second
1060** argument to calls it makes to the xLock() and xUnlock() methods
1061** of an [sqlite3_io_methods] object.
1062*/
1063#define SQLITE_LOCK_NONE          0
1064#define SQLITE_LOCK_SHARED        1
1065#define SQLITE_LOCK_RESERVED      2
1066#define SQLITE_LOCK_PENDING       3
1067#define SQLITE_LOCK_EXCLUSIVE     4
1068
1069/*
1070** CAPI3REF: Synchronization Type Flags
1071**
1072** When SQLite invokes the xSync() method of an
1073** [sqlite3_io_methods] object it uses a combination of
1074** these integer values as the second argument.
1075**
1076** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1077** sync operation only needs to flush data to mass storage.  Inode
1078** information need not be flushed. If the lower four bits of the flag
1079** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1080** If the lower four bits equal SQLITE_SYNC_FULL, that means
1081** to use Mac OS X style fullsync instead of fsync().
1082*/
1083#define SQLITE_SYNC_NORMAL        0x00002
1084#define SQLITE_SYNC_FULL          0x00003
1085#define SQLITE_SYNC_DATAONLY      0x00010
1086
1087/*
1088** CAPI3REF: OS Interface Open File Handle
1089**
1090** An [sqlite3_file] object represents an open file in the
1091** [sqlite3_vfs | OS interface layer].  Individual OS interface
1092** implementations will
1093** want to subclass this object by appending additional fields
1094** for their own use.  The pMethods entry is a pointer to an
1095** [sqlite3_io_methods] object that defines methods for performing
1096** I/O operations on the open file.
1097*/
1098typedef struct sqlite3_file sqlite3_file;
1099struct sqlite3_file {
1100  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1101};
1102
1103/*
1104** CAPI3REF: OS Interface File Virtual Methods Object
1105**
1106** Every file opened by the [sqlite3_vfs] xOpen method populates an
1107** [sqlite3_file] object (or, more commonly, a subclass of the
1108** [sqlite3_file] object) with a pointer to an instance of this object.
1109** This object defines the methods used to perform various operations
1110** against the open file represented by the [sqlite3_file] object.
1111**
1112** If the xOpen method sets the sqlite3_file.pMethods element
1113** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1114** may be invoked even if the xOpen reported that it failed.  The
1115** only way to prevent a call to xClose following a failed xOpen
1116** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1117**
1118** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1119** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1120** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1121** flag may be ORed in to indicate that only the data of the file
1122** and not its inode needs to be synced.
1123**
1124** The integer values to xLock() and xUnlock() are one of
1125** <ul>
1126** <li> [SQLITE_LOCK_NONE],
1127** <li> [SQLITE_LOCK_SHARED],
1128** <li> [SQLITE_LOCK_RESERVED],
1129** <li> [SQLITE_LOCK_PENDING], or
1130** <li> [SQLITE_LOCK_EXCLUSIVE].
1131** </ul>
1132** xLock() increases the lock. xUnlock() decreases the lock.
1133** The xCheckReservedLock() method checks whether any database connection,
1134** either in this process or in some other process, is holding a RESERVED,
1135** PENDING, or EXCLUSIVE lock on the file.  It returns true
1136** if such a lock exists and false otherwise.
1137**
1138** The xFileControl() method is a generic interface that allows custom
1139** VFS implementations to directly control an open file using the
1140** [sqlite3_file_control()] interface.  The second "op" argument is an
1141** integer opcode.  The third argument is a generic pointer intended to
1142** point to a structure that may contain arguments or space in which to
1143** write return values.  Potential uses for xFileControl() might be
1144** functions to enable blocking locks with timeouts, to change the
1145** locking strategy (for example to use dot-file locks), to inquire
1146** about the status of a lock, or to break stale locks.  The SQLite
1147** core reserves all opcodes less than 100 for its own use.
1148** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1149** Applications that define a custom xFileControl method should use opcodes
1150** greater than 100 to avoid conflicts.
1151**
1152** The xSectorSize() method returns the sector size of the
1153** device that underlies the file.  The sector size is the
1154** minimum write that can be performed without disturbing
1155** other bytes in the file.  The xDeviceCharacteristics()
1156** method returns a bit vector describing behaviors of the
1157** underlying device:
1158**
1159** <ul>
1160** <li> [SQLITE_IOCAP_ATOMIC]
1161** <li> [SQLITE_IOCAP_ATOMIC512]
1162** <li> [SQLITE_IOCAP_ATOMIC1K]
1163** <li> [SQLITE_IOCAP_ATOMIC2K]
1164** <li> [SQLITE_IOCAP_ATOMIC4K]
1165** <li> [SQLITE_IOCAP_ATOMIC8K]
1166** <li> [SQLITE_IOCAP_ATOMIC16K]
1167** <li> [SQLITE_IOCAP_ATOMIC32K]
1168** <li> [SQLITE_IOCAP_ATOMIC64K]
1169** <li> [SQLITE_IOCAP_SAFE_APPEND]
1170** <li> [SQLITE_IOCAP_SEQUENTIAL]
1171** </ul>
1172**
1173** The SQLITE_IOCAP_ATOMIC property means that all writes of
1174** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1175** mean that writes of blocks that are nnn bytes in size and
1176** are aligned to an address which is an integer multiple of
1177** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1178** that when data is appended to a file, the data is appended
1179** first then the size of the file is extended, never the other
1180** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1181** information is written to disk in the same order as calls
1182** to xWrite().
1183**
1184** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1185** in the unread portions of the buffer with zeros.  A VFS that
1186** fails to zero-fill short reads might seem to work.  However,
1187** failure to zero-fill short reads will eventually lead to
1188** database corruption.
1189*/
1190typedef struct sqlite3_io_methods sqlite3_io_methods;
1191struct sqlite3_io_methods {
1192  int iVersion;
1193  int (*xClose)(sqlite3_file*);
1194  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1195  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1196  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1197  int (*xSync)(sqlite3_file*, int flags);
1198  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1199  int (*xLock)(sqlite3_file*, int);
1200  int (*xUnlock)(sqlite3_file*, int);
1201  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1202  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1203  int (*xSectorSize)(sqlite3_file*);
1204  int (*xDeviceCharacteristics)(sqlite3_file*);
1205  /* Methods above are valid for version 1 */
1206  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1207  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1208  void (*xShmBarrier)(sqlite3_file*);
1209  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1210  /* Methods above are valid for version 2 */
1211  /* Additional methods may be added in future releases */
1212};
1213
1214/*
1215** CAPI3REF: Standard File Control Opcodes
1216**
1217** These integer constants are opcodes for the xFileControl method
1218** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1219** interface.
1220**
1221** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1222** opcode causes the xFileControl method to write the current state of
1223** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1224** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1225** into an integer that the pArg argument points to. This capability
1226** is used during testing and only needs to be supported when SQLITE_TEST
1227** is defined.
1228**
1229** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1230** layer a hint of how large the database file will grow to be during the
1231** current transaction.  This hint is not guaranteed to be accurate but it
1232** is often close.  The underlying VFS might choose to preallocate database
1233** file space based on this hint in order to help writes to the database
1234** file run faster.
1235**
1236** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1237** extends and truncates the database file in chunks of a size specified
1238** by the user. The fourth argument to [sqlite3_file_control()] should
1239** point to an integer (type int) containing the new chunk-size to use
1240** for the nominated database. Allocating database file space in large
1241** chunks (say 1MB at a time), may reduce file-system fragmentation and
1242** improve performance on some systems.
1243*/
1244#define SQLITE_FCNTL_LOCKSTATE        1
1245#define SQLITE_GET_LOCKPROXYFILE      2
1246#define SQLITE_SET_LOCKPROXYFILE      3
1247#define SQLITE_LAST_ERRNO             4
1248#define SQLITE_FCNTL_SIZE_HINT        5
1249#define SQLITE_FCNTL_CHUNK_SIZE       6
1250
1251/*
1252** CAPI3REF: Mutex Handle
1253**
1254** The mutex module within SQLite defines [sqlite3_mutex] to be an
1255** abstract type for a mutex object.  The SQLite core never looks
1256** at the internal representation of an [sqlite3_mutex].  It only
1257** deals with pointers to the [sqlite3_mutex] object.
1258**
1259** Mutexes are created using [sqlite3_mutex_alloc()].
1260*/
1261typedef struct sqlite3_mutex sqlite3_mutex;
1262
1263/*
1264** CAPI3REF: OS Interface Object
1265**
1266** An instance of the sqlite3_vfs object defines the interface between
1267** the SQLite core and the underlying operating system.  The "vfs"
1268** in the name of the object stands for "virtual file system".
1269**
1270** The value of the iVersion field is initially 1 but may be larger in
1271** future versions of SQLite.  Additional fields may be appended to this
1272** object when the iVersion value is increased.  Note that the structure
1273** of the sqlite3_vfs object changes in the transaction between
1274** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1275** modified.
1276**
1277** The szOsFile field is the size of the subclassed [sqlite3_file]
1278** structure used by this VFS.  mxPathname is the maximum length of
1279** a pathname in this VFS.
1280**
1281** Registered sqlite3_vfs objects are kept on a linked list formed by
1282** the pNext pointer.  The [sqlite3_vfs_register()]
1283** and [sqlite3_vfs_unregister()] interfaces manage this list
1284** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1285** searches the list.  Neither the application code nor the VFS
1286** implementation should use the pNext pointer.
1287**
1288** The pNext field is the only field in the sqlite3_vfs
1289** structure that SQLite will ever modify.  SQLite will only access
1290** or modify this field while holding a particular static mutex.
1291** The application should never modify anything within the sqlite3_vfs
1292** object once the object has been registered.
1293**
1294** The zName field holds the name of the VFS module.  The name must
1295** be unique across all VFS modules.
1296**
1297** SQLite will guarantee that the zFilename parameter to xOpen
1298** is either a NULL pointer or string obtained
1299** from xFullPathname().  SQLite further guarantees that
1300** the string will be valid and unchanged until xClose() is
1301** called. Because of the previous sentence,
1302** the [sqlite3_file] can safely store a pointer to the
1303** filename if it needs to remember the filename for some reason.
1304** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1305** must invent its own temporary name for the file.  Whenever the
1306** xFilename parameter is NULL it will also be the case that the
1307** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1308**
1309** The flags argument to xOpen() includes all bits set in
1310** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1311** or [sqlite3_open16()] is used, then flags includes at least
1312** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1313** If xOpen() opens a file read-only then it sets *pOutFlags to
1314** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1315**
1316** SQLite will also add one of the following flags to the xOpen()
1317** call, depending on the object being opened:
1318**
1319** <ul>
1320** <li>  [SQLITE_OPEN_MAIN_DB]
1321** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1322** <li>  [SQLITE_OPEN_TEMP_DB]
1323** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1324** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1325** <li>  [SQLITE_OPEN_SUBJOURNAL]
1326** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1327** </ul>
1328**
1329** The file I/O implementation can use the object type flags to
1330** change the way it deals with files.  For example, an application
1331** that does not care about crash recovery or rollback might make
1332** the open of a journal file a no-op.  Writes to this journal would
1333** also be no-ops, and any attempt to read the journal would return
1334** SQLITE_IOERR.  Or the implementation might recognize that a database
1335** file will be doing page-aligned sector reads and writes in a random
1336** order and set up its I/O subsystem accordingly.
1337**
1338** SQLite might also add one of the following flags to the xOpen method:
1339**
1340** <ul>
1341** <li> [SQLITE_OPEN_DELETEONCLOSE]
1342** <li> [SQLITE_OPEN_EXCLUSIVE]
1343** </ul>
1344**
1345** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1346** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1347** will be set for TEMP  databases, journals and for subjournals.
1348**
1349** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1350** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1351** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1352** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1353** SQLITE_OPEN_CREATE, is used to indicate that file should always
1354** be created, and that it is an error if it already exists.
1355** It is <i>not</i> used to indicate the file should be opened
1356** for exclusive access.
1357**
1358** At least szOsFile bytes of memory are allocated by SQLite
1359** to hold the  [sqlite3_file] structure passed as the third
1360** argument to xOpen.  The xOpen method does not have to
1361** allocate the structure; it should just fill it in.  Note that
1362** the xOpen method must set the sqlite3_file.pMethods to either
1363** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1364** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1365** element will be valid after xOpen returns regardless of the success
1366** or failure of the xOpen call.
1367**
1368** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1369** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1370** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1371** to test whether a file is at least readable.   The file can be a
1372** directory.
1373**
1374** SQLite will always allocate at least mxPathname+1 bytes for the
1375** output buffer xFullPathname.  The exact size of the output buffer
1376** is also passed as a parameter to both  methods. If the output buffer
1377** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1378** handled as a fatal error by SQLite, vfs implementations should endeavor
1379** to prevent this by setting mxPathname to a sufficiently large value.
1380**
1381** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1382** interfaces are not strictly a part of the filesystem, but they are
1383** included in the VFS structure for completeness.
1384** The xRandomness() function attempts to return nBytes bytes
1385** of good-quality randomness into zOut.  The return value is
1386** the actual number of bytes of randomness obtained.
1387** The xSleep() method causes the calling thread to sleep for at
1388** least the number of microseconds given.  The xCurrentTime()
1389** method returns a Julian Day Number for the current date and time as
1390** a floating point value.
1391** The xCurrentTimeInt64() method returns, as an integer, the Julian
1392** Day Number multipled by 86400000 (the number of milliseconds in
1393** a 24-hour day).
1394** ^SQLite will use the xCurrentTimeInt64() method to get the current
1395** date and time if that method is available (if iVersion is 2 or
1396** greater and the function pointer is not NULL) and will fall back
1397** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1398*/
1399typedef struct sqlite3_vfs sqlite3_vfs;
1400struct sqlite3_vfs {
1401  int iVersion;            /* Structure version number (currently 2) */
1402  int szOsFile;            /* Size of subclassed sqlite3_file */
1403  int mxPathname;          /* Maximum file pathname length */
1404  sqlite3_vfs *pNext;      /* Next registered VFS */
1405  const char *zName;       /* Name of this virtual file system */
1406  void *pAppData;          /* Pointer to application-specific data */
1407  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1408               int flags, int *pOutFlags);
1409  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1410  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1411  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1412  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1413  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1414  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1415  void (*xDlClose)(sqlite3_vfs*, void*);
1416  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1417  int (*xSleep)(sqlite3_vfs*, int microseconds);
1418  int (*xCurrentTime)(sqlite3_vfs*, double*);
1419  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1420  /*
1421  ** The methods above are in version 1 of the sqlite_vfs object
1422  ** definition.  Those that follow are added in version 2 or later
1423  */
1424  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1425  /*
1426  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1427  ** New fields may be appended in figure versions.  The iVersion
1428  ** value will increment whenever this happens.
1429  */
1430};
1431
1432/*
1433** CAPI3REF: Flags for the xAccess VFS method
1434**
1435** These integer constants can be used as the third parameter to
1436** the xAccess method of an [sqlite3_vfs] object.  They determine
1437** what kind of permissions the xAccess method is looking for.
1438** With SQLITE_ACCESS_EXISTS, the xAccess method
1439** simply checks whether the file exists.
1440** With SQLITE_ACCESS_READWRITE, the xAccess method
1441** checks whether the named directory is both readable and writable
1442** (in other words, if files can be added, removed, and renamed within
1443** the directory).
1444** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1445** [temp_store_directory pragma], though this could change in a future
1446** release of SQLite.
1447** With SQLITE_ACCESS_READ, the xAccess method
1448** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1449** currently unused, though it might be used in a future release of
1450** SQLite.
1451*/
1452#define SQLITE_ACCESS_EXISTS    0
1453#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1454#define SQLITE_ACCESS_READ      2   /* Unused */
1455
1456/*
1457** CAPI3REF: Flags for the xShmLock VFS method
1458**
1459** These integer constants define the various locking operations
1460** allowed by the xShmLock method of [sqlite3_io_methods].  The
1461** following are the only legal combinations of flags to the
1462** xShmLock method:
1463**
1464** <ul>
1465** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1466** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1467** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1468** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1469** </ul>
1470**
1471** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1472** was given no the corresponding lock.
1473**
1474** The xShmLock method can transition between unlocked and SHARED or
1475** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1476** and EXCLUSIVE.
1477*/
1478#define SQLITE_SHM_UNLOCK       1
1479#define SQLITE_SHM_LOCK         2
1480#define SQLITE_SHM_SHARED       4
1481#define SQLITE_SHM_EXCLUSIVE    8
1482
1483/*
1484** CAPI3REF: Maximum xShmLock index
1485**
1486** The xShmLock method on [sqlite3_io_methods] may use values
1487** between 0 and this upper bound as its "offset" argument.
1488** The SQLite core will never attempt to acquire or release a
1489** lock outside of this range
1490*/
1491#define SQLITE_SHM_NLOCK        8
1492
1493
1494/*
1495** CAPI3REF: Initialize The SQLite Library
1496**
1497** ^The sqlite3_initialize() routine initializes the
1498** SQLite library.  ^The sqlite3_shutdown() routine
1499** deallocates any resources that were allocated by sqlite3_initialize().
1500** These routines are designed to aid in process initialization and
1501** shutdown on embedded systems.  Workstation applications using
1502** SQLite normally do not need to invoke either of these routines.
1503**
1504** A call to sqlite3_initialize() is an "effective" call if it is
1505** the first time sqlite3_initialize() is invoked during the lifetime of
1506** the process, or if it is the first time sqlite3_initialize() is invoked
1507** following a call to sqlite3_shutdown().  ^(Only an effective call
1508** of sqlite3_initialize() does any initialization.  All other calls
1509** are harmless no-ops.)^
1510**
1511** A call to sqlite3_shutdown() is an "effective" call if it is the first
1512** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1513** an effective call to sqlite3_shutdown() does any deinitialization.
1514** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1515**
1516** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1517** is not.  The sqlite3_shutdown() interface must only be called from a
1518** single thread.  All open [database connections] must be closed and all
1519** other SQLite resources must be deallocated prior to invoking
1520** sqlite3_shutdown().
1521**
1522** Among other things, ^sqlite3_initialize() will invoke
1523** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1524** will invoke sqlite3_os_end().
1525**
1526** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1527** ^If for some reason, sqlite3_initialize() is unable to initialize
1528** the library (perhaps it is unable to allocate a needed resource such
1529** as a mutex) it returns an [error code] other than [SQLITE_OK].
1530**
1531** ^The sqlite3_initialize() routine is called internally by many other
1532** SQLite interfaces so that an application usually does not need to
1533** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1534** calls sqlite3_initialize() so the SQLite library will be automatically
1535** initialized when [sqlite3_open()] is called if it has not be initialized
1536** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1537** compile-time option, then the automatic calls to sqlite3_initialize()
1538** are omitted and the application must call sqlite3_initialize() directly
1539** prior to using any other SQLite interface.  For maximum portability,
1540** it is recommended that applications always invoke sqlite3_initialize()
1541** directly prior to using any other SQLite interface.  Future releases
1542** of SQLite may require this.  In other words, the behavior exhibited
1543** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1544** default behavior in some future release of SQLite.
1545**
1546** The sqlite3_os_init() routine does operating-system specific
1547** initialization of the SQLite library.  The sqlite3_os_end()
1548** routine undoes the effect of sqlite3_os_init().  Typical tasks
1549** performed by these routines include allocation or deallocation
1550** of static resources, initialization of global variables,
1551** setting up a default [sqlite3_vfs] module, or setting up
1552** a default configuration using [sqlite3_config()].
1553**
1554** The application should never invoke either sqlite3_os_init()
1555** or sqlite3_os_end() directly.  The application should only invoke
1556** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1557** interface is called automatically by sqlite3_initialize() and
1558** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1559** implementations for sqlite3_os_init() and sqlite3_os_end()
1560** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1561** When [custom builds | built for other platforms]
1562** (using the [SQLITE_OS_OTHER=1] compile-time
1563** option) the application must supply a suitable implementation for
1564** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1565** implementation of sqlite3_os_init() or sqlite3_os_end()
1566** must return [SQLITE_OK] on success and some other [error code] upon
1567** failure.
1568*/
1569SQLITE_API int sqlite3_initialize(void);
1570SQLITE_API int sqlite3_shutdown(void);
1571SQLITE_API int sqlite3_os_init(void);
1572SQLITE_API int sqlite3_os_end(void);
1573
1574/*
1575** CAPI3REF: Configuring The SQLite Library
1576**
1577** The sqlite3_config() interface is used to make global configuration
1578** changes to SQLite in order to tune SQLite to the specific needs of
1579** the application.  The default configuration is recommended for most
1580** applications and so this routine is usually not necessary.  It is
1581** provided to support rare applications with unusual needs.
1582**
1583** The sqlite3_config() interface is not threadsafe.  The application
1584** must insure that no other SQLite interfaces are invoked by other
1585** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1586** may only be invoked prior to library initialization using
1587** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1588** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1589** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1590** Note, however, that ^sqlite3_config() can be called as part of the
1591** implementation of an application-defined [sqlite3_os_init()].
1592**
1593** The first argument to sqlite3_config() is an integer
1594** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1595** what property of SQLite is to be configured.  Subsequent arguments
1596** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1597** in the first argument.
1598**
1599** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1600** ^If the option is unknown or SQLite is unable to set the option
1601** then this routine returns a non-zero [error code].
1602*/
1603SQLITE_API int sqlite3_config(int, ...);
1604
1605/*
1606** CAPI3REF: Configure database connections
1607**
1608** The sqlite3_db_config() interface is used to make configuration
1609** changes to a [database connection].  The interface is similar to
1610** [sqlite3_config()] except that the changes apply to a single
1611** [database connection] (specified in the first argument).  The
1612** sqlite3_db_config() interface should only be used immediately after
1613** the database connection is created using [sqlite3_open()],
1614** [sqlite3_open16()], or [sqlite3_open_v2()].
1615**
1616** The second argument to sqlite3_db_config(D,V,...)  is the
1617** configuration verb - an integer code that indicates what
1618** aspect of the [database connection] is being configured.
1619** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1620** New verbs are likely to be added in future releases of SQLite.
1621** Additional arguments depend on the verb.
1622**
1623** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1624** the call is considered successful.
1625*/
1626SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1627
1628/*
1629** CAPI3REF: Memory Allocation Routines
1630**
1631** An instance of this object defines the interface between SQLite
1632** and low-level memory allocation routines.
1633**
1634** This object is used in only one place in the SQLite interface.
1635** A pointer to an instance of this object is the argument to
1636** [sqlite3_config()] when the configuration option is
1637** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1638** By creating an instance of this object
1639** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1640** during configuration, an application can specify an alternative
1641** memory allocation subsystem for SQLite to use for all of its
1642** dynamic memory needs.
1643**
1644** Note that SQLite comes with several [built-in memory allocators]
1645** that are perfectly adequate for the overwhelming majority of applications
1646** and that this object is only useful to a tiny minority of applications
1647** with specialized memory allocation requirements.  This object is
1648** also used during testing of SQLite in order to specify an alternative
1649** memory allocator that simulates memory out-of-memory conditions in
1650** order to verify that SQLite recovers gracefully from such
1651** conditions.
1652**
1653** The xMalloc and xFree methods must work like the
1654** malloc() and free() functions from the standard C library.
1655** The xRealloc method must work like realloc() from the standard C library
1656** with the exception that if the second argument to xRealloc is zero,
1657** xRealloc must be a no-op - it must not perform any allocation or
1658** deallocation.  ^SQLite guarantees that the second argument to
1659** xRealloc is always a value returned by a prior call to xRoundup.
1660** And so in cases where xRoundup always returns a positive number,
1661** xRealloc can perform exactly as the standard library realloc() and
1662** still be in compliance with this specification.
1663**
1664** xSize should return the allocated size of a memory allocation
1665** previously obtained from xMalloc or xRealloc.  The allocated size
1666** is always at least as big as the requested size but may be larger.
1667**
1668** The xRoundup method returns what would be the allocated size of
1669** a memory allocation given a particular requested size.  Most memory
1670** allocators round up memory allocations at least to the next multiple
1671** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1672** Every memory allocation request coming in through [sqlite3_malloc()]
1673** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1674** that causes the corresponding memory allocation to fail.
1675**
1676** The xInit method initializes the memory allocator.  (For example,
1677** it might allocate any require mutexes or initialize internal data
1678** structures.  The xShutdown method is invoked (indirectly) by
1679** [sqlite3_shutdown()] and should deallocate any resources acquired
1680** by xInit.  The pAppData pointer is used as the only parameter to
1681** xInit and xShutdown.
1682**
1683** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1684** the xInit method, so the xInit method need not be threadsafe.  The
1685** xShutdown method is only called from [sqlite3_shutdown()] so it does
1686** not need to be threadsafe either.  For all other methods, SQLite
1687** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1688** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1689** it is by default) and so the methods are automatically serialized.
1690** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1691** methods must be threadsafe or else make their own arrangements for
1692** serialization.
1693**
1694** SQLite will never invoke xInit() more than once without an intervening
1695** call to xShutdown().
1696*/
1697typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1698struct sqlite3_mem_methods {
1699  void *(*xMalloc)(int);         /* Memory allocation function */
1700  void (*xFree)(void*);          /* Free a prior allocation */
1701  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1702  int (*xSize)(void*);           /* Return the size of an allocation */
1703  int (*xRoundup)(int);          /* Round up request size to allocation size */
1704  int (*xInit)(void*);           /* Initialize the memory allocator */
1705  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1706  void *pAppData;                /* Argument to xInit() and xShutdown() */
1707};
1708
1709/*
1710** CAPI3REF: Configuration Options
1711**
1712** These constants are the available integer configuration options that
1713** can be passed as the first argument to the [sqlite3_config()] interface.
1714**
1715** New configuration options may be added in future releases of SQLite.
1716** Existing configuration options might be discontinued.  Applications
1717** should check the return code from [sqlite3_config()] to make sure that
1718** the call worked.  The [sqlite3_config()] interface will return a
1719** non-zero [error code] if a discontinued or unsupported configuration option
1720** is invoked.
1721**
1722** <dl>
1723** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1724** <dd>There are no arguments to this option.  ^This option sets the
1725** [threading mode] to Single-thread.  In other words, it disables
1726** all mutexing and puts SQLite into a mode where it can only be used
1727** by a single thread.   ^If SQLite is compiled with
1728** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1729** it is not possible to change the [threading mode] from its default
1730** value of Single-thread and so [sqlite3_config()] will return
1731** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1732** configuration option.</dd>
1733**
1734** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1735** <dd>There are no arguments to this option.  ^This option sets the
1736** [threading mode] to Multi-thread.  In other words, it disables
1737** mutexing on [database connection] and [prepared statement] objects.
1738** The application is responsible for serializing access to
1739** [database connections] and [prepared statements].  But other mutexes
1740** are enabled so that SQLite will be safe to use in a multi-threaded
1741** environment as long as no two threads attempt to use the same
1742** [database connection] at the same time.  ^If SQLite is compiled with
1743** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1744** it is not possible to set the Multi-thread [threading mode] and
1745** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1746** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1747**
1748** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1749** <dd>There are no arguments to this option.  ^This option sets the
1750** [threading mode] to Serialized. In other words, this option enables
1751** all mutexes including the recursive
1752** mutexes on [database connection] and [prepared statement] objects.
1753** In this mode (which is the default when SQLite is compiled with
1754** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1755** to [database connections] and [prepared statements] so that the
1756** application is free to use the same [database connection] or the
1757** same [prepared statement] in different threads at the same time.
1758** ^If SQLite is compiled with
1759** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1760** it is not possible to set the Serialized [threading mode] and
1761** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1762** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1763**
1764** <dt>SQLITE_CONFIG_MALLOC</dt>
1765** <dd> ^(This option takes a single argument which is a pointer to an
1766** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1767** alternative low-level memory allocation routines to be used in place of
1768** the memory allocation routines built into SQLite.)^ ^SQLite makes
1769** its own private copy of the content of the [sqlite3_mem_methods] structure
1770** before the [sqlite3_config()] call returns.</dd>
1771**
1772** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1773** <dd> ^(This option takes a single argument which is a pointer to an
1774** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1775** structure is filled with the currently defined memory allocation routines.)^
1776** This option can be used to overload the default memory allocation
1777** routines with a wrapper that simulations memory allocation failure or
1778** tracks memory usage, for example. </dd>
1779**
1780** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1781** <dd> ^This option takes single argument of type int, interpreted as a
1782** boolean, which enables or disables the collection of memory allocation
1783** statistics. ^(When memory allocation statistics are disabled, the
1784** following SQLite interfaces become non-operational:
1785**   <ul>
1786**   <li> [sqlite3_memory_used()]
1787**   <li> [sqlite3_memory_highwater()]
1788**   <li> [sqlite3_soft_heap_limit()]
1789**   <li> [sqlite3_status()]
1790**   </ul>)^
1791** ^Memory allocation statistics are enabled by default unless SQLite is
1792** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1793** allocation statistics are disabled by default.
1794** </dd>
1795**
1796** <dt>SQLITE_CONFIG_SCRATCH</dt>
1797** <dd> ^This option specifies a static memory buffer that SQLite can use for
1798** scratch memory.  There are three arguments:  A pointer an 8-byte
1799** aligned memory buffer from which the scrach allocations will be
1800** drawn, the size of each scratch allocation (sz),
1801** and the maximum number of scratch allocations (N).  The sz
1802** argument must be a multiple of 16. The sz parameter should be a few bytes
1803** larger than the actual scratch space required due to internal overhead.
1804** The first argument must be a pointer to an 8-byte aligned buffer
1805** of at least sz*N bytes of memory.
1806** ^SQLite will use no more than one scratch buffer per thread.  So
1807** N should be set to the expected maximum number of threads.  ^SQLite will
1808** never require a scratch buffer that is more than 6 times the database
1809** page size. ^If SQLite needs needs additional scratch memory beyond
1810** what is provided by this configuration option, then
1811** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1812**
1813** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1814** <dd> ^This option specifies a static memory buffer that SQLite can use for
1815** the database page cache with the default page cache implemenation.
1816** This configuration should not be used if an application-define page
1817** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1818** There are three arguments to this option: A pointer to 8-byte aligned
1819** memory, the size of each page buffer (sz), and the number of pages (N).
1820** The sz argument should be the size of the largest database page
1821** (a power of two between 512 and 32768) plus a little extra for each
1822** page header.  ^The page header size is 20 to 40 bytes depending on
1823** the host architecture.  ^It is harmless, apart from the wasted memory,
1824** to make sz a little too large.  The first
1825** argument should point to an allocation of at least sz*N bytes of memory.
1826** ^SQLite will use the memory provided by the first argument to satisfy its
1827** memory needs for the first N pages that it adds to cache.  ^If additional
1828** page cache memory is needed beyond what is provided by this option, then
1829** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1830** ^The implementation might use one or more of the N buffers to hold
1831** memory accounting information. The pointer in the first argument must
1832** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1833** will be undefined.</dd>
1834**
1835** <dt>SQLITE_CONFIG_HEAP</dt>
1836** <dd> ^This option specifies a static memory buffer that SQLite will use
1837** for all of its dynamic memory allocation needs beyond those provided
1838** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1839** There are three arguments: An 8-byte aligned pointer to the memory,
1840** the number of bytes in the memory buffer, and the minimum allocation size.
1841** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1842** to using its default memory allocator (the system malloc() implementation),
1843** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1844** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1845** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1846** allocator is engaged to handle all of SQLites memory allocation needs.
1847** The first pointer (the memory pointer) must be aligned to an 8-byte
1848** boundary or subsequent behavior of SQLite will be undefined.</dd>
1849**
1850** <dt>SQLITE_CONFIG_MUTEX</dt>
1851** <dd> ^(This option takes a single argument which is a pointer to an
1852** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1853** alternative low-level mutex routines to be used in place
1854** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1855** content of the [sqlite3_mutex_methods] structure before the call to
1856** [sqlite3_config()] returns. ^If SQLite is compiled with
1857** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1858** the entire mutexing subsystem is omitted from the build and hence calls to
1859** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1860** return [SQLITE_ERROR].</dd>
1861**
1862** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1863** <dd> ^(This option takes a single argument which is a pointer to an
1864** instance of the [sqlite3_mutex_methods] structure.  The
1865** [sqlite3_mutex_methods]
1866** structure is filled with the currently defined mutex routines.)^
1867** This option can be used to overload the default mutex allocation
1868** routines with a wrapper used to track mutex usage for performance
1869** profiling or testing, for example.   ^If SQLite is compiled with
1870** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1871** the entire mutexing subsystem is omitted from the build and hence calls to
1872** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1873** return [SQLITE_ERROR].</dd>
1874**
1875** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1876** <dd> ^(This option takes two arguments that determine the default
1877** memory allocation for the lookaside memory allocator on each
1878** [database connection].  The first argument is the
1879** size of each lookaside buffer slot and the second is the number of
1880** slots allocated to each database connection.)^  ^(This option sets the
1881** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1882** verb to [sqlite3_db_config()] can be used to change the lookaside
1883** configuration on individual connections.)^ </dd>
1884**
1885** <dt>SQLITE_CONFIG_PCACHE</dt>
1886** <dd> ^(This option takes a single argument which is a pointer to
1887** an [sqlite3_pcache_methods] object.  This object specifies the interface
1888** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1889** object and uses it for page cache memory allocations.</dd>
1890**
1891** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1892** <dd> ^(This option takes a single argument which is a pointer to an
1893** [sqlite3_pcache_methods] object.  SQLite copies of the current
1894** page cache implementation into that object.)^ </dd>
1895**
1896** <dt>SQLITE_CONFIG_LOG</dt>
1897** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1898** function with a call signature of void(*)(void*,int,const char*),
1899** and a pointer to void. ^If the function pointer is not NULL, it is
1900** invoked by [sqlite3_log()] to process each logging event.  ^If the
1901** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1902** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1903** passed through as the first parameter to the application-defined logger
1904** function whenever that function is invoked.  ^The second parameter to
1905** the logger function is a copy of the first parameter to the corresponding
1906** [sqlite3_log()] call and is intended to be a [result code] or an
1907** [extended result code].  ^The third parameter passed to the logger is
1908** log message after formatting via [sqlite3_snprintf()].
1909** The SQLite logging interface is not reentrant; the logger function
1910** supplied by the application must not invoke any SQLite interface.
1911** In a multi-threaded application, the application-defined logger
1912** function must be threadsafe. </dd>
1913**
1914** </dl>
1915*/
1916#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1917#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1918#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1919#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1920#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1921#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1922#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1923#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1924#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1925#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1926#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1927/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1928#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1929#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1930#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1931#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1932
1933/*
1934** CAPI3REF: Database Connection Configuration Options
1935**
1936** These constants are the available integer configuration options that
1937** can be passed as the second argument to the [sqlite3_db_config()] interface.
1938**
1939** New configuration options may be added in future releases of SQLite.
1940** Existing configuration options might be discontinued.  Applications
1941** should check the return code from [sqlite3_db_config()] to make sure that
1942** the call worked.  ^The [sqlite3_db_config()] interface will return a
1943** non-zero [error code] if a discontinued or unsupported configuration option
1944** is invoked.
1945**
1946** <dl>
1947** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1948** <dd> ^This option takes three additional arguments that determine the
1949** [lookaside memory allocator] configuration for the [database connection].
1950** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1951** pointer to an memory buffer to use for lookaside memory.
1952** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1953** may be NULL in which case SQLite will allocate the
1954** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1955** size of each lookaside buffer slot.  ^The third argument is the number of
1956** slots.  The size of the buffer in the first argument must be greater than
1957** or equal to the product of the second and third arguments.  The buffer
1958** must be aligned to an 8-byte boundary.  ^If the second argument to
1959** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1960** rounded down to the next smaller
1961** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1962**
1963** </dl>
1964*/
1965#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1966
1967
1968/*
1969** CAPI3REF: Enable Or Disable Extended Result Codes
1970**
1971** ^The sqlite3_extended_result_codes() routine enables or disables the
1972** [extended result codes] feature of SQLite. ^The extended result
1973** codes are disabled by default for historical compatibility.
1974*/
1975SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1976
1977/*
1978** CAPI3REF: Last Insert Rowid
1979**
1980** ^Each entry in an SQLite table has a unique 64-bit signed
1981** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1982** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1983** names are not also used by explicitly declared columns. ^If
1984** the table has a column of type [INTEGER PRIMARY KEY] then that column
1985** is another alias for the rowid.
1986**
1987** ^This routine returns the [rowid] of the most recent
1988** successful [INSERT] into the database from the [database connection]
1989** in the first argument.  ^If no successful [INSERT]s
1990** have ever occurred on that database connection, zero is returned.
1991**
1992** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1993** row is returned by this routine as long as the trigger is running.
1994** But once the trigger terminates, the value returned by this routine
1995** reverts to the last value inserted before the trigger fired.)^
1996**
1997** ^An [INSERT] that fails due to a constraint violation is not a
1998** successful [INSERT] and does not change the value returned by this
1999** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2000** and INSERT OR ABORT make no changes to the return value of this
2001** routine when their insertion fails.  ^(When INSERT OR REPLACE
2002** encounters a constraint violation, it does not fail.  The
2003** INSERT continues to completion after deleting rows that caused
2004** the constraint problem so INSERT OR REPLACE will always change
2005** the return value of this interface.)^
2006**
2007** ^For the purposes of this routine, an [INSERT] is considered to
2008** be successful even if it is subsequently rolled back.
2009**
2010** This function is accessible to SQL statements via the
2011** [last_insert_rowid() SQL function].
2012**
2013** If a separate thread performs a new [INSERT] on the same
2014** database connection while the [sqlite3_last_insert_rowid()]
2015** function is running and thus changes the last insert [rowid],
2016** then the value returned by [sqlite3_last_insert_rowid()] is
2017** unpredictable and might not equal either the old or the new
2018** last insert [rowid].
2019*/
2020SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2021
2022/*
2023** CAPI3REF: Count The Number Of Rows Modified
2024**
2025** ^This function returns the number of database rows that were changed
2026** or inserted or deleted by the most recently completed SQL statement
2027** on the [database connection] specified by the first parameter.
2028** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2029** or [DELETE] statement are counted.  Auxiliary changes caused by
2030** triggers or [foreign key actions] are not counted.)^ Use the
2031** [sqlite3_total_changes()] function to find the total number of changes
2032** including changes caused by triggers and foreign key actions.
2033**
2034** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2035** are not counted.  Only real table changes are counted.
2036**
2037** ^(A "row change" is a change to a single row of a single table
2038** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2039** are changed as side effects of [REPLACE] constraint resolution,
2040** rollback, ABORT processing, [DROP TABLE], or by any other
2041** mechanisms do not count as direct row changes.)^
2042**
2043** A "trigger context" is a scope of execution that begins and
2044** ends with the script of a [CREATE TRIGGER | trigger].
2045** Most SQL statements are
2046** evaluated outside of any trigger.  This is the "top level"
2047** trigger context.  If a trigger fires from the top level, a
2048** new trigger context is entered for the duration of that one
2049** trigger.  Subtriggers create subcontexts for their duration.
2050**
2051** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2052** not create a new trigger context.
2053**
2054** ^This function returns the number of direct row changes in the
2055** most recent INSERT, UPDATE, or DELETE statement within the same
2056** trigger context.
2057**
2058** ^Thus, when called from the top level, this function returns the
2059** number of changes in the most recent INSERT, UPDATE, or DELETE
2060** that also occurred at the top level.  ^(Within the body of a trigger,
2061** the sqlite3_changes() interface can be called to find the number of
2062** changes in the most recently completed INSERT, UPDATE, or DELETE
2063** statement within the body of the same trigger.
2064** However, the number returned does not include changes
2065** caused by subtriggers since those have their own context.)^
2066**
2067** See also the [sqlite3_total_changes()] interface, the
2068** [count_changes pragma], and the [changes() SQL function].
2069**
2070** If a separate thread makes changes on the same database connection
2071** while [sqlite3_changes()] is running then the value returned
2072** is unpredictable and not meaningful.
2073*/
2074SQLITE_API int sqlite3_changes(sqlite3*);
2075
2076/*
2077** CAPI3REF: Total Number Of Rows Modified
2078**
2079** ^This function returns the number of row changes caused by [INSERT],
2080** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2081** ^(The count returned by sqlite3_total_changes() includes all changes
2082** from all [CREATE TRIGGER | trigger] contexts and changes made by
2083** [foreign key actions]. However,
2084** the count does not include changes used to implement [REPLACE] constraints,
2085** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2086** count does not include rows of views that fire an [INSTEAD OF trigger],
2087** though if the INSTEAD OF trigger makes changes of its own, those changes
2088** are counted.)^
2089** ^The sqlite3_total_changes() function counts the changes as soon as
2090** the statement that makes them is completed (when the statement handle
2091** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2092**
2093** See also the [sqlite3_changes()] interface, the
2094** [count_changes pragma], and the [total_changes() SQL function].
2095**
2096** If a separate thread makes changes on the same database connection
2097** while [sqlite3_total_changes()] is running then the value
2098** returned is unpredictable and not meaningful.
2099*/
2100SQLITE_API int sqlite3_total_changes(sqlite3*);
2101
2102/*
2103** CAPI3REF: Interrupt A Long-Running Query
2104**
2105** ^This function causes any pending database operation to abort and
2106** return at its earliest opportunity. This routine is typically
2107** called in response to a user action such as pressing "Cancel"
2108** or Ctrl-C where the user wants a long query operation to halt
2109** immediately.
2110**
2111** ^It is safe to call this routine from a thread different from the
2112** thread that is currently running the database operation.  But it
2113** is not safe to call this routine with a [database connection] that
2114** is closed or might close before sqlite3_interrupt() returns.
2115**
2116** ^If an SQL operation is very nearly finished at the time when
2117** sqlite3_interrupt() is called, then it might not have an opportunity
2118** to be interrupted and might continue to completion.
2119**
2120** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2121** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2122** that is inside an explicit transaction, then the entire transaction
2123** will be rolled back automatically.
2124**
2125** ^The sqlite3_interrupt(D) call is in effect until all currently running
2126** SQL statements on [database connection] D complete.  ^Any new SQL statements
2127** that are started after the sqlite3_interrupt() call and before the
2128** running statements reaches zero are interrupted as if they had been
2129** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2130** that are started after the running statement count reaches zero are
2131** not effected by the sqlite3_interrupt().
2132** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2133** SQL statements is a no-op and has no effect on SQL statements
2134** that are started after the sqlite3_interrupt() call returns.
2135**
2136** If the database connection closes while [sqlite3_interrupt()]
2137** is running then bad things will likely happen.
2138*/
2139SQLITE_API void sqlite3_interrupt(sqlite3*);
2140
2141/*
2142** CAPI3REF: Determine If An SQL Statement Is Complete
2143**
2144** These routines are useful during command-line input to determine if the
2145** currently entered text seems to form a complete SQL statement or
2146** if additional input is needed before sending the text into
2147** SQLite for parsing.  ^These routines return 1 if the input string
2148** appears to be a complete SQL statement.  ^A statement is judged to be
2149** complete if it ends with a semicolon token and is not a prefix of a
2150** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2151** string literals or quoted identifier names or comments are not
2152** independent tokens (they are part of the token in which they are
2153** embedded) and thus do not count as a statement terminator.  ^Whitespace
2154** and comments that follow the final semicolon are ignored.
2155**
2156** ^These routines return 0 if the statement is incomplete.  ^If a
2157** memory allocation fails, then SQLITE_NOMEM is returned.
2158**
2159** ^These routines do not parse the SQL statements thus
2160** will not detect syntactically incorrect SQL.
2161**
2162** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2163** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2164** automatically by sqlite3_complete16().  If that initialization fails,
2165** then the return value from sqlite3_complete16() will be non-zero
2166** regardless of whether or not the input SQL is complete.)^
2167**
2168** The input to [sqlite3_complete()] must be a zero-terminated
2169** UTF-8 string.
2170**
2171** The input to [sqlite3_complete16()] must be a zero-terminated
2172** UTF-16 string in native byte order.
2173*/
2174SQLITE_API int sqlite3_complete(const char *sql);
2175SQLITE_API int sqlite3_complete16(const void *sql);
2176
2177/*
2178** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2179**
2180** ^This routine sets a callback function that might be invoked whenever
2181** an attempt is made to open a database table that another thread
2182** or process has locked.
2183**
2184** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2185** is returned immediately upon encountering the lock.  ^If the busy callback
2186** is not NULL, then the callback might be invoked with two arguments.
2187**
2188** ^The first argument to the busy handler is a copy of the void* pointer which
2189** is the third argument to sqlite3_busy_handler().  ^The second argument to
2190** the busy handler callback is the number of times that the busy handler has
2191** been invoked for this locking event.  ^If the
2192** busy callback returns 0, then no additional attempts are made to
2193** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2194** ^If the callback returns non-zero, then another attempt
2195** is made to open the database for reading and the cycle repeats.
2196**
2197** The presence of a busy handler does not guarantee that it will be invoked
2198** when there is lock contention. ^If SQLite determines that invoking the busy
2199** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2200** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2201** Consider a scenario where one process is holding a read lock that
2202** it is trying to promote to a reserved lock and
2203** a second process is holding a reserved lock that it is trying
2204** to promote to an exclusive lock.  The first process cannot proceed
2205** because it is blocked by the second and the second process cannot
2206** proceed because it is blocked by the first.  If both processes
2207** invoke the busy handlers, neither will make any progress.  Therefore,
2208** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2209** will induce the first process to release its read lock and allow
2210** the second process to proceed.
2211**
2212** ^The default busy callback is NULL.
2213**
2214** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2215** when SQLite is in the middle of a large transaction where all the
2216** changes will not fit into the in-memory cache.  SQLite will
2217** already hold a RESERVED lock on the database file, but it needs
2218** to promote this lock to EXCLUSIVE so that it can spill cache
2219** pages into the database file without harm to concurrent
2220** readers.  ^If it is unable to promote the lock, then the in-memory
2221** cache will be left in an inconsistent state and so the error
2222** code is promoted from the relatively benign [SQLITE_BUSY] to
2223** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2224** forces an automatic rollback of the changes.  See the
2225** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2226** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2227** this is important.
2228**
2229** ^(There can only be a single busy handler defined for each
2230** [database connection].  Setting a new busy handler clears any
2231** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2232** will also set or clear the busy handler.
2233**
2234** The busy callback should not take any actions which modify the
2235** database connection that invoked the busy handler.  Any such actions
2236** result in undefined behavior.
2237**
2238** A busy handler must not close the database connection
2239** or [prepared statement] that invoked the busy handler.
2240*/
2241SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2242
2243/*
2244** CAPI3REF: Set A Busy Timeout
2245**
2246** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2247** for a specified amount of time when a table is locked.  ^The handler
2248** will sleep multiple times until at least "ms" milliseconds of sleeping
2249** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2250** the handler returns 0 which causes [sqlite3_step()] to return
2251** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2252**
2253** ^Calling this routine with an argument less than or equal to zero
2254** turns off all busy handlers.
2255**
2256** ^(There can only be a single busy handler for a particular
2257** [database connection] any any given moment.  If another busy handler
2258** was defined  (using [sqlite3_busy_handler()]) prior to calling
2259** this routine, that other busy handler is cleared.)^
2260*/
2261SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2262
2263/*
2264** CAPI3REF: Convenience Routines For Running Queries
2265**
2266** Definition: A <b>result table</b> is memory data structure created by the
2267** [sqlite3_get_table()] interface.  A result table records the
2268** complete query results from one or more queries.
2269**
2270** The table conceptually has a number of rows and columns.  But
2271** these numbers are not part of the result table itself.  These
2272** numbers are obtained separately.  Let N be the number of rows
2273** and M be the number of columns.
2274**
2275** A result table is an array of pointers to zero-terminated UTF-8 strings.
2276** There are (N+1)*M elements in the array.  The first M pointers point
2277** to zero-terminated strings that  contain the names of the columns.
2278** The remaining entries all point to query results.  NULL values result
2279** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2280** string representation as returned by [sqlite3_column_text()].
2281**
2282** A result table might consist of one or more memory allocations.
2283** It is not safe to pass a result table directly to [sqlite3_free()].
2284** A result table should be deallocated using [sqlite3_free_table()].
2285**
2286** As an example of the result table format, suppose a query result
2287** is as follows:
2288**
2289** <blockquote><pre>
2290**        Name        | Age
2291**        -----------------------
2292**        Alice       | 43
2293**        Bob         | 28
2294**        Cindy       | 21
2295** </pre></blockquote>
2296**
2297** There are two column (M==2) and three rows (N==3).  Thus the
2298** result table has 8 entries.  Suppose the result table is stored
2299** in an array names azResult.  Then azResult holds this content:
2300**
2301** <blockquote><pre>
2302**        azResult&#91;0] = "Name";
2303**        azResult&#91;1] = "Age";
2304**        azResult&#91;2] = "Alice";
2305**        azResult&#91;3] = "43";
2306**        azResult&#91;4] = "Bob";
2307**        azResult&#91;5] = "28";
2308**        azResult&#91;6] = "Cindy";
2309**        azResult&#91;7] = "21";
2310** </pre></blockquote>
2311**
2312** ^The sqlite3_get_table() function evaluates one or more
2313** semicolon-separated SQL statements in the zero-terminated UTF-8
2314** string of its 2nd parameter and returns a result table to the
2315** pointer given in its 3rd parameter.
2316**
2317** After the application has finished with the result from sqlite3_get_table(),
2318** it should pass the result table pointer to sqlite3_free_table() in order to
2319** release the memory that was malloced.  Because of the way the
2320** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2321** function must not try to call [sqlite3_free()] directly.  Only
2322** [sqlite3_free_table()] is able to release the memory properly and safely.
2323**
2324** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2325** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2326** to any internal data structures of SQLite.  It uses only the public
2327** interface defined here.  As a consequence, errors that occur in the
2328** wrapper layer outside of the internal [sqlite3_exec()] call are not
2329** reflected in subsequent calls to [sqlite3_errcode()] or
2330** [sqlite3_errmsg()].)^
2331*/
2332SQLITE_API int sqlite3_get_table(
2333  sqlite3 *db,          /* An open database */
2334  const char *zSql,     /* SQL to be evaluated */
2335  char ***pazResult,    /* Results of the query */
2336  int *pnRow,           /* Number of result rows written here */
2337  int *pnColumn,        /* Number of result columns written here */
2338  char **pzErrmsg       /* Error msg written here */
2339);
2340SQLITE_API void sqlite3_free_table(char **result);
2341
2342/*
2343** CAPI3REF: Formatted String Printing Functions
2344**
2345** These routines are work-alikes of the "printf()" family of functions
2346** from the standard C library.
2347**
2348** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2349** results into memory obtained from [sqlite3_malloc()].
2350** The strings returned by these two routines should be
2351** released by [sqlite3_free()].  ^Both routines return a
2352** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2353** memory to hold the resulting string.
2354**
2355** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2356** the standard C library.  The result is written into the
2357** buffer supplied as the second parameter whose size is given by
2358** the first parameter. Note that the order of the
2359** first two parameters is reversed from snprintf().)^  This is an
2360** historical accident that cannot be fixed without breaking
2361** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2362** returns a pointer to its buffer instead of the number of
2363** characters actually written into the buffer.)^  We admit that
2364** the number of characters written would be a more useful return
2365** value but we cannot change the implementation of sqlite3_snprintf()
2366** now without breaking compatibility.
2367**
2368** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2369** guarantees that the buffer is always zero-terminated.  ^The first
2370** parameter "n" is the total size of the buffer, including space for
2371** the zero terminator.  So the longest string that can be completely
2372** written will be n-1 characters.
2373**
2374** These routines all implement some additional formatting
2375** options that are useful for constructing SQL statements.
2376** All of the usual printf() formatting options apply.  In addition, there
2377** is are "%q", "%Q", and "%z" options.
2378**
2379** ^(The %q option works like %s in that it substitutes a null-terminated
2380** string from the argument list.  But %q also doubles every '\'' character.
2381** %q is designed for use inside a string literal.)^  By doubling each '\''
2382** character it escapes that character and allows it to be inserted into
2383** the string.
2384**
2385** For example, assume the string variable zText contains text as follows:
2386**
2387** <blockquote><pre>
2388**  char *zText = "It's a happy day!";
2389** </pre></blockquote>
2390**
2391** One can use this text in an SQL statement as follows:
2392**
2393** <blockquote><pre>
2394**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2395**  sqlite3_exec(db, zSQL, 0, 0, 0);
2396**  sqlite3_free(zSQL);
2397** </pre></blockquote>
2398**
2399** Because the %q format string is used, the '\'' character in zText
2400** is escaped and the SQL generated is as follows:
2401**
2402** <blockquote><pre>
2403**  INSERT INTO table1 VALUES('It''s a happy day!')
2404** </pre></blockquote>
2405**
2406** This is correct.  Had we used %s instead of %q, the generated SQL
2407** would have looked like this:
2408**
2409** <blockquote><pre>
2410**  INSERT INTO table1 VALUES('It's a happy day!');
2411** </pre></blockquote>
2412**
2413** This second example is an SQL syntax error.  As a general rule you should
2414** always use %q instead of %s when inserting text into a string literal.
2415**
2416** ^(The %Q option works like %q except it also adds single quotes around
2417** the outside of the total string.  Additionally, if the parameter in the
2418** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2419** single quotes).)^  So, for example, one could say:
2420**
2421** <blockquote><pre>
2422**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2423**  sqlite3_exec(db, zSQL, 0, 0, 0);
2424**  sqlite3_free(zSQL);
2425** </pre></blockquote>
2426**
2427** The code above will render a correct SQL statement in the zSQL
2428** variable even if the zText variable is a NULL pointer.
2429**
2430** ^(The "%z" formatting option works like "%s" but with the
2431** addition that after the string has been read and copied into
2432** the result, [sqlite3_free()] is called on the input string.)^
2433*/
2434SQLITE_API char *sqlite3_mprintf(const char*,...);
2435SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2436SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2437
2438/*
2439** CAPI3REF: Memory Allocation Subsystem
2440**
2441** The SQLite core uses these three routines for all of its own
2442** internal memory allocation needs. "Core" in the previous sentence
2443** does not include operating-system specific VFS implementation.  The
2444** Windows VFS uses native malloc() and free() for some operations.
2445**
2446** ^The sqlite3_malloc() routine returns a pointer to a block
2447** of memory at least N bytes in length, where N is the parameter.
2448** ^If sqlite3_malloc() is unable to obtain sufficient free
2449** memory, it returns a NULL pointer.  ^If the parameter N to
2450** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2451** a NULL pointer.
2452**
2453** ^Calling sqlite3_free() with a pointer previously returned
2454** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2455** that it might be reused.  ^The sqlite3_free() routine is
2456** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2457** to sqlite3_free() is harmless.  After being freed, memory
2458** should neither be read nor written.  Even reading previously freed
2459** memory might result in a segmentation fault or other severe error.
2460** Memory corruption, a segmentation fault, or other severe error
2461** might result if sqlite3_free() is called with a non-NULL pointer that
2462** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2463**
2464** ^(The sqlite3_realloc() interface attempts to resize a
2465** prior memory allocation to be at least N bytes, where N is the
2466** second parameter.  The memory allocation to be resized is the first
2467** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2468** is a NULL pointer then its behavior is identical to calling
2469** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2470** ^If the second parameter to sqlite3_realloc() is zero or
2471** negative then the behavior is exactly the same as calling
2472** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2473** ^sqlite3_realloc() returns a pointer to a memory allocation
2474** of at least N bytes in size or NULL if sufficient memory is unavailable.
2475** ^If M is the size of the prior allocation, then min(N,M) bytes
2476** of the prior allocation are copied into the beginning of buffer returned
2477** by sqlite3_realloc() and the prior allocation is freed.
2478** ^If sqlite3_realloc() returns NULL, then the prior allocation
2479** is not freed.
2480**
2481** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2482** is always aligned to at least an 8 byte boundary.
2483**
2484** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2485** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2486** implementation of these routines to be omitted.  That capability
2487** is no longer provided.  Only built-in memory allocators can be used.
2488**
2489** The Windows OS interface layer calls
2490** the system malloc() and free() directly when converting
2491** filenames between the UTF-8 encoding used by SQLite
2492** and whatever filename encoding is used by the particular Windows
2493** installation.  Memory allocation errors are detected, but
2494** they are reported back as [SQLITE_CANTOPEN] or
2495** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2496**
2497** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2498** must be either NULL or else pointers obtained from a prior
2499** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2500** not yet been released.
2501**
2502** The application must not read or write any part of
2503** a block of memory after it has been released using
2504** [sqlite3_free()] or [sqlite3_realloc()].
2505*/
2506SQLITE_API void *sqlite3_malloc(int);
2507SQLITE_API void *sqlite3_realloc(void*, int);
2508SQLITE_API void sqlite3_free(void*);
2509
2510/*
2511** CAPI3REF: Memory Allocator Statistics
2512**
2513** SQLite provides these two interfaces for reporting on the status
2514** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2515** routines, which form the built-in memory allocation subsystem.
2516**
2517** ^The [sqlite3_memory_used()] routine returns the number of bytes
2518** of memory currently outstanding (malloced but not freed).
2519** ^The [sqlite3_memory_highwater()] routine returns the maximum
2520** value of [sqlite3_memory_used()] since the high-water mark
2521** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2522** [sqlite3_memory_highwater()] include any overhead
2523** added by SQLite in its implementation of [sqlite3_malloc()],
2524** but not overhead added by the any underlying system library
2525** routines that [sqlite3_malloc()] may call.
2526**
2527** ^The memory high-water mark is reset to the current value of
2528** [sqlite3_memory_used()] if and only if the parameter to
2529** [sqlite3_memory_highwater()] is true.  ^The value returned
2530** by [sqlite3_memory_highwater(1)] is the high-water mark
2531** prior to the reset.
2532*/
2533SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2534SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2535
2536/*
2537** CAPI3REF: Pseudo-Random Number Generator
2538**
2539** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2540** select random [ROWID | ROWIDs] when inserting new records into a table that
2541** already uses the largest possible [ROWID].  The PRNG is also used for
2542** the build-in random() and randomblob() SQL functions.  This interface allows
2543** applications to access the same PRNG for other purposes.
2544**
2545** ^A call to this routine stores N bytes of randomness into buffer P.
2546**
2547** ^The first time this routine is invoked (either internally or by
2548** the application) the PRNG is seeded using randomness obtained
2549** from the xRandomness method of the default [sqlite3_vfs] object.
2550** ^On all subsequent invocations, the pseudo-randomness is generated
2551** internally and without recourse to the [sqlite3_vfs] xRandomness
2552** method.
2553*/
2554SQLITE_API void sqlite3_randomness(int N, void *P);
2555
2556/*
2557** CAPI3REF: Compile-Time Authorization Callbacks
2558**
2559** ^This routine registers a authorizer callback with a particular
2560** [database connection], supplied in the first argument.
2561** ^The authorizer callback is invoked as SQL statements are being compiled
2562** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2563** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2564** points during the compilation process, as logic is being created
2565** to perform various actions, the authorizer callback is invoked to
2566** see if those actions are allowed.  ^The authorizer callback should
2567** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2568** specific action but allow the SQL statement to continue to be
2569** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2570** rejected with an error.  ^If the authorizer callback returns
2571** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2572** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2573** the authorizer will fail with an error message.
2574**
2575** When the callback returns [SQLITE_OK], that means the operation
2576** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2577** [sqlite3_prepare_v2()] or equivalent call that triggered the
2578** authorizer will fail with an error message explaining that
2579** access is denied.
2580**
2581** ^The first parameter to the authorizer callback is a copy of the third
2582** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2583** to the callback is an integer [SQLITE_COPY | action code] that specifies
2584** the particular action to be authorized. ^The third through sixth parameters
2585** to the callback are zero-terminated strings that contain additional
2586** details about the action to be authorized.
2587**
2588** ^If the action code is [SQLITE_READ]
2589** and the callback returns [SQLITE_IGNORE] then the
2590** [prepared statement] statement is constructed to substitute
2591** a NULL value in place of the table column that would have
2592** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2593** return can be used to deny an untrusted user access to individual
2594** columns of a table.
2595** ^If the action code is [SQLITE_DELETE] and the callback returns
2596** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2597** [truncate optimization] is disabled and all rows are deleted individually.
2598**
2599** An authorizer is used when [sqlite3_prepare | preparing]
2600** SQL statements from an untrusted source, to ensure that the SQL statements
2601** do not try to access data they are not allowed to see, or that they do not
2602** try to execute malicious statements that damage the database.  For
2603** example, an application may allow a user to enter arbitrary
2604** SQL queries for evaluation by a database.  But the application does
2605** not want the user to be able to make arbitrary changes to the
2606** database.  An authorizer could then be put in place while the
2607** user-entered SQL is being [sqlite3_prepare | prepared] that
2608** disallows everything except [SELECT] statements.
2609**
2610** Applications that need to process SQL from untrusted sources
2611** might also consider lowering resource limits using [sqlite3_limit()]
2612** and limiting database size using the [max_page_count] [PRAGMA]
2613** in addition to using an authorizer.
2614**
2615** ^(Only a single authorizer can be in place on a database connection
2616** at a time.  Each call to sqlite3_set_authorizer overrides the
2617** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2618** The authorizer is disabled by default.
2619**
2620** The authorizer callback must not do anything that will modify
2621** the database connection that invoked the authorizer callback.
2622** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2623** database connections for the meaning of "modify" in this paragraph.
2624**
2625** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2626** statement might be re-prepared during [sqlite3_step()] due to a
2627** schema change.  Hence, the application should ensure that the
2628** correct authorizer callback remains in place during the [sqlite3_step()].
2629**
2630** ^Note that the authorizer callback is invoked only during
2631** [sqlite3_prepare()] or its variants.  Authorization is not
2632** performed during statement evaluation in [sqlite3_step()], unless
2633** as stated in the previous paragraph, sqlite3_step() invokes
2634** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2635*/
2636SQLITE_API int sqlite3_set_authorizer(
2637  sqlite3*,
2638  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2639  void *pUserData
2640);
2641
2642/*
2643** CAPI3REF: Authorizer Return Codes
2644**
2645** The [sqlite3_set_authorizer | authorizer callback function] must
2646** return either [SQLITE_OK] or one of these two constants in order
2647** to signal SQLite whether or not the action is permitted.  See the
2648** [sqlite3_set_authorizer | authorizer documentation] for additional
2649** information.
2650*/
2651#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2652#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2653
2654/*
2655** CAPI3REF: Authorizer Action Codes
2656**
2657** The [sqlite3_set_authorizer()] interface registers a callback function
2658** that is invoked to authorize certain SQL statement actions.  The
2659** second parameter to the callback is an integer code that specifies
2660** what action is being authorized.  These are the integer action codes that
2661** the authorizer callback may be passed.
2662**
2663** These action code values signify what kind of operation is to be
2664** authorized.  The 3rd and 4th parameters to the authorization
2665** callback function will be parameters or NULL depending on which of these
2666** codes is used as the second parameter.  ^(The 5th parameter to the
2667** authorizer callback is the name of the database ("main", "temp",
2668** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2669** is the name of the inner-most trigger or view that is responsible for
2670** the access attempt or NULL if this access attempt is directly from
2671** top-level SQL code.
2672*/
2673/******************************************* 3rd ************ 4th ***********/
2674#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2675#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2676#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2677#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2678#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2679#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2680#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2681#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2682#define SQLITE_DELETE                9   /* Table Name      NULL            */
2683#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2684#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2685#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2686#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2687#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2688#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2689#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2690#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2691#define SQLITE_INSERT               18   /* Table Name      NULL            */
2692#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2693#define SQLITE_READ                 20   /* Table Name      Column Name     */
2694#define SQLITE_SELECT               21   /* NULL            NULL            */
2695#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2696#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2697#define SQLITE_ATTACH               24   /* Filename        NULL            */
2698#define SQLITE_DETACH               25   /* Database Name   NULL            */
2699#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2700#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2701#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2702#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2703#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2704#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2705#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2706#define SQLITE_COPY                  0   /* No longer used */
2707
2708/*
2709** CAPI3REF: Tracing And Profiling Functions
2710**
2711** These routines register callback functions that can be used for
2712** tracing and profiling the execution of SQL statements.
2713**
2714** ^The callback function registered by sqlite3_trace() is invoked at
2715** various times when an SQL statement is being run by [sqlite3_step()].
2716** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2717** SQL statement text as the statement first begins executing.
2718** ^(Additional sqlite3_trace() callbacks might occur
2719** as each triggered subprogram is entered.  The callbacks for triggers
2720** contain a UTF-8 SQL comment that identifies the trigger.)^
2721**
2722** ^The callback function registered by sqlite3_profile() is invoked
2723** as each SQL statement finishes.  ^The profile callback contains
2724** the original statement text and an estimate of wall-clock time
2725** of how long that statement took to run.  ^The profile callback
2726** time is in units of nanoseconds, however the current implementation
2727** is only capable of millisecond resolution so the six least significant
2728** digits in the time are meaningless.  Future versions of SQLite
2729** might provide greater resolution on the profiler callback.  The
2730** sqlite3_profile() function is considered experimental and is
2731** subject to change in future versions of SQLite.
2732*/
2733SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2734SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2735   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2736
2737/*
2738** CAPI3REF: Query Progress Callbacks
2739**
2740** ^This routine configures a callback function - the
2741** progress callback - that is invoked periodically during long
2742** running calls to [sqlite3_exec()], [sqlite3_step()] and
2743** [sqlite3_get_table()].  An example use for this
2744** interface is to keep a GUI updated during a large query.
2745**
2746** ^If the progress callback returns non-zero, the operation is
2747** interrupted.  This feature can be used to implement a
2748** "Cancel" button on a GUI progress dialog box.
2749**
2750** The progress handler must not do anything that will modify
2751** the database connection that invoked the progress handler.
2752** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2753** database connections for the meaning of "modify" in this paragraph.
2754**
2755*/
2756SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2757
2758/*
2759** CAPI3REF: Opening A New Database Connection
2760**
2761** ^These routines open an SQLite database file whose name is given by the
2762** filename argument. ^The filename argument is interpreted as UTF-8 for
2763** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2764** order for sqlite3_open16(). ^(A [database connection] handle is usually
2765** returned in *ppDb, even if an error occurs.  The only exception is that
2766** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2767** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2768** object.)^ ^(If the database is opened (and/or created) successfully, then
2769** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2770** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2771** an English language description of the error following a failure of any
2772** of the sqlite3_open() routines.
2773**
2774** ^The default encoding for the database will be UTF-8 if
2775** sqlite3_open() or sqlite3_open_v2() is called and
2776** UTF-16 in the native byte order if sqlite3_open16() is used.
2777**
2778** Whether or not an error occurs when it is opened, resources
2779** associated with the [database connection] handle should be released by
2780** passing it to [sqlite3_close()] when it is no longer required.
2781**
2782** The sqlite3_open_v2() interface works like sqlite3_open()
2783** except that it accepts two additional parameters for additional control
2784** over the new database connection.  ^(The flags parameter to
2785** sqlite3_open_v2() can take one of
2786** the following three values, optionally combined with the
2787** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2788** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2789**
2790** <dl>
2791** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2792** <dd>The database is opened in read-only mode.  If the database does not
2793** already exist, an error is returned.</dd>)^
2794**
2795** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2796** <dd>The database is opened for reading and writing if possible, or reading
2797** only if the file is write protected by the operating system.  In either
2798** case the database must already exist, otherwise an error is returned.</dd>)^
2799**
2800** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2801** <dd>The database is opened for reading and writing, and is creates it if
2802** it does not already exist. This is the behavior that is always used for
2803** sqlite3_open() and sqlite3_open16().</dd>)^
2804** </dl>
2805**
2806** If the 3rd parameter to sqlite3_open_v2() is not one of the
2807** combinations shown above or one of the combinations shown above combined
2808** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2809** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2810** then the behavior is undefined.
2811**
2812** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2813** opens in the multi-thread [threading mode] as long as the single-thread
2814** mode has not been set at compile-time or start-time.  ^If the
2815** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2816** in the serialized [threading mode] unless single-thread was
2817** previously selected at compile-time or start-time.
2818** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2819** eligible to use [shared cache mode], regardless of whether or not shared
2820** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2821** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2822** participate in [shared cache mode] even if it is enabled.
2823**
2824** ^If the filename is ":memory:", then a private, temporary in-memory database
2825** is created for the connection.  ^This in-memory database will vanish when
2826** the database connection is closed.  Future versions of SQLite might
2827** make use of additional special filenames that begin with the ":" character.
2828** It is recommended that when a database filename actually does begin with
2829** a ":" character you should prefix the filename with a pathname such as
2830** "./" to avoid ambiguity.
2831**
2832** ^If the filename is an empty string, then a private, temporary
2833** on-disk database will be created.  ^This private database will be
2834** automatically deleted as soon as the database connection is closed.
2835**
2836** ^The fourth parameter to sqlite3_open_v2() is the name of the
2837** [sqlite3_vfs] object that defines the operating system interface that
2838** the new database connection should use.  ^If the fourth parameter is
2839** a NULL pointer then the default [sqlite3_vfs] object is used.
2840**
2841** <b>Note to Windows users:</b>  The encoding used for the filename argument
2842** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2843** codepage is currently defined.  Filenames containing international
2844** characters must be converted to UTF-8 prior to passing them into
2845** sqlite3_open() or sqlite3_open_v2().
2846*/
2847SQLITE_API int sqlite3_open(
2848  const char *filename,   /* Database filename (UTF-8) */
2849  sqlite3 **ppDb          /* OUT: SQLite db handle */
2850);
2851SQLITE_API int sqlite3_open16(
2852  const void *filename,   /* Database filename (UTF-16) */
2853  sqlite3 **ppDb          /* OUT: SQLite db handle */
2854);
2855SQLITE_API int sqlite3_open_v2(
2856  const char *filename,   /* Database filename (UTF-8) */
2857  sqlite3 **ppDb,         /* OUT: SQLite db handle */
2858  int flags,              /* Flags */
2859  const char *zVfs        /* Name of VFS module to use */
2860);
2861
2862/*
2863** CAPI3REF: Error Codes And Messages
2864**
2865** ^The sqlite3_errcode() interface returns the numeric [result code] or
2866** [extended result code] for the most recent failed sqlite3_* API call
2867** associated with a [database connection]. If a prior API call failed
2868** but the most recent API call succeeded, the return value from
2869** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2870** interface is the same except that it always returns the
2871** [extended result code] even when extended result codes are
2872** disabled.
2873**
2874** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2875** text that describes the error, as either UTF-8 or UTF-16 respectively.
2876** ^(Memory to hold the error message string is managed internally.
2877** The application does not need to worry about freeing the result.
2878** However, the error string might be overwritten or deallocated by
2879** subsequent calls to other SQLite interface functions.)^
2880**
2881** When the serialized [threading mode] is in use, it might be the
2882** case that a second error occurs on a separate thread in between
2883** the time of the first error and the call to these interfaces.
2884** When that happens, the second error will be reported since these
2885** interfaces always report the most recent result.  To avoid
2886** this, each thread can obtain exclusive use of the [database connection] D
2887** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2888** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2889** all calls to the interfaces listed here are completed.
2890**
2891** If an interface fails with SQLITE_MISUSE, that means the interface
2892** was invoked incorrectly by the application.  In that case, the
2893** error code and message may or may not be set.
2894*/
2895SQLITE_API int sqlite3_errcode(sqlite3 *db);
2896SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2897SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2898SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2899
2900/*
2901** CAPI3REF: SQL Statement Object
2902** KEYWORDS: {prepared statement} {prepared statements}
2903**
2904** An instance of this object represents a single SQL statement.
2905** This object is variously known as a "prepared statement" or a
2906** "compiled SQL statement" or simply as a "statement".
2907**
2908** The life of a statement object goes something like this:
2909**
2910** <ol>
2911** <li> Create the object using [sqlite3_prepare_v2()] or a related
2912**      function.
2913** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2914**      interfaces.
2915** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2916** <li> Reset the statement using [sqlite3_reset()] then go back
2917**      to step 2.  Do this zero or more times.
2918** <li> Destroy the object using [sqlite3_finalize()].
2919** </ol>
2920**
2921** Refer to documentation on individual methods above for additional
2922** information.
2923*/
2924typedef struct sqlite3_stmt sqlite3_stmt;
2925
2926/*
2927** CAPI3REF: Run-time Limits
2928**
2929** ^(This interface allows the size of various constructs to be limited
2930** on a connection by connection basis.  The first parameter is the
2931** [database connection] whose limit is to be set or queried.  The
2932** second parameter is one of the [limit categories] that define a
2933** class of constructs to be size limited.  The third parameter is the
2934** new limit for that construct.  The function returns the old limit.)^
2935**
2936** ^If the new limit is a negative number, the limit is unchanged.
2937** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2938** [limits | hard upper bound]
2939** set by a compile-time C preprocessor macro named
2940** [limits | SQLITE_MAX_XYZ].
2941** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2942** ^Attempts to increase a limit above its hard upper bound are
2943** silently truncated to the hard upper bound.
2944**
2945** Run-time limits are intended for use in applications that manage
2946** both their own internal database and also databases that are controlled
2947** by untrusted external sources.  An example application might be a
2948** web browser that has its own databases for storing history and
2949** separate databases controlled by JavaScript applications downloaded
2950** off the Internet.  The internal databases can be given the
2951** large, default limits.  Databases managed by external sources can
2952** be given much smaller limits designed to prevent a denial of service
2953** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2954** interface to further control untrusted SQL.  The size of the database
2955** created by an untrusted script can be contained using the
2956** [max_page_count] [PRAGMA].
2957**
2958** New run-time limit categories may be added in future releases.
2959*/
2960SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2961
2962/*
2963** CAPI3REF: Run-Time Limit Categories
2964** KEYWORDS: {limit category} {*limit categories}
2965**
2966** These constants define various performance limits
2967** that can be lowered at run-time using [sqlite3_limit()].
2968** The synopsis of the meanings of the various limits is shown below.
2969** Additional information is available at [limits | Limits in SQLite].
2970**
2971** <dl>
2972** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2973** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2974**
2975** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2976** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2977**
2978** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2979** <dd>The maximum number of columns in a table definition or in the
2980** result set of a [SELECT] or the maximum number of columns in an index
2981** or in an ORDER BY or GROUP BY clause.</dd>)^
2982**
2983** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2984** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2985**
2986** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2987** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2988**
2989** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2990** <dd>The maximum number of instructions in a virtual machine program
2991** used to implement an SQL statement.</dd>)^
2992**
2993** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2994** <dd>The maximum number of arguments on a function.</dd>)^
2995**
2996** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2997** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2998**
2999** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3000** <dd>The maximum length of the pattern argument to the [LIKE] or
3001** [GLOB] operators.</dd>)^
3002**
3003** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3004** <dd>The maximum number of variables in an SQL statement that can
3005** be bound.</dd>)^
3006**
3007** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3008** <dd>The maximum depth of recursion for triggers.</dd>)^
3009** </dl>
3010*/
3011#define SQLITE_LIMIT_LENGTH                    0
3012#define SQLITE_LIMIT_SQL_LENGTH                1
3013#define SQLITE_LIMIT_COLUMN                    2
3014#define SQLITE_LIMIT_EXPR_DEPTH                3
3015#define SQLITE_LIMIT_COMPOUND_SELECT           4
3016#define SQLITE_LIMIT_VDBE_OP                   5
3017#define SQLITE_LIMIT_FUNCTION_ARG              6
3018#define SQLITE_LIMIT_ATTACHED                  7
3019#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3020#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3021#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3022
3023/*
3024** CAPI3REF: Compiling An SQL Statement
3025** KEYWORDS: {SQL statement compiler}
3026**
3027** To execute an SQL query, it must first be compiled into a byte-code
3028** program using one of these routines.
3029**
3030** The first argument, "db", is a [database connection] obtained from a
3031** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3032** [sqlite3_open16()].  The database connection must not have been closed.
3033**
3034** The second argument, "zSql", is the statement to be compiled, encoded
3035** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3036** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3037** use UTF-16.
3038**
3039** ^If the nByte argument is less than zero, then zSql is read up to the
3040** first zero terminator. ^If nByte is non-negative, then it is the maximum
3041** number of  bytes read from zSql.  ^When nByte is non-negative, the
3042** zSql string ends at either the first '\000' or '\u0000' character or
3043** the nByte-th byte, whichever comes first. If the caller knows
3044** that the supplied string is nul-terminated, then there is a small
3045** performance advantage to be gained by passing an nByte parameter that
3046** is equal to the number of bytes in the input string <i>including</i>
3047** the nul-terminator bytes.
3048**
3049** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3050** past the end of the first SQL statement in zSql.  These routines only
3051** compile the first statement in zSql, so *pzTail is left pointing to
3052** what remains uncompiled.
3053**
3054** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3055** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3056** to NULL.  ^If the input text contains no SQL (if the input is an empty
3057** string or a comment) then *ppStmt is set to NULL.
3058** The calling procedure is responsible for deleting the compiled
3059** SQL statement using [sqlite3_finalize()] after it has finished with it.
3060** ppStmt may not be NULL.
3061**
3062** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3063** otherwise an [error code] is returned.
3064**
3065** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3066** recommended for all new programs. The two older interfaces are retained
3067** for backwards compatibility, but their use is discouraged.
3068** ^In the "v2" interfaces, the prepared statement
3069** that is returned (the [sqlite3_stmt] object) contains a copy of the
3070** original SQL text. This causes the [sqlite3_step()] interface to
3071** behave differently in three ways:
3072**
3073** <ol>
3074** <li>
3075** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3076** always used to do, [sqlite3_step()] will automatically recompile the SQL
3077** statement and try to run it again.  ^If the schema has changed in
3078** a way that makes the statement no longer valid, [sqlite3_step()] will still
3079** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
3080** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
3081** error go away.  Note: use [sqlite3_errmsg()] to find the text
3082** of the parsing error that results in an [SQLITE_SCHEMA] return.
3083** </li>
3084**
3085** <li>
3086** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3087** [error codes] or [extended error codes].  ^The legacy behavior was that
3088** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3089** and the application would have to make a second call to [sqlite3_reset()]
3090** in order to find the underlying cause of the problem. With the "v2" prepare
3091** interfaces, the underlying reason for the error is returned immediately.
3092** </li>
3093**
3094** <li>
3095** ^If the value of a [parameter | host parameter] in the WHERE clause might
3096** change the query plan for a statement, then the statement may be
3097** automatically recompiled (as if there had been a schema change) on the first
3098** [sqlite3_step()] call following any change to the
3099** [sqlite3_bind_text | bindings] of the [parameter].
3100** </li>
3101** </ol>
3102*/
3103SQLITE_API int sqlite3_prepare(
3104  sqlite3 *db,            /* Database handle */
3105  const char *zSql,       /* SQL statement, UTF-8 encoded */
3106  int nByte,              /* Maximum length of zSql in bytes. */
3107  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3108  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3109);
3110SQLITE_API int sqlite3_prepare_v2(
3111  sqlite3 *db,            /* Database handle */
3112  const char *zSql,       /* SQL statement, UTF-8 encoded */
3113  int nByte,              /* Maximum length of zSql in bytes. */
3114  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3115  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3116);
3117SQLITE_API int sqlite3_prepare16(
3118  sqlite3 *db,            /* Database handle */
3119  const void *zSql,       /* SQL statement, UTF-16 encoded */
3120  int nByte,              /* Maximum length of zSql in bytes. */
3121  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3122  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3123);
3124SQLITE_API int sqlite3_prepare16_v2(
3125  sqlite3 *db,            /* Database handle */
3126  const void *zSql,       /* SQL statement, UTF-16 encoded */
3127  int nByte,              /* Maximum length of zSql in bytes. */
3128  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3129  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3130);
3131
3132/*
3133** CAPI3REF: Retrieving Statement SQL
3134**
3135** ^This interface can be used to retrieve a saved copy of the original
3136** SQL text used to create a [prepared statement] if that statement was
3137** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3138*/
3139SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3140
3141/*
3142** CAPI3REF: Dynamically Typed Value Object
3143** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3144**
3145** SQLite uses the sqlite3_value object to represent all values
3146** that can be stored in a database table. SQLite uses dynamic typing
3147** for the values it stores.  ^Values stored in sqlite3_value objects
3148** can be integers, floating point values, strings, BLOBs, or NULL.
3149**
3150** An sqlite3_value object may be either "protected" or "unprotected".
3151** Some interfaces require a protected sqlite3_value.  Other interfaces
3152** will accept either a protected or an unprotected sqlite3_value.
3153** Every interface that accepts sqlite3_value arguments specifies
3154** whether or not it requires a protected sqlite3_value.
3155**
3156** The terms "protected" and "unprotected" refer to whether or not
3157** a mutex is held.  A internal mutex is held for a protected
3158** sqlite3_value object but no mutex is held for an unprotected
3159** sqlite3_value object.  If SQLite is compiled to be single-threaded
3160** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3161** or if SQLite is run in one of reduced mutex modes
3162** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3163** then there is no distinction between protected and unprotected
3164** sqlite3_value objects and they can be used interchangeably.  However,
3165** for maximum code portability it is recommended that applications
3166** still make the distinction between between protected and unprotected
3167** sqlite3_value objects even when not strictly required.
3168**
3169** ^The sqlite3_value objects that are passed as parameters into the
3170** implementation of [application-defined SQL functions] are protected.
3171** ^The sqlite3_value object returned by
3172** [sqlite3_column_value()] is unprotected.
3173** Unprotected sqlite3_value objects may only be used with
3174** [sqlite3_result_value()] and [sqlite3_bind_value()].
3175** The [sqlite3_value_blob | sqlite3_value_type()] family of
3176** interfaces require protected sqlite3_value objects.
3177*/
3178typedef struct Mem sqlite3_value;
3179
3180/*
3181** CAPI3REF: SQL Function Context Object
3182**
3183** The context in which an SQL function executes is stored in an
3184** sqlite3_context object.  ^A pointer to an sqlite3_context object
3185** is always first parameter to [application-defined SQL functions].
3186** The application-defined SQL function implementation will pass this
3187** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3188** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3189** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3190** and/or [sqlite3_set_auxdata()].
3191*/
3192typedef struct sqlite3_context sqlite3_context;
3193
3194/*
3195** CAPI3REF: Binding Values To Prepared Statements
3196** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3197** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3198**
3199** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3200** literals may be replaced by a [parameter] that matches one of following
3201** templates:
3202**
3203** <ul>
3204** <li>  ?
3205** <li>  ?NNN
3206** <li>  :VVV
3207** <li>  @VVV
3208** <li>  $VVV
3209** </ul>
3210**
3211** In the templates above, NNN represents an integer literal,
3212** and VVV represents an alphanumeric identifier.)^  ^The values of these
3213** parameters (also called "host parameter names" or "SQL parameters")
3214** can be set using the sqlite3_bind_*() routines defined here.
3215**
3216** ^The first argument to the sqlite3_bind_*() routines is always
3217** a pointer to the [sqlite3_stmt] object returned from
3218** [sqlite3_prepare_v2()] or its variants.
3219**
3220** ^The second argument is the index of the SQL parameter to be set.
3221** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3222** SQL parameter is used more than once, second and subsequent
3223** occurrences have the same index as the first occurrence.
3224** ^The index for named parameters can be looked up using the
3225** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3226** for "?NNN" parameters is the value of NNN.
3227** ^The NNN value must be between 1 and the [sqlite3_limit()]
3228** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3229**
3230** ^The third argument is the value to bind to the parameter.
3231**
3232** ^(In those routines that have a fourth argument, its value is the
3233** number of bytes in the parameter.  To be clear: the value is the
3234** number of <u>bytes</u> in the value, not the number of characters.)^
3235** ^If the fourth parameter is negative, the length of the string is
3236** the number of bytes up to the first zero terminator.
3237**
3238** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3239** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3240** string after SQLite has finished with it. ^If the fifth argument is
3241** the special value [SQLITE_STATIC], then SQLite assumes that the
3242** information is in static, unmanaged space and does not need to be freed.
3243** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3244** SQLite makes its own private copy of the data immediately, before
3245** the sqlite3_bind_*() routine returns.
3246**
3247** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3248** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3249** (just an integer to hold its size) while it is being processed.
3250** Zeroblobs are intended to serve as placeholders for BLOBs whose
3251** content is later written using
3252** [sqlite3_blob_open | incremental BLOB I/O] routines.
3253** ^A negative value for the zeroblob results in a zero-length BLOB.
3254**
3255** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3256** for the [prepared statement] or with a prepared statement for which
3257** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3258** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3259** routine is passed a [prepared statement] that has been finalized, the
3260** result is undefined and probably harmful.
3261**
3262** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3263** ^Unbound parameters are interpreted as NULL.
3264**
3265** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3266** [error code] if anything goes wrong.
3267** ^[SQLITE_RANGE] is returned if the parameter
3268** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3269**
3270** See also: [sqlite3_bind_parameter_count()],
3271** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3272*/
3273SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3274SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3275SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3276SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3277SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3278SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3279SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3280SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3281SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3282
3283/*
3284** CAPI3REF: Number Of SQL Parameters
3285**
3286** ^This routine can be used to find the number of [SQL parameters]
3287** in a [prepared statement].  SQL parameters are tokens of the
3288** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3289** placeholders for values that are [sqlite3_bind_blob | bound]
3290** to the parameters at a later time.
3291**
3292** ^(This routine actually returns the index of the largest (rightmost)
3293** parameter. For all forms except ?NNN, this will correspond to the
3294** number of unique parameters.  If parameters of the ?NNN form are used,
3295** there may be gaps in the list.)^
3296**
3297** See also: [sqlite3_bind_blob|sqlite3_bind()],
3298** [sqlite3_bind_parameter_name()], and
3299** [sqlite3_bind_parameter_index()].
3300*/
3301SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3302
3303/*
3304** CAPI3REF: Name Of A Host Parameter
3305**
3306** ^The sqlite3_bind_parameter_name(P,N) interface returns
3307** the name of the N-th [SQL parameter] in the [prepared statement] P.
3308** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3309** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3310** respectively.
3311** In other words, the initial ":" or "$" or "@" or "?"
3312** is included as part of the name.)^
3313** ^Parameters of the form "?" without a following integer have no name
3314** and are referred to as "nameless" or "anonymous parameters".
3315**
3316** ^The first host parameter has an index of 1, not 0.
3317**
3318** ^If the value N is out of range or if the N-th parameter is
3319** nameless, then NULL is returned.  ^The returned string is
3320** always in UTF-8 encoding even if the named parameter was
3321** originally specified as UTF-16 in [sqlite3_prepare16()] or
3322** [sqlite3_prepare16_v2()].
3323**
3324** See also: [sqlite3_bind_blob|sqlite3_bind()],
3325** [sqlite3_bind_parameter_count()], and
3326** [sqlite3_bind_parameter_index()].
3327*/
3328SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3329
3330/*
3331** CAPI3REF: Index Of A Parameter With A Given Name
3332**
3333** ^Return the index of an SQL parameter given its name.  ^The
3334** index value returned is suitable for use as the second
3335** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3336** is returned if no matching parameter is found.  ^The parameter
3337** name must be given in UTF-8 even if the original statement
3338** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3339**
3340** See also: [sqlite3_bind_blob|sqlite3_bind()],
3341** [sqlite3_bind_parameter_count()], and
3342** [sqlite3_bind_parameter_index()].
3343*/
3344SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3345
3346/*
3347** CAPI3REF: Reset All Bindings On A Prepared Statement
3348**
3349** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3350** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3351** ^Use this routine to reset all host parameters to NULL.
3352*/
3353SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3354
3355/*
3356** CAPI3REF: Number Of Columns In A Result Set
3357**
3358** ^Return the number of columns in the result set returned by the
3359** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3360** statement that does not return data (for example an [UPDATE]).
3361*/
3362SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3363
3364/*
3365** CAPI3REF: Column Names In A Result Set
3366**
3367** ^These routines return the name assigned to a particular column
3368** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3369** interface returns a pointer to a zero-terminated UTF-8 string
3370** and sqlite3_column_name16() returns a pointer to a zero-terminated
3371** UTF-16 string.  ^The first parameter is the [prepared statement]
3372** that implements the [SELECT] statement. ^The second parameter is the
3373** column number.  ^The leftmost column is number 0.
3374**
3375** ^The returned string pointer is valid until either the [prepared statement]
3376** is destroyed by [sqlite3_finalize()] or until the next call to
3377** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3378**
3379** ^If sqlite3_malloc() fails during the processing of either routine
3380** (for example during a conversion from UTF-8 to UTF-16) then a
3381** NULL pointer is returned.
3382**
3383** ^The name of a result column is the value of the "AS" clause for
3384** that column, if there is an AS clause.  If there is no AS clause
3385** then the name of the column is unspecified and may change from
3386** one release of SQLite to the next.
3387*/
3388SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3389SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3390
3391/*
3392** CAPI3REF: Source Of Data In A Query Result
3393**
3394** ^These routines provide a means to determine the database, table, and
3395** table column that is the origin of a particular result column in
3396** [SELECT] statement.
3397** ^The name of the database or table or column can be returned as
3398** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3399** the database name, the _table_ routines return the table name, and
3400** the origin_ routines return the column name.
3401** ^The returned string is valid until the [prepared statement] is destroyed
3402** using [sqlite3_finalize()] or until the same information is requested
3403** again in a different encoding.
3404**
3405** ^The names returned are the original un-aliased names of the
3406** database, table, and column.
3407**
3408** ^The first argument to these interfaces is a [prepared statement].
3409** ^These functions return information about the Nth result column returned by
3410** the statement, where N is the second function argument.
3411** ^The left-most column is column 0 for these routines.
3412**
3413** ^If the Nth column returned by the statement is an expression or
3414** subquery and is not a column value, then all of these functions return
3415** NULL.  ^These routine might also return NULL if a memory allocation error
3416** occurs.  ^Otherwise, they return the name of the attached database, table,
3417** or column that query result column was extracted from.
3418**
3419** ^As with all other SQLite APIs, those whose names end with "16" return
3420** UTF-16 encoded strings and the other functions return UTF-8.
3421**
3422** ^These APIs are only available if the library was compiled with the
3423** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3424**
3425** If two or more threads call one or more of these routines against the same
3426** prepared statement and column at the same time then the results are
3427** undefined.
3428**
3429** If two or more threads call one or more
3430** [sqlite3_column_database_name | column metadata interfaces]
3431** for the same [prepared statement] and result column
3432** at the same time then the results are undefined.
3433*/
3434SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3435SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3436SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3437SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3438SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3439SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3440
3441/*
3442** CAPI3REF: Declared Datatype Of A Query Result
3443**
3444** ^(The first parameter is a [prepared statement].
3445** If this statement is a [SELECT] statement and the Nth column of the
3446** returned result set of that [SELECT] is a table column (not an
3447** expression or subquery) then the declared type of the table
3448** column is returned.)^  ^If the Nth column of the result set is an
3449** expression or subquery, then a NULL pointer is returned.
3450** ^The returned string is always UTF-8 encoded.
3451**
3452** ^(For example, given the database schema:
3453**
3454** CREATE TABLE t1(c1 VARIANT);
3455**
3456** and the following statement to be compiled:
3457**
3458** SELECT c1 + 1, c1 FROM t1;
3459**
3460** this routine would return the string "VARIANT" for the second result
3461** column (i==1), and a NULL pointer for the first result column (i==0).)^
3462**
3463** ^SQLite uses dynamic run-time typing.  ^So just because a column
3464** is declared to contain a particular type does not mean that the
3465** data stored in that column is of the declared type.  SQLite is
3466** strongly typed, but the typing is dynamic not static.  ^Type
3467** is associated with individual values, not with the containers
3468** used to hold those values.
3469*/
3470SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3471SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3472
3473/*
3474** CAPI3REF: Evaluate An SQL Statement
3475**
3476** After a [prepared statement] has been prepared using either
3477** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3478** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3479** must be called one or more times to evaluate the statement.
3480**
3481** The details of the behavior of the sqlite3_step() interface depend
3482** on whether the statement was prepared using the newer "v2" interface
3483** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3484** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3485** new "v2" interface is recommended for new applications but the legacy
3486** interface will continue to be supported.
3487**
3488** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3489** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3490** ^With the "v2" interface, any of the other [result codes] or
3491** [extended result codes] might be returned as well.
3492**
3493** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3494** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3495** or occurs outside of an explicit transaction, then you can retry the
3496** statement.  If the statement is not a [COMMIT] and occurs within a
3497** explicit transaction then you should rollback the transaction before
3498** continuing.
3499**
3500** ^[SQLITE_DONE] means that the statement has finished executing
3501** successfully.  sqlite3_step() should not be called again on this virtual
3502** machine without first calling [sqlite3_reset()] to reset the virtual
3503** machine back to its initial state.
3504**
3505** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3506** is returned each time a new row of data is ready for processing by the
3507** caller. The values may be accessed using the [column access functions].
3508** sqlite3_step() is called again to retrieve the next row of data.
3509**
3510** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3511** violation) has occurred.  sqlite3_step() should not be called again on
3512** the VM. More information may be found by calling [sqlite3_errmsg()].
3513** ^With the legacy interface, a more specific error code (for example,
3514** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3515** can be obtained by calling [sqlite3_reset()] on the
3516** [prepared statement].  ^In the "v2" interface,
3517** the more specific error code is returned directly by sqlite3_step().
3518**
3519** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3520** Perhaps it was called on a [prepared statement] that has
3521** already been [sqlite3_finalize | finalized] or on one that had
3522** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3523** be the case that the same database connection is being used by two or
3524** more threads at the same moment in time.
3525**
3526** For all versions of SQLite up to and including 3.6.23.1, it was required
3527** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3528** [sqlite3_reset()] be called before any subsequent invocation of
3529** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3530** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3531** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()]
3532** automatically in this circumstance rather than returning [SQLITE_MISUSE].
3533**
3534** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3535** API always returns a generic error code, [SQLITE_ERROR], following any
3536** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3537** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3538** specific [error codes] that better describes the error.
3539** We admit that this is a goofy design.  The problem has been fixed
3540** with the "v2" interface.  If you prepare all of your SQL statements
3541** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3542** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3543** then the more specific [error codes] are returned directly
3544** by sqlite3_step().  The use of the "v2" interface is recommended.
3545*/
3546SQLITE_API int sqlite3_step(sqlite3_stmt*);
3547
3548/*
3549** CAPI3REF: Number of columns in a result set
3550**
3551** ^The sqlite3_data_count(P) the number of columns in the
3552** of the result set of [prepared statement] P.
3553*/
3554SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3555
3556/*
3557** CAPI3REF: Fundamental Datatypes
3558** KEYWORDS: SQLITE_TEXT
3559**
3560** ^(Every value in SQLite has one of five fundamental datatypes:
3561**
3562** <ul>
3563** <li> 64-bit signed integer
3564** <li> 64-bit IEEE floating point number
3565** <li> string
3566** <li> BLOB
3567** <li> NULL
3568** </ul>)^
3569**
3570** These constants are codes for each of those types.
3571**
3572** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3573** for a completely different meaning.  Software that links against both
3574** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3575** SQLITE_TEXT.
3576*/
3577#define SQLITE_INTEGER  1
3578#define SQLITE_FLOAT    2
3579#define SQLITE_BLOB     4
3580#define SQLITE_NULL     5
3581#ifdef SQLITE_TEXT
3582# undef SQLITE_TEXT
3583#else
3584# define SQLITE_TEXT     3
3585#endif
3586#define SQLITE3_TEXT     3
3587
3588/*
3589** CAPI3REF: Result Values From A Query
3590** KEYWORDS: {column access functions}
3591**
3592** These routines form the "result set" interface.
3593**
3594** ^These routines return information about a single column of the current
3595** result row of a query.  ^In every case the first argument is a pointer
3596** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3597** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3598** and the second argument is the index of the column for which information
3599** should be returned. ^The leftmost column of the result set has the index 0.
3600** ^The number of columns in the result can be determined using
3601** [sqlite3_column_count()].
3602**
3603** If the SQL statement does not currently point to a valid row, or if the
3604** column index is out of range, the result is undefined.
3605** These routines may only be called when the most recent call to
3606** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3607** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3608** If any of these routines are called after [sqlite3_reset()] or
3609** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3610** something other than [SQLITE_ROW], the results are undefined.
3611** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3612** are called from a different thread while any of these routines
3613** are pending, then the results are undefined.
3614**
3615** ^The sqlite3_column_type() routine returns the
3616** [SQLITE_INTEGER | datatype code] for the initial data type
3617** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3618** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3619** returned by sqlite3_column_type() is only meaningful if no type
3620** conversions have occurred as described below.  After a type conversion,
3621** the value returned by sqlite3_column_type() is undefined.  Future
3622** versions of SQLite may change the behavior of sqlite3_column_type()
3623** following a type conversion.
3624**
3625** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3626** routine returns the number of bytes in that BLOB or string.
3627** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3628** the string to UTF-8 and then returns the number of bytes.
3629** ^If the result is a numeric value then sqlite3_column_bytes() uses
3630** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3631** the number of bytes in that string.
3632** ^The value returned does not include the zero terminator at the end
3633** of the string.  ^For clarity: the value returned is the number of
3634** bytes in the string, not the number of characters.
3635**
3636** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3637** even empty strings, are always zero terminated.  ^The return
3638** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3639** pointer, possibly even a NULL pointer.
3640**
3641** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3642** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3643** ^The zero terminator is not included in this count.
3644**
3645** ^The object returned by [sqlite3_column_value()] is an
3646** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3647** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3648** If the [unprotected sqlite3_value] object returned by
3649** [sqlite3_column_value()] is used in any other way, including calls
3650** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3651** or [sqlite3_value_bytes()], then the behavior is undefined.
3652**
3653** These routines attempt to convert the value where appropriate.  ^For
3654** example, if the internal representation is FLOAT and a text result
3655** is requested, [sqlite3_snprintf()] is used internally to perform the
3656** conversion automatically.  ^(The following table details the conversions
3657** that are applied:
3658**
3659** <blockquote>
3660** <table border="1">
3661** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3662**
3663** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3664** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3665** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3666** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3667** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3668** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3669** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3670** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3671** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3672** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3673** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3674** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3675** <tr><td>  TEXT    <td>   BLOB    <td> No change
3676** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3677** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3678** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3679** </table>
3680** </blockquote>)^
3681**
3682** The table above makes reference to standard C library functions atoi()
3683** and atof().  SQLite does not really use these functions.  It has its
3684** own equivalent internal routines.  The atoi() and atof() names are
3685** used in the table for brevity and because they are familiar to most
3686** C programmers.
3687**
3688** ^Note that when type conversions occur, pointers returned by prior
3689** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3690** sqlite3_column_text16() may be invalidated.
3691** ^(Type conversions and pointer invalidations might occur
3692** in the following cases:
3693**
3694** <ul>
3695** <li> The initial content is a BLOB and sqlite3_column_text() or
3696**      sqlite3_column_text16() is called.  A zero-terminator might
3697**      need to be added to the string.</li>
3698** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3699**      sqlite3_column_text16() is called.  The content must be converted
3700**      to UTF-16.</li>
3701** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3702**      sqlite3_column_text() is called.  The content must be converted
3703**      to UTF-8.</li>
3704** </ul>)^
3705**
3706** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3707** not invalidate a prior pointer, though of course the content of the buffer
3708** that the prior pointer points to will have been modified.  Other kinds
3709** of conversion are done in place when it is possible, but sometimes they
3710** are not possible and in those cases prior pointers are invalidated.
3711**
3712** ^(The safest and easiest to remember policy is to invoke these routines
3713** in one of the following ways:
3714**
3715** <ul>
3716**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3717**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3718**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3719** </ul>)^
3720**
3721** In other words, you should call sqlite3_column_text(),
3722** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3723** into the desired format, then invoke sqlite3_column_bytes() or
3724** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3725** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3726** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3727** with calls to sqlite3_column_bytes().
3728**
3729** ^The pointers returned are valid until a type conversion occurs as
3730** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3731** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3732** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3733** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3734** [sqlite3_free()].
3735**
3736** ^(If a memory allocation error occurs during the evaluation of any
3737** of these routines, a default value is returned.  The default value
3738** is either the integer 0, the floating point number 0.0, or a NULL
3739** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3740** [SQLITE_NOMEM].)^
3741*/
3742SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3743SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3744SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3745SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3746SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3747SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3748SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3749SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3750SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3751SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3752
3753/*
3754** CAPI3REF: Destroy A Prepared Statement Object
3755**
3756** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3757** ^If the statement was executed successfully or not executed at all, then
3758** SQLITE_OK is returned. ^If execution of the statement failed then an
3759** [error code] or [extended error code] is returned.
3760**
3761** ^This routine can be called at any point during the execution of the
3762** [prepared statement].  ^If the virtual machine has not
3763** completed execution when this routine is called, that is like
3764** encountering an error or an [sqlite3_interrupt | interrupt].
3765** ^Incomplete updates may be rolled back and transactions canceled,
3766** depending on the circumstances, and the
3767** [error code] returned will be [SQLITE_ABORT].
3768*/
3769SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3770
3771/*
3772** CAPI3REF: Reset A Prepared Statement Object
3773**
3774** The sqlite3_reset() function is called to reset a [prepared statement]
3775** object back to its initial state, ready to be re-executed.
3776** ^Any SQL statement variables that had values bound to them using
3777** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3778** Use [sqlite3_clear_bindings()] to reset the bindings.
3779**
3780** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3781** back to the beginning of its program.
3782**
3783** ^If the most recent call to [sqlite3_step(S)] for the
3784** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3785** or if [sqlite3_step(S)] has never before been called on S,
3786** then [sqlite3_reset(S)] returns [SQLITE_OK].
3787**
3788** ^If the most recent call to [sqlite3_step(S)] for the
3789** [prepared statement] S indicated an error, then
3790** [sqlite3_reset(S)] returns an appropriate [error code].
3791**
3792** ^The [sqlite3_reset(S)] interface does not change the values
3793** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3794*/
3795SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3796
3797/*
3798** CAPI3REF: Create Or Redefine SQL Functions
3799** KEYWORDS: {function creation routines}
3800** KEYWORDS: {application-defined SQL function}
3801** KEYWORDS: {application-defined SQL functions}
3802**
3803** ^These two functions (collectively known as "function creation routines")
3804** are used to add SQL functions or aggregates or to redefine the behavior
3805** of existing SQL functions or aggregates.  The only difference between the
3806** two is that the second parameter, the name of the (scalar) function or
3807** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3808** for sqlite3_create_function16().
3809**
3810** ^The first parameter is the [database connection] to which the SQL
3811** function is to be added.  ^If an application uses more than one database
3812** connection then application-defined SQL functions must be added
3813** to each database connection separately.
3814**
3815** The second parameter is the name of the SQL function to be created or
3816** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3817** the zero-terminator.  Note that the name length limit is in bytes, not
3818** characters.  ^Any attempt to create a function with a longer name
3819** will result in [SQLITE_ERROR] being returned.
3820**
3821** ^The third parameter (nArg)
3822** is the number of arguments that the SQL function or
3823** aggregate takes. ^If this parameter is -1, then the SQL function or
3824** aggregate may take any number of arguments between 0 and the limit
3825** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3826** parameter is less than -1 or greater than 127 then the behavior is
3827** undefined.
3828**
3829** The fourth parameter, eTextRep, specifies what
3830** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3831** its parameters.  Any SQL function implementation should be able to work
3832** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3833** more efficient with one encoding than another.  ^An application may
3834** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3835** times with the same function but with different values of eTextRep.
3836** ^When multiple implementations of the same function are available, SQLite
3837** will pick the one that involves the least amount of data conversion.
3838** If there is only a single implementation which does not care what text
3839** encoding is used, then the fourth argument should be [SQLITE_ANY].
3840**
3841** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3842** function can gain access to this pointer using [sqlite3_user_data()].)^
3843**
3844** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3845** pointers to C-language functions that implement the SQL function or
3846** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3847** callback only; NULL pointers should be passed as the xStep and xFinal
3848** parameters. ^An aggregate SQL function requires an implementation of xStep
3849** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3850** SQL function or aggregate, pass NULL for all three function callbacks.
3851**
3852** ^It is permitted to register multiple implementations of the same
3853** functions with the same name but with either differing numbers of
3854** arguments or differing preferred text encodings.  ^SQLite will use
3855** the implementation that most closely matches the way in which the
3856** SQL function is used.  ^A function implementation with a non-negative
3857** nArg parameter is a better match than a function implementation with
3858** a negative nArg.  ^A function where the preferred text encoding
3859** matches the database encoding is a better
3860** match than a function where the encoding is different.
3861** ^A function where the encoding difference is between UTF16le and UTF16be
3862** is a closer match than a function where the encoding difference is
3863** between UTF8 and UTF16.
3864**
3865** ^Built-in functions may be overloaded by new application-defined functions.
3866** ^The first application-defined function with a given name overrides all
3867** built-in functions in the same [database connection] with the same name.
3868** ^Subsequent application-defined functions of the same name only override
3869** prior application-defined functions that are an exact match for the
3870** number of parameters and preferred encoding.
3871**
3872** ^An application-defined function is permitted to call other
3873** SQLite interfaces.  However, such calls must not
3874** close the database connection nor finalize or reset the prepared
3875** statement in which the function is running.
3876*/
3877SQLITE_API int sqlite3_create_function(
3878  sqlite3 *db,
3879  const char *zFunctionName,
3880  int nArg,
3881  int eTextRep,
3882  void *pApp,
3883  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3884  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3885  void (*xFinal)(sqlite3_context*)
3886);
3887SQLITE_API int sqlite3_create_function16(
3888  sqlite3 *db,
3889  const void *zFunctionName,
3890  int nArg,
3891  int eTextRep,
3892  void *pApp,
3893  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3894  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3895  void (*xFinal)(sqlite3_context*)
3896);
3897
3898/*
3899** CAPI3REF: Text Encodings
3900**
3901** These constant define integer codes that represent the various
3902** text encodings supported by SQLite.
3903*/
3904#define SQLITE_UTF8           1
3905#define SQLITE_UTF16LE        2
3906#define SQLITE_UTF16BE        3
3907#define SQLITE_UTF16          4    /* Use native byte order */
3908#define SQLITE_ANY            5    /* sqlite3_create_function only */
3909#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3910
3911/*
3912** CAPI3REF: Deprecated Functions
3913** DEPRECATED
3914**
3915** These functions are [deprecated].  In order to maintain
3916** backwards compatibility with older code, these functions continue
3917** to be supported.  However, new applications should avoid
3918** the use of these functions.  To help encourage people to avoid
3919** using these functions, we are not going to tell you what they do.
3920*/
3921#ifndef SQLITE_OMIT_DEPRECATED
3922SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3923SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3924SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3925SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3926SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3927SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3928#endif
3929
3930/*
3931** CAPI3REF: Obtaining SQL Function Parameter Values
3932**
3933** The C-language implementation of SQL functions and aggregates uses
3934** this set of interface routines to access the parameter values on
3935** the function or aggregate.
3936**
3937** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3938** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3939** define callbacks that implement the SQL functions and aggregates.
3940** The 4th parameter to these callbacks is an array of pointers to
3941** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3942** each parameter to the SQL function.  These routines are used to
3943** extract values from the [sqlite3_value] objects.
3944**
3945** These routines work only with [protected sqlite3_value] objects.
3946** Any attempt to use these routines on an [unprotected sqlite3_value]
3947** object results in undefined behavior.
3948**
3949** ^These routines work just like the corresponding [column access functions]
3950** except that  these routines take a single [protected sqlite3_value] object
3951** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3952**
3953** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3954** in the native byte-order of the host machine.  ^The
3955** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3956** extract UTF-16 strings as big-endian and little-endian respectively.
3957**
3958** ^(The sqlite3_value_numeric_type() interface attempts to apply
3959** numeric affinity to the value.  This means that an attempt is
3960** made to convert the value to an integer or floating point.  If
3961** such a conversion is possible without loss of information (in other
3962** words, if the value is a string that looks like a number)
3963** then the conversion is performed.  Otherwise no conversion occurs.
3964** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3965**
3966** Please pay particular attention to the fact that the pointer returned
3967** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3968** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3969** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3970** or [sqlite3_value_text16()].
3971**
3972** These routines must be called from the same thread as
3973** the SQL function that supplied the [sqlite3_value*] parameters.
3974*/
3975SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3976SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3977SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3978SQLITE_API double sqlite3_value_double(sqlite3_value*);
3979SQLITE_API int sqlite3_value_int(sqlite3_value*);
3980SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3981SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3982SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3983SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3984SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3985SQLITE_API int sqlite3_value_type(sqlite3_value*);
3986SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3987
3988/*
3989** CAPI3REF: Obtain Aggregate Function Context
3990**
3991** Implementations of aggregate SQL functions use this
3992** routine to allocate memory for storing their state.
3993**
3994** ^The first time the sqlite3_aggregate_context(C,N) routine is called
3995** for a particular aggregate function, SQLite
3996** allocates N of memory, zeroes out that memory, and returns a pointer
3997** to the new memory. ^On second and subsequent calls to
3998** sqlite3_aggregate_context() for the same aggregate function instance,
3999** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4000** called once for each invocation of the xStep callback and then one
4001** last time when the xFinal callback is invoked.  ^(When no rows match
4002** an aggregate query, the xStep() callback of the aggregate function
4003** implementation is never called and xFinal() is called exactly once.
4004** In those cases, sqlite3_aggregate_context() might be called for the
4005** first time from within xFinal().)^
4006**
4007** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4008** less than or equal to zero or if a memory allocate error occurs.
4009**
4010** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4011** determined by the N parameter on first successful call.  Changing the
4012** value of N in subsequent call to sqlite3_aggregate_context() within
4013** the same aggregate function instance will not resize the memory
4014** allocation.)^
4015**
4016** ^SQLite automatically frees the memory allocated by
4017** sqlite3_aggregate_context() when the aggregate query concludes.
4018**
4019** The first parameter must be a copy of the
4020** [sqlite3_context | SQL function context] that is the first parameter
4021** to the xStep or xFinal callback routine that implements the aggregate
4022** function.
4023**
4024** This routine must be called from the same thread in which
4025** the aggregate SQL function is running.
4026*/
4027SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4028
4029/*
4030** CAPI3REF: User Data For Functions
4031**
4032** ^The sqlite3_user_data() interface returns a copy of
4033** the pointer that was the pUserData parameter (the 5th parameter)
4034** of the [sqlite3_create_function()]
4035** and [sqlite3_create_function16()] routines that originally
4036** registered the application defined function.
4037**
4038** This routine must be called from the same thread in which
4039** the application-defined function is running.
4040*/
4041SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4042
4043/*
4044** CAPI3REF: Database Connection For Functions
4045**
4046** ^The sqlite3_context_db_handle() interface returns a copy of
4047** the pointer to the [database connection] (the 1st parameter)
4048** of the [sqlite3_create_function()]
4049** and [sqlite3_create_function16()] routines that originally
4050** registered the application defined function.
4051*/
4052SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4053
4054/*
4055** CAPI3REF: Function Auxiliary Data
4056**
4057** The following two functions may be used by scalar SQL functions to
4058** associate metadata with argument values. If the same value is passed to
4059** multiple invocations of the same SQL function during query execution, under
4060** some circumstances the associated metadata may be preserved. This may
4061** be used, for example, to add a regular-expression matching scalar
4062** function. The compiled version of the regular expression is stored as
4063** metadata associated with the SQL value passed as the regular expression
4064** pattern.  The compiled regular expression can be reused on multiple
4065** invocations of the same function so that the original pattern string
4066** does not need to be recompiled on each invocation.
4067**
4068** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4069** associated by the sqlite3_set_auxdata() function with the Nth argument
4070** value to the application-defined function. ^If no metadata has been ever
4071** been set for the Nth argument of the function, or if the corresponding
4072** function parameter has changed since the meta-data was set,
4073** then sqlite3_get_auxdata() returns a NULL pointer.
4074**
4075** ^The sqlite3_set_auxdata() interface saves the metadata
4076** pointed to by its 3rd parameter as the metadata for the N-th
4077** argument of the application-defined function.  Subsequent
4078** calls to sqlite3_get_auxdata() might return this data, if it has
4079** not been destroyed.
4080** ^If it is not NULL, SQLite will invoke the destructor
4081** function given by the 4th parameter to sqlite3_set_auxdata() on
4082** the metadata when the corresponding function parameter changes
4083** or when the SQL statement completes, whichever comes first.
4084**
4085** SQLite is free to call the destructor and drop metadata on any
4086** parameter of any function at any time.  ^The only guarantee is that
4087** the destructor will be called before the metadata is dropped.
4088**
4089** ^(In practice, metadata is preserved between function calls for
4090** expressions that are constant at compile time. This includes literal
4091** values and [parameters].)^
4092**
4093** These routines must be called from the same thread in which
4094** the SQL function is running.
4095*/
4096SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4097SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4098
4099
4100/*
4101** CAPI3REF: Constants Defining Special Destructor Behavior
4102**
4103** These are special values for the destructor that is passed in as the
4104** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4105** argument is SQLITE_STATIC, it means that the content pointer is constant
4106** and will never change.  It does not need to be destroyed.  ^The
4107** SQLITE_TRANSIENT value means that the content will likely change in
4108** the near future and that SQLite should make its own private copy of
4109** the content before returning.
4110**
4111** The typedef is necessary to work around problems in certain
4112** C++ compilers.  See ticket #2191.
4113*/
4114typedef void (*sqlite3_destructor_type)(void*);
4115#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4116#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4117
4118/*
4119** CAPI3REF: Setting The Result Of An SQL Function
4120**
4121** These routines are used by the xFunc or xFinal callbacks that
4122** implement SQL functions and aggregates.  See
4123** [sqlite3_create_function()] and [sqlite3_create_function16()]
4124** for additional information.
4125**
4126** These functions work very much like the [parameter binding] family of
4127** functions used to bind values to host parameters in prepared statements.
4128** Refer to the [SQL parameter] documentation for additional information.
4129**
4130** ^The sqlite3_result_blob() interface sets the result from
4131** an application-defined function to be the BLOB whose content is pointed
4132** to by the second parameter and which is N bytes long where N is the
4133** third parameter.
4134**
4135** ^The sqlite3_result_zeroblob() interfaces set the result of
4136** the application-defined function to be a BLOB containing all zero
4137** bytes and N bytes in size, where N is the value of the 2nd parameter.
4138**
4139** ^The sqlite3_result_double() interface sets the result from
4140** an application-defined function to be a floating point value specified
4141** by its 2nd argument.
4142**
4143** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4144** cause the implemented SQL function to throw an exception.
4145** ^SQLite uses the string pointed to by the
4146** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4147** as the text of an error message.  ^SQLite interprets the error
4148** message string from sqlite3_result_error() as UTF-8. ^SQLite
4149** interprets the string from sqlite3_result_error16() as UTF-16 in native
4150** byte order.  ^If the third parameter to sqlite3_result_error()
4151** or sqlite3_result_error16() is negative then SQLite takes as the error
4152** message all text up through the first zero character.
4153** ^If the third parameter to sqlite3_result_error() or
4154** sqlite3_result_error16() is non-negative then SQLite takes that many
4155** bytes (not characters) from the 2nd parameter as the error message.
4156** ^The sqlite3_result_error() and sqlite3_result_error16()
4157** routines make a private copy of the error message text before
4158** they return.  Hence, the calling function can deallocate or
4159** modify the text after they return without harm.
4160** ^The sqlite3_result_error_code() function changes the error code
4161** returned by SQLite as a result of an error in a function.  ^By default,
4162** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4163** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4164**
4165** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4166** indicating that a string or BLOB is too long to represent.
4167**
4168** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4169** indicating that a memory allocation failed.
4170**
4171** ^The sqlite3_result_int() interface sets the return value
4172** of the application-defined function to be the 32-bit signed integer
4173** value given in the 2nd argument.
4174** ^The sqlite3_result_int64() interface sets the return value
4175** of the application-defined function to be the 64-bit signed integer
4176** value given in the 2nd argument.
4177**
4178** ^The sqlite3_result_null() interface sets the return value
4179** of the application-defined function to be NULL.
4180**
4181** ^The sqlite3_result_text(), sqlite3_result_text16(),
4182** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4183** set the return value of the application-defined function to be
4184** a text string which is represented as UTF-8, UTF-16 native byte order,
4185** UTF-16 little endian, or UTF-16 big endian, respectively.
4186** ^SQLite takes the text result from the application from
4187** the 2nd parameter of the sqlite3_result_text* interfaces.
4188** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4189** is negative, then SQLite takes result text from the 2nd parameter
4190** through the first zero character.
4191** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4192** is non-negative, then as many bytes (not characters) of the text
4193** pointed to by the 2nd parameter are taken as the application-defined
4194** function result.
4195** ^If the 4th parameter to the sqlite3_result_text* interfaces
4196** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4197** function as the destructor on the text or BLOB result when it has
4198** finished using that result.
4199** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4200** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4201** assumes that the text or BLOB result is in constant space and does not
4202** copy the content of the parameter nor call a destructor on the content
4203** when it has finished using that result.
4204** ^If the 4th parameter to the sqlite3_result_text* interfaces
4205** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4206** then SQLite makes a copy of the result into space obtained from
4207** from [sqlite3_malloc()] before it returns.
4208**
4209** ^The sqlite3_result_value() interface sets the result of
4210** the application-defined function to be a copy the
4211** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4212** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4213** so that the [sqlite3_value] specified in the parameter may change or
4214** be deallocated after sqlite3_result_value() returns without harm.
4215** ^A [protected sqlite3_value] object may always be used where an
4216** [unprotected sqlite3_value] object is required, so either
4217** kind of [sqlite3_value] object can be used with this interface.
4218**
4219** If these routines are called from within the different thread
4220** than the one containing the application-defined function that received
4221** the [sqlite3_context] pointer, the results are undefined.
4222*/
4223SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4224SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4225SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4226SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4227SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4228SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4229SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4230SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4231SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4232SQLITE_API void sqlite3_result_null(sqlite3_context*);
4233SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4234SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4235SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4236SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4237SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4238SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4239
4240/*
4241** CAPI3REF: Define New Collating Sequences
4242**
4243** These functions are used to add new collation sequences to the
4244** [database connection] specified as the first argument.
4245**
4246** ^The name of the new collation sequence is specified as a UTF-8 string
4247** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4248** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4249** the name is passed as the second function argument.
4250**
4251** ^The third argument may be one of the constants [SQLITE_UTF8],
4252** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4253** routine expects to be passed pointers to strings encoded using UTF-8,
4254** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4255** third argument might also be [SQLITE_UTF16] to indicate that the routine
4256** expects pointers to be UTF-16 strings in the native byte order, or the
4257** argument can be [SQLITE_UTF16_ALIGNED] if the
4258** the routine expects pointers to 16-bit word aligned strings
4259** of UTF-16 in the native byte order.
4260**
4261** A pointer to the user supplied routine must be passed as the fifth
4262** argument.  ^If it is NULL, this is the same as deleting the collation
4263** sequence (so that SQLite cannot call it any more).
4264** ^Each time the application supplied function is invoked, it is passed
4265** as its first parameter a copy of the void* passed as the fourth argument
4266** to sqlite3_create_collation() or sqlite3_create_collation16().
4267**
4268** ^The remaining arguments to the application-supplied routine are two strings,
4269** each represented by a (length, data) pair and encoded in the encoding
4270** that was passed as the third argument when the collation sequence was
4271** registered.  The application defined collation routine should
4272** return negative, zero or positive if the first string is less than,
4273** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4274**
4275** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4276** except that it takes an extra argument which is a destructor for
4277** the collation.  ^The destructor is called when the collation is
4278** destroyed and is passed a copy of the fourth parameter void* pointer
4279** of the sqlite3_create_collation_v2().
4280** ^Collations are destroyed when they are overridden by later calls to the
4281** collation creation functions or when the [database connection] is closed
4282** using [sqlite3_close()].
4283**
4284** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4285*/
4286SQLITE_API int sqlite3_create_collation(
4287  sqlite3*,
4288  const char *zName,
4289  int eTextRep,
4290  void*,
4291  int(*xCompare)(void*,int,const void*,int,const void*)
4292);
4293SQLITE_API int sqlite3_create_collation_v2(
4294  sqlite3*,
4295  const char *zName,
4296  int eTextRep,
4297  void*,
4298  int(*xCompare)(void*,int,const void*,int,const void*),
4299  void(*xDestroy)(void*)
4300);
4301SQLITE_API int sqlite3_create_collation16(
4302  sqlite3*,
4303  const void *zName,
4304  int eTextRep,
4305  void*,
4306  int(*xCompare)(void*,int,const void*,int,const void*)
4307);
4308
4309/*
4310** CAPI3REF: Collation Needed Callbacks
4311**
4312** ^To avoid having to register all collation sequences before a database
4313** can be used, a single callback function may be registered with the
4314** [database connection] to be invoked whenever an undefined collation
4315** sequence is required.
4316**
4317** ^If the function is registered using the sqlite3_collation_needed() API,
4318** then it is passed the names of undefined collation sequences as strings
4319** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4320** the names are passed as UTF-16 in machine native byte order.
4321** ^A call to either function replaces the existing collation-needed callback.
4322**
4323** ^(When the callback is invoked, the first argument passed is a copy
4324** of the second argument to sqlite3_collation_needed() or
4325** sqlite3_collation_needed16().  The second argument is the database
4326** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4327** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4328** sequence function required.  The fourth parameter is the name of the
4329** required collation sequence.)^
4330**
4331** The callback function should register the desired collation using
4332** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4333** [sqlite3_create_collation_v2()].
4334*/
4335SQLITE_API int sqlite3_collation_needed(
4336  sqlite3*,
4337  void*,
4338  void(*)(void*,sqlite3*,int eTextRep,const char*)
4339);
4340SQLITE_API int sqlite3_collation_needed16(
4341  sqlite3*,
4342  void*,
4343  void(*)(void*,sqlite3*,int eTextRep,const void*)
4344);
4345
4346#ifdef SQLITE_HAS_CODEC
4347/*
4348** Specify the key for an encrypted database.  This routine should be
4349** called right after sqlite3_open().
4350**
4351** The code to implement this API is not available in the public release
4352** of SQLite.
4353*/
4354SQLITE_API int sqlite3_key(
4355  sqlite3 *db,                   /* Database to be rekeyed */
4356  const void *pKey, int nKey     /* The key */
4357);
4358
4359/*
4360** Change the key on an open database.  If the current database is not
4361** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4362** database is decrypted.
4363**
4364** The code to implement this API is not available in the public release
4365** of SQLite.
4366*/
4367SQLITE_API int sqlite3_rekey(
4368  sqlite3 *db,                   /* Database to be rekeyed */
4369  const void *pKey, int nKey     /* The new key */
4370);
4371
4372/*
4373** Specify the activation key for a SEE database.  Unless
4374** activated, none of the SEE routines will work.
4375*/
4376SQLITE_API void sqlite3_activate_see(
4377  const char *zPassPhrase        /* Activation phrase */
4378);
4379#endif
4380
4381#ifdef SQLITE_ENABLE_CEROD
4382/*
4383** Specify the activation key for a CEROD database.  Unless
4384** activated, none of the CEROD routines will work.
4385*/
4386SQLITE_API void sqlite3_activate_cerod(
4387  const char *zPassPhrase        /* Activation phrase */
4388);
4389#endif
4390
4391/*
4392** CAPI3REF: Suspend Execution For A Short Time
4393**
4394** ^The sqlite3_sleep() function causes the current thread to suspend execution
4395** for at least a number of milliseconds specified in its parameter.
4396**
4397** ^If the operating system does not support sleep requests with
4398** millisecond time resolution, then the time will be rounded up to
4399** the nearest second. ^The number of milliseconds of sleep actually
4400** requested from the operating system is returned.
4401**
4402** ^SQLite implements this interface by calling the xSleep()
4403** method of the default [sqlite3_vfs] object.
4404*/
4405SQLITE_API int sqlite3_sleep(int);
4406
4407/*
4408** CAPI3REF: Name Of The Folder Holding Temporary Files
4409**
4410** ^(If this global variable is made to point to a string which is
4411** the name of a folder (a.k.a. directory), then all temporary files
4412** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4413** will be placed in that directory.)^  ^If this variable
4414** is a NULL pointer, then SQLite performs a search for an appropriate
4415** temporary file directory.
4416**
4417** It is not safe to read or modify this variable in more than one
4418** thread at a time.  It is not safe to read or modify this variable
4419** if a [database connection] is being used at the same time in a separate
4420** thread.
4421** It is intended that this variable be set once
4422** as part of process initialization and before any SQLite interface
4423** routines have been called and that this variable remain unchanged
4424** thereafter.
4425**
4426** ^The [temp_store_directory pragma] may modify this variable and cause
4427** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4428** the [temp_store_directory pragma] always assumes that any string
4429** that this variable points to is held in memory obtained from
4430** [sqlite3_malloc] and the pragma may attempt to free that memory
4431** using [sqlite3_free].
4432** Hence, if this variable is modified directly, either it should be
4433** made NULL or made to point to memory obtained from [sqlite3_malloc]
4434** or else the use of the [temp_store_directory pragma] should be avoided.
4435*/
4436SQLITE_API char *sqlite3_temp_directory;
4437
4438/*
4439** CAPI3REF: Test For Auto-Commit Mode
4440** KEYWORDS: {autocommit mode}
4441**
4442** ^The sqlite3_get_autocommit() interface returns non-zero or
4443** zero if the given database connection is or is not in autocommit mode,
4444** respectively.  ^Autocommit mode is on by default.
4445** ^Autocommit mode is disabled by a [BEGIN] statement.
4446** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4447**
4448** If certain kinds of errors occur on a statement within a multi-statement
4449** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4450** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4451** transaction might be rolled back automatically.  The only way to
4452** find out whether SQLite automatically rolled back the transaction after
4453** an error is to use this function.
4454**
4455** If another thread changes the autocommit status of the database
4456** connection while this routine is running, then the return value
4457** is undefined.
4458*/
4459SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4460
4461/*
4462** CAPI3REF: Find The Database Handle Of A Prepared Statement
4463**
4464** ^The sqlite3_db_handle interface returns the [database connection] handle
4465** to which a [prepared statement] belongs.  ^The [database connection]
4466** returned by sqlite3_db_handle is the same [database connection]
4467** that was the first argument
4468** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4469** create the statement in the first place.
4470*/
4471SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4472
4473/*
4474** CAPI3REF: Find the next prepared statement
4475**
4476** ^This interface returns a pointer to the next [prepared statement] after
4477** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4478** then this interface returns a pointer to the first prepared statement
4479** associated with the database connection pDb.  ^If no prepared statement
4480** satisfies the conditions of this routine, it returns NULL.
4481**
4482** The [database connection] pointer D in a call to
4483** [sqlite3_next_stmt(D,S)] must refer to an open database
4484** connection and in particular must not be a NULL pointer.
4485*/
4486SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4487
4488/*
4489** CAPI3REF: Commit And Rollback Notification Callbacks
4490**
4491** ^The sqlite3_commit_hook() interface registers a callback
4492** function to be invoked whenever a transaction is [COMMIT | committed].
4493** ^Any callback set by a previous call to sqlite3_commit_hook()
4494** for the same database connection is overridden.
4495** ^The sqlite3_rollback_hook() interface registers a callback
4496** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4497** ^Any callback set by a previous call to sqlite3_rollback_hook()
4498** for the same database connection is overridden.
4499** ^The pArg argument is passed through to the callback.
4500** ^If the callback on a commit hook function returns non-zero,
4501** then the commit is converted into a rollback.
4502**
4503** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4504** return the P argument from the previous call of the same function
4505** on the same [database connection] D, or NULL for
4506** the first call for each function on D.
4507**
4508** The callback implementation must not do anything that will modify
4509** the database connection that invoked the callback.  Any actions
4510** to modify the database connection must be deferred until after the
4511** completion of the [sqlite3_step()] call that triggered the commit
4512** or rollback hook in the first place.
4513** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4514** database connections for the meaning of "modify" in this paragraph.
4515**
4516** ^Registering a NULL function disables the callback.
4517**
4518** ^When the commit hook callback routine returns zero, the [COMMIT]
4519** operation is allowed to continue normally.  ^If the commit hook
4520** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4521** ^The rollback hook is invoked on a rollback that results from a commit
4522** hook returning non-zero, just as it would be with any other rollback.
4523**
4524** ^For the purposes of this API, a transaction is said to have been
4525** rolled back if an explicit "ROLLBACK" statement is executed, or
4526** an error or constraint causes an implicit rollback to occur.
4527** ^The rollback callback is not invoked if a transaction is
4528** automatically rolled back because the database connection is closed.
4529**
4530** See also the [sqlite3_update_hook()] interface.
4531*/
4532SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4533SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4534
4535/*
4536** CAPI3REF: Data Change Notification Callbacks
4537**
4538** ^The sqlite3_update_hook() interface registers a callback function
4539** with the [database connection] identified by the first argument
4540** to be invoked whenever a row is updated, inserted or deleted.
4541** ^Any callback set by a previous call to this function
4542** for the same database connection is overridden.
4543**
4544** ^The second argument is a pointer to the function to invoke when a
4545** row is updated, inserted or deleted.
4546** ^The first argument to the callback is a copy of the third argument
4547** to sqlite3_update_hook().
4548** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4549** or [SQLITE_UPDATE], depending on the operation that caused the callback
4550** to be invoked.
4551** ^The third and fourth arguments to the callback contain pointers to the
4552** database and table name containing the affected row.
4553** ^The final callback parameter is the [rowid] of the row.
4554** ^In the case of an update, this is the [rowid] after the update takes place.
4555**
4556** ^(The update hook is not invoked when internal system tables are
4557** modified (i.e. sqlite_master and sqlite_sequence).)^
4558**
4559** ^In the current implementation, the update hook
4560** is not invoked when duplication rows are deleted because of an
4561** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4562** invoked when rows are deleted using the [truncate optimization].
4563** The exceptions defined in this paragraph might change in a future
4564** release of SQLite.
4565**
4566** The update hook implementation must not do anything that will modify
4567** the database connection that invoked the update hook.  Any actions
4568** to modify the database connection must be deferred until after the
4569** completion of the [sqlite3_step()] call that triggered the update hook.
4570** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4571** database connections for the meaning of "modify" in this paragraph.
4572**
4573** ^The sqlite3_update_hook(D,C,P) function
4574** returns the P argument from the previous call
4575** on the same [database connection] D, or NULL for
4576** the first call on D.
4577**
4578** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4579** interfaces.
4580*/
4581SQLITE_API void *sqlite3_update_hook(
4582  sqlite3*,
4583  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4584  void*
4585);
4586
4587/*
4588** CAPI3REF: Enable Or Disable Shared Pager Cache
4589** KEYWORDS: {shared cache}
4590**
4591** ^(This routine enables or disables the sharing of the database cache
4592** and schema data structures between [database connection | connections]
4593** to the same database. Sharing is enabled if the argument is true
4594** and disabled if the argument is false.)^
4595**
4596** ^Cache sharing is enabled and disabled for an entire process.
4597** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4598** sharing was enabled or disabled for each thread separately.
4599**
4600** ^(The cache sharing mode set by this interface effects all subsequent
4601** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4602** Existing database connections continue use the sharing mode
4603** that was in effect at the time they were opened.)^
4604**
4605** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4606** successfully.  An [error code] is returned otherwise.)^
4607**
4608** ^Shared cache is disabled by default. But this might change in
4609** future releases of SQLite.  Applications that care about shared
4610** cache setting should set it explicitly.
4611**
4612** See Also:  [SQLite Shared-Cache Mode]
4613*/
4614SQLITE_API int sqlite3_enable_shared_cache(int);
4615
4616/*
4617** CAPI3REF: Attempt To Free Heap Memory
4618**
4619** ^The sqlite3_release_memory() interface attempts to free N bytes
4620** of heap memory by deallocating non-essential memory allocations
4621** held by the database library.   Memory used to cache database
4622** pages to improve performance is an example of non-essential memory.
4623** ^sqlite3_release_memory() returns the number of bytes actually freed,
4624** which might be more or less than the amount requested.
4625*/
4626SQLITE_API int sqlite3_release_memory(int);
4627
4628/*
4629** CAPI3REF: Impose A Limit On Heap Size
4630**
4631** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4632** on the amount of heap memory that may be allocated by SQLite.
4633** ^If an internal allocation is requested that would exceed the
4634** soft heap limit, [sqlite3_release_memory()] is invoked one or
4635** more times to free up some space before the allocation is performed.
4636**
4637** ^The limit is called "soft" because if [sqlite3_release_memory()]
4638** cannot free sufficient memory to prevent the limit from being exceeded,
4639** the memory is allocated anyway and the current operation proceeds.
4640**
4641** ^A negative or zero value for N means that there is no soft heap limit and
4642** [sqlite3_release_memory()] will only be called when memory is exhausted.
4643** ^The default value for the soft heap limit is zero.
4644**
4645** ^(SQLite makes a best effort to honor the soft heap limit.
4646** But if the soft heap limit cannot be honored, execution will
4647** continue without error or notification.)^  This is why the limit is
4648** called a "soft" limit.  It is advisory only.
4649**
4650** Prior to SQLite version 3.5.0, this routine only constrained the memory
4651** allocated by a single thread - the same thread in which this routine
4652** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4653** applied to all threads. The value specified for the soft heap limit
4654** is an upper bound on the total memory allocation for all threads. In
4655** version 3.5.0 there is no mechanism for limiting the heap usage for
4656** individual threads.
4657*/
4658SQLITE_API void sqlite3_soft_heap_limit(int);
4659
4660/*
4661** CAPI3REF: Extract Metadata About A Column Of A Table
4662**
4663** ^This routine returns metadata about a specific column of a specific
4664** database table accessible using the [database connection] handle
4665** passed as the first function argument.
4666**
4667** ^The column is identified by the second, third and fourth parameters to
4668** this function. ^The second parameter is either the name of the database
4669** (i.e. "main", "temp", or an attached database) containing the specified
4670** table or NULL. ^If it is NULL, then all attached databases are searched
4671** for the table using the same algorithm used by the database engine to
4672** resolve unqualified table references.
4673**
4674** ^The third and fourth parameters to this function are the table and column
4675** name of the desired column, respectively. Neither of these parameters
4676** may be NULL.
4677**
4678** ^Metadata is returned by writing to the memory locations passed as the 5th
4679** and subsequent parameters to this function. ^Any of these arguments may be
4680** NULL, in which case the corresponding element of metadata is omitted.
4681**
4682** ^(<blockquote>
4683** <table border="1">
4684** <tr><th> Parameter <th> Output<br>Type <th>  Description
4685**
4686** <tr><td> 5th <td> const char* <td> Data type
4687** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4688** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4689** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4690** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4691** </table>
4692** </blockquote>)^
4693**
4694** ^The memory pointed to by the character pointers returned for the
4695** declaration type and collation sequence is valid only until the next
4696** call to any SQLite API function.
4697**
4698** ^If the specified table is actually a view, an [error code] is returned.
4699**
4700** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4701** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4702** parameters are set for the explicitly declared column. ^(If there is no
4703** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4704** parameters are set as follows:
4705**
4706** <pre>
4707**     data type: "INTEGER"
4708**     collation sequence: "BINARY"
4709**     not null: 0
4710**     primary key: 1
4711**     auto increment: 0
4712** </pre>)^
4713**
4714** ^(This function may load one or more schemas from database files. If an
4715** error occurs during this process, or if the requested table or column
4716** cannot be found, an [error code] is returned and an error message left
4717** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4718**
4719** ^This API is only available if the library was compiled with the
4720** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4721*/
4722SQLITE_API int sqlite3_table_column_metadata(
4723  sqlite3 *db,                /* Connection handle */
4724  const char *zDbName,        /* Database name or NULL */
4725  const char *zTableName,     /* Table name */
4726  const char *zColumnName,    /* Column name */
4727  char const **pzDataType,    /* OUTPUT: Declared data type */
4728  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4729  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4730  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4731  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4732);
4733
4734/*
4735** CAPI3REF: Load An Extension
4736**
4737** ^This interface loads an SQLite extension library from the named file.
4738**
4739** ^The sqlite3_load_extension() interface attempts to load an
4740** SQLite extension library contained in the file zFile.
4741**
4742** ^The entry point is zProc.
4743** ^zProc may be 0, in which case the name of the entry point
4744** defaults to "sqlite3_extension_init".
4745** ^The sqlite3_load_extension() interface returns
4746** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4747** ^If an error occurs and pzErrMsg is not 0, then the
4748** [sqlite3_load_extension()] interface shall attempt to
4749** fill *pzErrMsg with error message text stored in memory
4750** obtained from [sqlite3_malloc()]. The calling function
4751** should free this memory by calling [sqlite3_free()].
4752**
4753** ^Extension loading must be enabled using
4754** [sqlite3_enable_load_extension()] prior to calling this API,
4755** otherwise an error will be returned.
4756**
4757** See also the [load_extension() SQL function].
4758*/
4759SQLITE_API int sqlite3_load_extension(
4760  sqlite3 *db,          /* Load the extension into this database connection */
4761  const char *zFile,    /* Name of the shared library containing extension */
4762  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4763  char **pzErrMsg       /* Put error message here if not 0 */
4764);
4765
4766/*
4767** CAPI3REF: Enable Or Disable Extension Loading
4768**
4769** ^So as not to open security holes in older applications that are
4770** unprepared to deal with extension loading, and as a means of disabling
4771** extension loading while evaluating user-entered SQL, the following API
4772** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4773**
4774** ^Extension loading is off by default. See ticket #1863.
4775** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4776** to turn extension loading on and call it with onoff==0 to turn
4777** it back off again.
4778*/
4779SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4780
4781/*
4782** CAPI3REF: Automatically Load An Extensions
4783**
4784** ^This API can be invoked at program startup in order to register
4785** one or more statically linked extensions that will be available
4786** to all new [database connections].
4787**
4788** ^(This routine stores a pointer to the extension entry point
4789** in an array that is obtained from [sqlite3_malloc()].  That memory
4790** is deallocated by [sqlite3_reset_auto_extension()].)^
4791**
4792** ^This function registers an extension entry point that is
4793** automatically invoked whenever a new [database connection]
4794** is opened using [sqlite3_open()], [sqlite3_open16()],
4795** or [sqlite3_open_v2()].
4796** ^Duplicate extensions are detected so calling this routine
4797** multiple times with the same extension is harmless.
4798** ^Automatic extensions apply across all threads.
4799*/
4800SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4801
4802/*
4803** CAPI3REF: Reset Automatic Extension Loading
4804**
4805** ^(This function disables all previously registered automatic
4806** extensions. It undoes the effect of all prior
4807** [sqlite3_auto_extension()] calls.)^
4808**
4809** ^This function disables automatic extensions in all threads.
4810*/
4811SQLITE_API void sqlite3_reset_auto_extension(void);
4812
4813/*
4814** The interface to the virtual-table mechanism is currently considered
4815** to be experimental.  The interface might change in incompatible ways.
4816** If this is a problem for you, do not use the interface at this time.
4817**
4818** When the virtual-table mechanism stabilizes, we will declare the
4819** interface fixed, support it indefinitely, and remove this comment.
4820*/
4821
4822/*
4823** Structures used by the virtual table interface
4824*/
4825typedef struct sqlite3_vtab sqlite3_vtab;
4826typedef struct sqlite3_index_info sqlite3_index_info;
4827typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4828typedef struct sqlite3_module sqlite3_module;
4829
4830/*
4831** CAPI3REF: Virtual Table Object
4832** KEYWORDS: sqlite3_module {virtual table module}
4833**
4834** This structure, sometimes called a a "virtual table module",
4835** defines the implementation of a [virtual tables].
4836** This structure consists mostly of methods for the module.
4837**
4838** ^A virtual table module is created by filling in a persistent
4839** instance of this structure and passing a pointer to that instance
4840** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4841** ^The registration remains valid until it is replaced by a different
4842** module or until the [database connection] closes.  The content
4843** of this structure must not change while it is registered with
4844** any database connection.
4845*/
4846struct sqlite3_module {
4847  int iVersion;
4848  int (*xCreate)(sqlite3*, void *pAux,
4849               int argc, const char *const*argv,
4850               sqlite3_vtab **ppVTab, char**);
4851  int (*xConnect)(sqlite3*, void *pAux,
4852               int argc, const char *const*argv,
4853               sqlite3_vtab **ppVTab, char**);
4854  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4855  int (*xDisconnect)(sqlite3_vtab *pVTab);
4856  int (*xDestroy)(sqlite3_vtab *pVTab);
4857  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4858  int (*xClose)(sqlite3_vtab_cursor*);
4859  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4860                int argc, sqlite3_value **argv);
4861  int (*xNext)(sqlite3_vtab_cursor*);
4862  int (*xEof)(sqlite3_vtab_cursor*);
4863  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4864  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4865  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4866  int (*xBegin)(sqlite3_vtab *pVTab);
4867  int (*xSync)(sqlite3_vtab *pVTab);
4868  int (*xCommit)(sqlite3_vtab *pVTab);
4869  int (*xRollback)(sqlite3_vtab *pVTab);
4870  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4871                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4872                       void **ppArg);
4873  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4874};
4875
4876/*
4877** CAPI3REF: Virtual Table Indexing Information
4878** KEYWORDS: sqlite3_index_info
4879**
4880** The sqlite3_index_info structure and its substructures is used as part
4881** of the [virtual table] interface to
4882** pass information into and receive the reply from the [xBestIndex]
4883** method of a [virtual table module].  The fields under **Inputs** are the
4884** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4885** results into the **Outputs** fields.
4886**
4887** ^(The aConstraint[] array records WHERE clause constraints of the form:
4888**
4889** <blockquote>column OP expr</blockquote>
4890**
4891** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4892** stored in aConstraint[].op using one of the
4893** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
4894** ^(The index of the column is stored in
4895** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4896** expr on the right-hand side can be evaluated (and thus the constraint
4897** is usable) and false if it cannot.)^
4898**
4899** ^The optimizer automatically inverts terms of the form "expr OP column"
4900** and makes other simplifications to the WHERE clause in an attempt to
4901** get as many WHERE clause terms into the form shown above as possible.
4902** ^The aConstraint[] array only reports WHERE clause terms that are
4903** relevant to the particular virtual table being queried.
4904**
4905** ^Information about the ORDER BY clause is stored in aOrderBy[].
4906** ^Each term of aOrderBy records a column of the ORDER BY clause.
4907**
4908** The [xBestIndex] method must fill aConstraintUsage[] with information
4909** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4910** the right-hand side of the corresponding aConstraint[] is evaluated
4911** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4912** is true, then the constraint is assumed to be fully handled by the
4913** virtual table and is not checked again by SQLite.)^
4914**
4915** ^The idxNum and idxPtr values are recorded and passed into the
4916** [xFilter] method.
4917** ^[sqlite3_free()] is used to free idxPtr if and only if
4918** needToFreeIdxPtr is true.
4919**
4920** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4921** the correct order to satisfy the ORDER BY clause so that no separate
4922** sorting step is required.
4923**
4924** ^The estimatedCost value is an estimate of the cost of doing the
4925** particular lookup.  A full scan of a table with N entries should have
4926** a cost of N.  A binary search of a table of N entries should have a
4927** cost of approximately log(N).
4928*/
4929struct sqlite3_index_info {
4930  /* Inputs */
4931  int nConstraint;           /* Number of entries in aConstraint */
4932  struct sqlite3_index_constraint {
4933     int iColumn;              /* Column on left-hand side of constraint */
4934     unsigned char op;         /* Constraint operator */
4935     unsigned char usable;     /* True if this constraint is usable */
4936     int iTermOffset;          /* Used internally - xBestIndex should ignore */
4937  } *aConstraint;            /* Table of WHERE clause constraints */
4938  int nOrderBy;              /* Number of terms in the ORDER BY clause */
4939  struct sqlite3_index_orderby {
4940     int iColumn;              /* Column number */
4941     unsigned char desc;       /* True for DESC.  False for ASC. */
4942  } *aOrderBy;               /* The ORDER BY clause */
4943  /* Outputs */
4944  struct sqlite3_index_constraint_usage {
4945    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4946    unsigned char omit;      /* Do not code a test for this constraint */
4947  } *aConstraintUsage;
4948  int idxNum;                /* Number used to identify the index */
4949  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4950  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4951  int orderByConsumed;       /* True if output is already ordered */
4952  double estimatedCost;      /* Estimated cost of using this index */
4953};
4954
4955/*
4956** CAPI3REF: Virtual Table Constraint Operator Codes
4957**
4958** These macros defined the allowed values for the
4959** [sqlite3_index_info].aConstraint[].op field.  Each value represents
4960** an operator that is part of a constraint term in the wHERE clause of
4961** a query that uses a [virtual table].
4962*/
4963#define SQLITE_INDEX_CONSTRAINT_EQ    2
4964#define SQLITE_INDEX_CONSTRAINT_GT    4
4965#define SQLITE_INDEX_CONSTRAINT_LE    8
4966#define SQLITE_INDEX_CONSTRAINT_LT    16
4967#define SQLITE_INDEX_CONSTRAINT_GE    32
4968#define SQLITE_INDEX_CONSTRAINT_MATCH 64
4969
4970/*
4971** CAPI3REF: Register A Virtual Table Implementation
4972**
4973** ^These routines are used to register a new [virtual table module] name.
4974** ^Module names must be registered before
4975** creating a new [virtual table] using the module and before using a
4976** preexisting [virtual table] for the module.
4977**
4978** ^The module name is registered on the [database connection] specified
4979** by the first parameter.  ^The name of the module is given by the
4980** second parameter.  ^The third parameter is a pointer to
4981** the implementation of the [virtual table module].   ^The fourth
4982** parameter is an arbitrary client data pointer that is passed through
4983** into the [xCreate] and [xConnect] methods of the virtual table module
4984** when a new virtual table is be being created or reinitialized.
4985**
4986** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4987** is a pointer to a destructor for the pClientData.  ^SQLite will
4988** invoke the destructor function (if it is not NULL) when SQLite
4989** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4990** interface is equivalent to sqlite3_create_module_v2() with a NULL
4991** destructor.
4992*/
4993SQLITE_API int sqlite3_create_module(
4994  sqlite3 *db,               /* SQLite connection to register module with */
4995  const char *zName,         /* Name of the module */
4996  const sqlite3_module *p,   /* Methods for the module */
4997  void *pClientData          /* Client data for xCreate/xConnect */
4998);
4999SQLITE_API int sqlite3_create_module_v2(
5000  sqlite3 *db,               /* SQLite connection to register module with */
5001  const char *zName,         /* Name of the module */
5002  const sqlite3_module *p,   /* Methods for the module */
5003  void *pClientData,         /* Client data for xCreate/xConnect */
5004  void(*xDestroy)(void*)     /* Module destructor function */
5005);
5006
5007/*
5008** CAPI3REF: Virtual Table Instance Object
5009** KEYWORDS: sqlite3_vtab
5010**
5011** Every [virtual table module] implementation uses a subclass
5012** of this object to describe a particular instance
5013** of the [virtual table].  Each subclass will
5014** be tailored to the specific needs of the module implementation.
5015** The purpose of this superclass is to define certain fields that are
5016** common to all module implementations.
5017**
5018** ^Virtual tables methods can set an error message by assigning a
5019** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5020** take care that any prior string is freed by a call to [sqlite3_free()]
5021** prior to assigning a new string to zErrMsg.  ^After the error message
5022** is delivered up to the client application, the string will be automatically
5023** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5024*/
5025struct sqlite3_vtab {
5026  const sqlite3_module *pModule;  /* The module for this virtual table */
5027  int nRef;                       /* NO LONGER USED */
5028  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5029  /* Virtual table implementations will typically add additional fields */
5030};
5031
5032/*
5033** CAPI3REF: Virtual Table Cursor Object
5034** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5035**
5036** Every [virtual table module] implementation uses a subclass of the
5037** following structure to describe cursors that point into the
5038** [virtual table] and are used
5039** to loop through the virtual table.  Cursors are created using the
5040** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5041** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5042** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5043** of the module.  Each module implementation will define
5044** the content of a cursor structure to suit its own needs.
5045**
5046** This superclass exists in order to define fields of the cursor that
5047** are common to all implementations.
5048*/
5049struct sqlite3_vtab_cursor {
5050  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5051  /* Virtual table implementations will typically add additional fields */
5052};
5053
5054/*
5055** CAPI3REF: Declare The Schema Of A Virtual Table
5056**
5057** ^The [xCreate] and [xConnect] methods of a
5058** [virtual table module] call this interface
5059** to declare the format (the names and datatypes of the columns) of
5060** the virtual tables they implement.
5061*/
5062SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5063
5064/*
5065** CAPI3REF: Overload A Function For A Virtual Table
5066**
5067** ^(Virtual tables can provide alternative implementations of functions
5068** using the [xFindFunction] method of the [virtual table module].
5069** But global versions of those functions
5070** must exist in order to be overloaded.)^
5071**
5072** ^(This API makes sure a global version of a function with a particular
5073** name and number of parameters exists.  If no such function exists
5074** before this API is called, a new function is created.)^  ^The implementation
5075** of the new function always causes an exception to be thrown.  So
5076** the new function is not good for anything by itself.  Its only
5077** purpose is to be a placeholder function that can be overloaded
5078** by a [virtual table].
5079*/
5080SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5081
5082/*
5083** The interface to the virtual-table mechanism defined above (back up
5084** to a comment remarkably similar to this one) is currently considered
5085** to be experimental.  The interface might change in incompatible ways.
5086** If this is a problem for you, do not use the interface at this time.
5087**
5088** When the virtual-table mechanism stabilizes, we will declare the
5089** interface fixed, support it indefinitely, and remove this comment.
5090*/
5091
5092/*
5093** CAPI3REF: A Handle To An Open BLOB
5094** KEYWORDS: {BLOB handle} {BLOB handles}
5095**
5096** An instance of this object represents an open BLOB on which
5097** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5098** ^Objects of this type are created by [sqlite3_blob_open()]
5099** and destroyed by [sqlite3_blob_close()].
5100** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5101** can be used to read or write small subsections of the BLOB.
5102** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5103*/
5104typedef struct sqlite3_blob sqlite3_blob;
5105
5106/*
5107** CAPI3REF: Open A BLOB For Incremental I/O
5108**
5109** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5110** in row iRow, column zColumn, table zTable in database zDb;
5111** in other words, the same BLOB that would be selected by:
5112**
5113** <pre>
5114**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5115** </pre>)^
5116**
5117** ^If the flags parameter is non-zero, then the BLOB is opened for read
5118** and write access. ^If it is zero, the BLOB is opened for read access.
5119** ^It is not possible to open a column that is part of an index or primary
5120** key for writing. ^If [foreign key constraints] are enabled, it is
5121** not possible to open a column that is part of a [child key] for writing.
5122**
5123** ^Note that the database name is not the filename that contains
5124** the database but rather the symbolic name of the database that
5125** appears after the AS keyword when the database is connected using [ATTACH].
5126** ^For the main database file, the database name is "main".
5127** ^For TEMP tables, the database name is "temp".
5128**
5129** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5130** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5131** to be a null pointer.)^
5132** ^This function sets the [database connection] error code and message
5133** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5134** functions. ^Note that the *ppBlob variable is always initialized in a
5135** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5136** regardless of the success or failure of this routine.
5137**
5138** ^(If the row that a BLOB handle points to is modified by an
5139** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5140** then the BLOB handle is marked as "expired".
5141** This is true if any column of the row is changed, even a column
5142** other than the one the BLOB handle is open on.)^
5143** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5144** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5145** ^(Changes written into a BLOB prior to the BLOB expiring are not
5146** rolled back by the expiration of the BLOB.  Such changes will eventually
5147** commit if the transaction continues to completion.)^
5148**
5149** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5150** the opened blob.  ^The size of a blob may not be changed by this
5151** interface.  Use the [UPDATE] SQL command to change the size of a
5152** blob.
5153**
5154** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5155** and the built-in [zeroblob] SQL function can be used, if desired,
5156** to create an empty, zero-filled blob in which to read or write using
5157** this interface.
5158**
5159** To avoid a resource leak, every open [BLOB handle] should eventually
5160** be released by a call to [sqlite3_blob_close()].
5161*/
5162SQLITE_API int sqlite3_blob_open(
5163  sqlite3*,
5164  const char *zDb,
5165  const char *zTable,
5166  const char *zColumn,
5167  sqlite3_int64 iRow,
5168  int flags,
5169  sqlite3_blob **ppBlob
5170);
5171
5172/*
5173** CAPI3REF: Close A BLOB Handle
5174**
5175** ^Closes an open [BLOB handle].
5176**
5177** ^Closing a BLOB shall cause the current transaction to commit
5178** if there are no other BLOBs, no pending prepared statements, and the
5179** database connection is in [autocommit mode].
5180** ^If any writes were made to the BLOB, they might be held in cache
5181** until the close operation if they will fit.
5182**
5183** ^(Closing the BLOB often forces the changes
5184** out to disk and so if any I/O errors occur, they will likely occur
5185** at the time when the BLOB is closed.  Any errors that occur during
5186** closing are reported as a non-zero return value.)^
5187**
5188** ^(The BLOB is closed unconditionally.  Even if this routine returns
5189** an error code, the BLOB is still closed.)^
5190**
5191** ^Calling this routine with a null pointer (such as would be returned
5192** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5193*/
5194SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5195
5196/*
5197** CAPI3REF: Return The Size Of An Open BLOB
5198**
5199** ^Returns the size in bytes of the BLOB accessible via the
5200** successfully opened [BLOB handle] in its only argument.  ^The
5201** incremental blob I/O routines can only read or overwriting existing
5202** blob content; they cannot change the size of a blob.
5203**
5204** This routine only works on a [BLOB handle] which has been created
5205** by a prior successful call to [sqlite3_blob_open()] and which has not
5206** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5207** to this routine results in undefined and probably undesirable behavior.
5208*/
5209SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5210
5211/*
5212** CAPI3REF: Read Data From A BLOB Incrementally
5213**
5214** ^(This function is used to read data from an open [BLOB handle] into a
5215** caller-supplied buffer. N bytes of data are copied into buffer Z
5216** from the open BLOB, starting at offset iOffset.)^
5217**
5218** ^If offset iOffset is less than N bytes from the end of the BLOB,
5219** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5220** less than zero, [SQLITE_ERROR] is returned and no data is read.
5221** ^The size of the blob (and hence the maximum value of N+iOffset)
5222** can be determined using the [sqlite3_blob_bytes()] interface.
5223**
5224** ^An attempt to read from an expired [BLOB handle] fails with an
5225** error code of [SQLITE_ABORT].
5226**
5227** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5228** Otherwise, an [error code] or an [extended error code] is returned.)^
5229**
5230** This routine only works on a [BLOB handle] which has been created
5231** by a prior successful call to [sqlite3_blob_open()] and which has not
5232** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5233** to this routine results in undefined and probably undesirable behavior.
5234**
5235** See also: [sqlite3_blob_write()].
5236*/
5237SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5238
5239/*
5240** CAPI3REF: Write Data Into A BLOB Incrementally
5241**
5242** ^This function is used to write data into an open [BLOB handle] from a
5243** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5244** into the open BLOB, starting at offset iOffset.
5245**
5246** ^If the [BLOB handle] passed as the first argument was not opened for
5247** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5248** this function returns [SQLITE_READONLY].
5249**
5250** ^This function may only modify the contents of the BLOB; it is
5251** not possible to increase the size of a BLOB using this API.
5252** ^If offset iOffset is less than N bytes from the end of the BLOB,
5253** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5254** less than zero [SQLITE_ERROR] is returned and no data is written.
5255** The size of the BLOB (and hence the maximum value of N+iOffset)
5256** can be determined using the [sqlite3_blob_bytes()] interface.
5257**
5258** ^An attempt to write to an expired [BLOB handle] fails with an
5259** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5260** before the [BLOB handle] expired are not rolled back by the
5261** expiration of the handle, though of course those changes might
5262** have been overwritten by the statement that expired the BLOB handle
5263** or by other independent statements.
5264**
5265** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5266** Otherwise, an  [error code] or an [extended error code] is returned.)^
5267**
5268** This routine only works on a [BLOB handle] which has been created
5269** by a prior successful call to [sqlite3_blob_open()] and which has not
5270** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5271** to this routine results in undefined and probably undesirable behavior.
5272**
5273** See also: [sqlite3_blob_read()].
5274*/
5275SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5276
5277/*
5278** CAPI3REF: Virtual File System Objects
5279**
5280** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5281** that SQLite uses to interact
5282** with the underlying operating system.  Most SQLite builds come with a
5283** single default VFS that is appropriate for the host computer.
5284** New VFSes can be registered and existing VFSes can be unregistered.
5285** The following interfaces are provided.
5286**
5287** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5288** ^Names are case sensitive.
5289** ^Names are zero-terminated UTF-8 strings.
5290** ^If there is no match, a NULL pointer is returned.
5291** ^If zVfsName is NULL then the default VFS is returned.
5292**
5293** ^New VFSes are registered with sqlite3_vfs_register().
5294** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5295** ^The same VFS can be registered multiple times without injury.
5296** ^To make an existing VFS into the default VFS, register it again
5297** with the makeDflt flag set.  If two different VFSes with the
5298** same name are registered, the behavior is undefined.  If a
5299** VFS is registered with a name that is NULL or an empty string,
5300** then the behavior is undefined.
5301**
5302** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5303** ^(If the default VFS is unregistered, another VFS is chosen as
5304** the default.  The choice for the new VFS is arbitrary.)^
5305*/
5306SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5307SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5308SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5309
5310/*
5311** CAPI3REF: Mutexes
5312**
5313** The SQLite core uses these routines for thread
5314** synchronization. Though they are intended for internal
5315** use by SQLite, code that links against SQLite is
5316** permitted to use any of these routines.
5317**
5318** The SQLite source code contains multiple implementations
5319** of these mutex routines.  An appropriate implementation
5320** is selected automatically at compile-time.  ^(The following
5321** implementations are available in the SQLite core:
5322**
5323** <ul>
5324** <li>   SQLITE_MUTEX_OS2
5325** <li>   SQLITE_MUTEX_PTHREAD
5326** <li>   SQLITE_MUTEX_W32
5327** <li>   SQLITE_MUTEX_NOOP
5328** </ul>)^
5329**
5330** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5331** that does no real locking and is appropriate for use in
5332** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5333** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5334** are appropriate for use on OS/2, Unix, and Windows.
5335**
5336** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5337** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5338** implementation is included with the library. In this case the
5339** application must supply a custom mutex implementation using the
5340** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5341** before calling sqlite3_initialize() or any other public sqlite3_
5342** function that calls sqlite3_initialize().)^
5343**
5344** ^The sqlite3_mutex_alloc() routine allocates a new
5345** mutex and returns a pointer to it. ^If it returns NULL
5346** that means that a mutex could not be allocated.  ^SQLite
5347** will unwind its stack and return an error.  ^(The argument
5348** to sqlite3_mutex_alloc() is one of these integer constants:
5349**
5350** <ul>
5351** <li>  SQLITE_MUTEX_FAST
5352** <li>  SQLITE_MUTEX_RECURSIVE
5353** <li>  SQLITE_MUTEX_STATIC_MASTER
5354** <li>  SQLITE_MUTEX_STATIC_MEM
5355** <li>  SQLITE_MUTEX_STATIC_MEM2
5356** <li>  SQLITE_MUTEX_STATIC_PRNG
5357** <li>  SQLITE_MUTEX_STATIC_LRU
5358** <li>  SQLITE_MUTEX_STATIC_LRU2
5359** </ul>)^
5360**
5361** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5362** cause sqlite3_mutex_alloc() to create
5363** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5364** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5365** The mutex implementation does not need to make a distinction
5366** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5367** not want to.  ^SQLite will only request a recursive mutex in
5368** cases where it really needs one.  ^If a faster non-recursive mutex
5369** implementation is available on the host platform, the mutex subsystem
5370** might return such a mutex in response to SQLITE_MUTEX_FAST.
5371**
5372** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5373** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5374** a pointer to a static preexisting mutex.  ^Six static mutexes are
5375** used by the current version of SQLite.  Future versions of SQLite
5376** may add additional static mutexes.  Static mutexes are for internal
5377** use by SQLite only.  Applications that use SQLite mutexes should
5378** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5379** SQLITE_MUTEX_RECURSIVE.
5380**
5381** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5382** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5383** returns a different mutex on every call.  ^But for the static
5384** mutex types, the same mutex is returned on every call that has
5385** the same type number.
5386**
5387** ^The sqlite3_mutex_free() routine deallocates a previously
5388** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5389** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5390** use when they are deallocated.  Attempting to deallocate a static
5391** mutex results in undefined behavior.  ^SQLite never deallocates
5392** a static mutex.
5393**
5394** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5395** to enter a mutex.  ^If another thread is already within the mutex,
5396** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5397** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5398** upon successful entry.  ^(Mutexes created using
5399** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5400** In such cases the,
5401** mutex must be exited an equal number of times before another thread
5402** can enter.)^  ^(If the same thread tries to enter any other
5403** kind of mutex more than once, the behavior is undefined.
5404** SQLite will never exhibit
5405** such behavior in its own use of mutexes.)^
5406**
5407** ^(Some systems (for example, Windows 95) do not support the operation
5408** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5409** will always return SQLITE_BUSY.  The SQLite core only ever uses
5410** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5411**
5412** ^The sqlite3_mutex_leave() routine exits a mutex that was
5413** previously entered by the same thread.   ^(The behavior
5414** is undefined if the mutex is not currently entered by the
5415** calling thread or is not currently allocated.  SQLite will
5416** never do either.)^
5417**
5418** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5419** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5420** behave as no-ops.
5421**
5422** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5423*/
5424SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5425SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5426SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5427SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5428SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5429
5430/*
5431** CAPI3REF: Mutex Methods Object
5432**
5433** An instance of this structure defines the low-level routines
5434** used to allocate and use mutexes.
5435**
5436** Usually, the default mutex implementations provided by SQLite are
5437** sufficient, however the user has the option of substituting a custom
5438** implementation for specialized deployments or systems for which SQLite
5439** does not provide a suitable implementation. In this case, the user
5440** creates and populates an instance of this structure to pass
5441** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5442** Additionally, an instance of this structure can be used as an
5443** output variable when querying the system for the current mutex
5444** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5445**
5446** ^The xMutexInit method defined by this structure is invoked as
5447** part of system initialization by the sqlite3_initialize() function.
5448** ^The xMutexInit routine is calle by SQLite exactly once for each
5449** effective call to [sqlite3_initialize()].
5450**
5451** ^The xMutexEnd method defined by this structure is invoked as
5452** part of system shutdown by the sqlite3_shutdown() function. The
5453** implementation of this method is expected to release all outstanding
5454** resources obtained by the mutex methods implementation, especially
5455** those obtained by the xMutexInit method.  ^The xMutexEnd()
5456** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5457**
5458** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5459** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5460** xMutexNotheld) implement the following interfaces (respectively):
5461**
5462** <ul>
5463**   <li>  [sqlite3_mutex_alloc()] </li>
5464**   <li>  [sqlite3_mutex_free()] </li>
5465**   <li>  [sqlite3_mutex_enter()] </li>
5466**   <li>  [sqlite3_mutex_try()] </li>
5467**   <li>  [sqlite3_mutex_leave()] </li>
5468**   <li>  [sqlite3_mutex_held()] </li>
5469**   <li>  [sqlite3_mutex_notheld()] </li>
5470** </ul>)^
5471**
5472** The only difference is that the public sqlite3_XXX functions enumerated
5473** above silently ignore any invocations that pass a NULL pointer instead
5474** of a valid mutex handle. The implementations of the methods defined
5475** by this structure are not required to handle this case, the results
5476** of passing a NULL pointer instead of a valid mutex handle are undefined
5477** (i.e. it is acceptable to provide an implementation that segfaults if
5478** it is passed a NULL pointer).
5479**
5480** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5481** invoke xMutexInit() multiple times within the same process and without
5482** intervening calls to xMutexEnd().  Second and subsequent calls to
5483** xMutexInit() must be no-ops.
5484**
5485** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5486** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5487** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5488** memory allocation for a fast or recursive mutex.
5489**
5490** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5491** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5492** If xMutexInit fails in any way, it is expected to clean up after itself
5493** prior to returning.
5494*/
5495typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5496struct sqlite3_mutex_methods {
5497  int (*xMutexInit)(void);
5498  int (*xMutexEnd)(void);
5499  sqlite3_mutex *(*xMutexAlloc)(int);
5500  void (*xMutexFree)(sqlite3_mutex *);
5501  void (*xMutexEnter)(sqlite3_mutex *);
5502  int (*xMutexTry)(sqlite3_mutex *);
5503  void (*xMutexLeave)(sqlite3_mutex *);
5504  int (*xMutexHeld)(sqlite3_mutex *);
5505  int (*xMutexNotheld)(sqlite3_mutex *);
5506};
5507
5508/*
5509** CAPI3REF: Mutex Verification Routines
5510**
5511** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5512** are intended for use inside assert() statements.  ^The SQLite core
5513** never uses these routines except inside an assert() and applications
5514** are advised to follow the lead of the core.  ^The SQLite core only
5515** provides implementations for these routines when it is compiled
5516** with the SQLITE_DEBUG flag.  ^External mutex implementations
5517** are only required to provide these routines if SQLITE_DEBUG is
5518** defined and if NDEBUG is not defined.
5519**
5520** ^These routines should return true if the mutex in their argument
5521** is held or not held, respectively, by the calling thread.
5522**
5523** ^The implementation is not required to provided versions of these
5524** routines that actually work. If the implementation does not provide working
5525** versions of these routines, it should at least provide stubs that always
5526** return true so that one does not get spurious assertion failures.
5527**
5528** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5529** the routine should return 1.   This seems counter-intuitive since
5530** clearly the mutex cannot be held if it does not exist.  But the
5531** the reason the mutex does not exist is because the build is not
5532** using mutexes.  And we do not want the assert() containing the
5533** call to sqlite3_mutex_held() to fail, so a non-zero return is
5534** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5535** interface should also return 1 when given a NULL pointer.
5536*/
5537#ifndef NDEBUG
5538SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5539SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5540#endif
5541
5542/*
5543** CAPI3REF: Mutex Types
5544**
5545** The [sqlite3_mutex_alloc()] interface takes a single argument
5546** which is one of these integer constants.
5547**
5548** The set of static mutexes may change from one SQLite release to the
5549** next.  Applications that override the built-in mutex logic must be
5550** prepared to accommodate additional static mutexes.
5551*/
5552#define SQLITE_MUTEX_FAST             0
5553#define SQLITE_MUTEX_RECURSIVE        1
5554#define SQLITE_MUTEX_STATIC_MASTER    2
5555#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5556#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5557#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5558#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5559#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5560#define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5561
5562/*
5563** CAPI3REF: Retrieve the mutex for a database connection
5564**
5565** ^This interface returns a pointer the [sqlite3_mutex] object that
5566** serializes access to the [database connection] given in the argument
5567** when the [threading mode] is Serialized.
5568** ^If the [threading mode] is Single-thread or Multi-thread then this
5569** routine returns a NULL pointer.
5570*/
5571SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5572
5573/*
5574** CAPI3REF: Low-Level Control Of Database Files
5575**
5576** ^The [sqlite3_file_control()] interface makes a direct call to the
5577** xFileControl method for the [sqlite3_io_methods] object associated
5578** with a particular database identified by the second argument. ^The
5579** name of the database "main" for the main database or "temp" for the
5580** TEMP database, or the name that appears after the AS keyword for
5581** databases that are added using the [ATTACH] SQL command.
5582** ^A NULL pointer can be used in place of "main" to refer to the
5583** main database file.
5584** ^The third and fourth parameters to this routine
5585** are passed directly through to the second and third parameters of
5586** the xFileControl method.  ^The return value of the xFileControl
5587** method becomes the return value of this routine.
5588**
5589** ^If the second parameter (zDbName) does not match the name of any
5590** open database file, then SQLITE_ERROR is returned.  ^This error
5591** code is not remembered and will not be recalled by [sqlite3_errcode()]
5592** or [sqlite3_errmsg()].  The underlying xFileControl method might
5593** also return SQLITE_ERROR.  There is no way to distinguish between
5594** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5595** xFileControl method.
5596**
5597** See also: [SQLITE_FCNTL_LOCKSTATE]
5598*/
5599SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5600
5601/*
5602** CAPI3REF: Testing Interface
5603**
5604** ^The sqlite3_test_control() interface is used to read out internal
5605** state of SQLite and to inject faults into SQLite for testing
5606** purposes.  ^The first parameter is an operation code that determines
5607** the number, meaning, and operation of all subsequent parameters.
5608**
5609** This interface is not for use by applications.  It exists solely
5610** for verifying the correct operation of the SQLite library.  Depending
5611** on how the SQLite library is compiled, this interface might not exist.
5612**
5613** The details of the operation codes, their meanings, the parameters
5614** they take, and what they do are all subject to change without notice.
5615** Unlike most of the SQLite API, this function is not guaranteed to
5616** operate consistently from one release to the next.
5617*/
5618SQLITE_API int sqlite3_test_control(int op, ...);
5619
5620/*
5621** CAPI3REF: Testing Interface Operation Codes
5622**
5623** These constants are the valid operation code parameters used
5624** as the first argument to [sqlite3_test_control()].
5625**
5626** These parameters and their meanings are subject to change
5627** without notice.  These values are for testing purposes only.
5628** Applications should not use any of these parameters or the
5629** [sqlite3_test_control()] interface.
5630*/
5631#define SQLITE_TESTCTRL_FIRST                    5
5632#define SQLITE_TESTCTRL_PRNG_SAVE                5
5633#define SQLITE_TESTCTRL_PRNG_RESTORE             6
5634#define SQLITE_TESTCTRL_PRNG_RESET               7
5635#define SQLITE_TESTCTRL_BITVEC_TEST              8
5636#define SQLITE_TESTCTRL_FAULT_INSTALL            9
5637#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5638#define SQLITE_TESTCTRL_PENDING_BYTE            11
5639#define SQLITE_TESTCTRL_ASSERT                  12
5640#define SQLITE_TESTCTRL_ALWAYS                  13
5641#define SQLITE_TESTCTRL_RESERVE                 14
5642#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5643#define SQLITE_TESTCTRL_ISKEYWORD               16
5644#define SQLITE_TESTCTRL_PGHDRSZ                 17
5645#define SQLITE_TESTCTRL_LAST                    17
5646
5647/*
5648** CAPI3REF: SQLite Runtime Status
5649**
5650** ^This interface is used to retrieve runtime status information
5651** about the performance of SQLite, and optionally to reset various
5652** highwater marks.  ^The first argument is an integer code for
5653** the specific parameter to measure.  ^(Recognized integer codes
5654** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5655** ^The current value of the parameter is returned into *pCurrent.
5656** ^The highest recorded value is returned in *pHighwater.  ^If the
5657** resetFlag is true, then the highest record value is reset after
5658** *pHighwater is written.  ^(Some parameters do not record the highest
5659** value.  For those parameters
5660** nothing is written into *pHighwater and the resetFlag is ignored.)^
5661** ^(Other parameters record only the highwater mark and not the current
5662** value.  For these latter parameters nothing is written into *pCurrent.)^
5663**
5664** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5665** non-zero [error code] on failure.
5666**
5667** This routine is threadsafe but is not atomic.  This routine can be
5668** called while other threads are running the same or different SQLite
5669** interfaces.  However the values returned in *pCurrent and
5670** *pHighwater reflect the status of SQLite at different points in time
5671** and it is possible that another thread might change the parameter
5672** in between the times when *pCurrent and *pHighwater are written.
5673**
5674** See also: [sqlite3_db_status()]
5675*/
5676SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5677
5678
5679/*
5680** CAPI3REF: Status Parameters
5681**
5682** These integer constants designate various run-time status parameters
5683** that can be returned by [sqlite3_status()].
5684**
5685** <dl>
5686** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5687** <dd>This parameter is the current amount of memory checked out
5688** using [sqlite3_malloc()], either directly or indirectly.  The
5689** figure includes calls made to [sqlite3_malloc()] by the application
5690** and internal memory usage by the SQLite library.  Scratch memory
5691** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5692** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5693** this parameter.  The amount returned is the sum of the allocation
5694** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5695**
5696** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5697** <dd>This parameter records the largest memory allocation request
5698** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5699** internal equivalents).  Only the value returned in the
5700** *pHighwater parameter to [sqlite3_status()] is of interest.
5701** The value written into the *pCurrent parameter is undefined.</dd>)^
5702**
5703** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
5704** <dd>This parameter records the number of separate memory allocations.</dd>)^
5705**
5706** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5707** <dd>This parameter returns the number of pages used out of the
5708** [pagecache memory allocator] that was configured using
5709** [SQLITE_CONFIG_PAGECACHE].  The
5710** value returned is in pages, not in bytes.</dd>)^
5711**
5712** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5713** <dd>This parameter returns the number of bytes of page cache
5714** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5715** buffer and where forced to overflow to [sqlite3_malloc()].  The
5716** returned value includes allocations that overflowed because they
5717** where too large (they were larger than the "sz" parameter to
5718** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5719** no space was left in the page cache.</dd>)^
5720**
5721** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5722** <dd>This parameter records the largest memory allocation request
5723** handed to [pagecache memory allocator].  Only the value returned in the
5724** *pHighwater parameter to [sqlite3_status()] is of interest.
5725** The value written into the *pCurrent parameter is undefined.</dd>)^
5726**
5727** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5728** <dd>This parameter returns the number of allocations used out of the
5729** [scratch memory allocator] configured using
5730** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5731** in bytes.  Since a single thread may only have one scratch allocation
5732** outstanding at time, this parameter also reports the number of threads
5733** using scratch memory at the same time.</dd>)^
5734**
5735** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5736** <dd>This parameter returns the number of bytes of scratch memory
5737** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5738** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5739** returned include overflows because the requested allocation was too
5740** larger (that is, because the requested allocation was larger than the
5741** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5742** slots were available.
5743** </dd>)^
5744**
5745** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5746** <dd>This parameter records the largest memory allocation request
5747** handed to [scratch memory allocator].  Only the value returned in the
5748** *pHighwater parameter to [sqlite3_status()] is of interest.
5749** The value written into the *pCurrent parameter is undefined.</dd>)^
5750**
5751** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5752** <dd>This parameter records the deepest parser stack.  It is only
5753** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5754** </dl>
5755**
5756** New status parameters may be added from time to time.
5757*/
5758#define SQLITE_STATUS_MEMORY_USED          0
5759#define SQLITE_STATUS_PAGECACHE_USED       1
5760#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5761#define SQLITE_STATUS_SCRATCH_USED         3
5762#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5763#define SQLITE_STATUS_MALLOC_SIZE          5
5764#define SQLITE_STATUS_PARSER_STACK         6
5765#define SQLITE_STATUS_PAGECACHE_SIZE       7
5766#define SQLITE_STATUS_SCRATCH_SIZE         8
5767#define SQLITE_STATUS_MALLOC_COUNT         9
5768
5769/*
5770** CAPI3REF: Database Connection Status
5771**
5772** ^This interface is used to retrieve runtime status information
5773** about a single [database connection].  ^The first argument is the
5774** database connection object to be interrogated.  ^The second argument
5775** is an integer constant, taken from the set of
5776** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
5777** determines the parameter to interrogate.  The set of
5778** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
5779** to grow in future releases of SQLite.
5780**
5781** ^The current value of the requested parameter is written into *pCur
5782** and the highest instantaneous value is written into *pHiwtr.  ^If
5783** the resetFlg is true, then the highest instantaneous value is
5784** reset back down to the current value.
5785**
5786** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5787*/
5788SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5789
5790/*
5791** CAPI3REF: Status Parameters for database connections
5792**
5793** These constants are the available integer "verbs" that can be passed as
5794** the second argument to the [sqlite3_db_status()] interface.
5795**
5796** New verbs may be added in future releases of SQLite. Existing verbs
5797** might be discontinued. Applications should check the return code from
5798** [sqlite3_db_status()] to make sure that the call worked.
5799** The [sqlite3_db_status()] interface will return a non-zero error code
5800** if a discontinued or unsupported verb is invoked.
5801**
5802** <dl>
5803** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5804** <dd>This parameter returns the number of lookaside memory slots currently
5805** checked out.</dd>)^
5806**
5807** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
5808** <dd>This parameter returns the approximate number of of bytes of heap
5809** memory used by all pager caches associated with the database connection.)^
5810** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
5811**
5812** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
5813** <dd>This parameter returns the approximate number of of bytes of heap
5814** memory used to store the schema for all databases associated
5815** with the connection - main, temp, and any [ATTACH]-ed databases.)^
5816** ^The full amount of memory used by the schemas is reported, even if the
5817** schema memory is shared with other database connections due to
5818** [shared cache mode] being enabled.
5819** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
5820**
5821** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
5822** <dd>This parameter returns the approximate number of of bytes of heap
5823** and lookaside memory used by all prepared statements associated with
5824** the database connection.)^
5825** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
5826** </dd>
5827** </dl>
5828*/
5829#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5830#define SQLITE_DBSTATUS_CACHE_USED         1
5831#define SQLITE_DBSTATUS_SCHEMA_USED        2
5832#define SQLITE_DBSTATUS_STMT_USED          3
5833#define SQLITE_DBSTATUS_MAX                3   /* Largest defined DBSTATUS */
5834
5835
5836/*
5837** CAPI3REF: Prepared Statement Status
5838**
5839** ^(Each prepared statement maintains various
5840** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5841** of times it has performed specific operations.)^  These counters can
5842** be used to monitor the performance characteristics of the prepared
5843** statements.  For example, if the number of table steps greatly exceeds
5844** the number of table searches or result rows, that would tend to indicate
5845** that the prepared statement is using a full table scan rather than
5846** an index.
5847**
5848** ^(This interface is used to retrieve and reset counter values from
5849** a [prepared statement].  The first argument is the prepared statement
5850** object to be interrogated.  The second argument
5851** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5852** to be interrogated.)^
5853** ^The current value of the requested counter is returned.
5854** ^If the resetFlg is true, then the counter is reset to zero after this
5855** interface call returns.
5856**
5857** See also: [sqlite3_status()] and [sqlite3_db_status()].
5858*/
5859SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5860
5861/*
5862** CAPI3REF: Status Parameters for prepared statements
5863**
5864** These preprocessor macros define integer codes that name counter
5865** values associated with the [sqlite3_stmt_status()] interface.
5866** The meanings of the various counters are as follows:
5867**
5868** <dl>
5869** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5870** <dd>^This is the number of times that SQLite has stepped forward in
5871** a table as part of a full table scan.  Large numbers for this counter
5872** may indicate opportunities for performance improvement through
5873** careful use of indices.</dd>
5874**
5875** <dt>SQLITE_STMTSTATUS_SORT</dt>
5876** <dd>^This is the number of sort operations that have occurred.
5877** A non-zero value in this counter may indicate an opportunity to
5878** improvement performance through careful use of indices.</dd>
5879**
5880** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
5881** <dd>^This is the number of rows inserted into transient indices that
5882** were created automatically in order to help joins run faster.
5883** A non-zero value in this counter may indicate an opportunity to
5884** improvement performance by adding permanent indices that do not
5885** need to be reinitialized each time the statement is run.</dd>
5886**
5887** </dl>
5888*/
5889#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5890#define SQLITE_STMTSTATUS_SORT              2
5891#define SQLITE_STMTSTATUS_AUTOINDEX         3
5892
5893/*
5894** CAPI3REF: Custom Page Cache Object
5895**
5896** The sqlite3_pcache type is opaque.  It is implemented by
5897** the pluggable module.  The SQLite core has no knowledge of
5898** its size or internal structure and never deals with the
5899** sqlite3_pcache object except by holding and passing pointers
5900** to the object.
5901**
5902** See [sqlite3_pcache_methods] for additional information.
5903*/
5904typedef struct sqlite3_pcache sqlite3_pcache;
5905
5906/*
5907** CAPI3REF: Application Defined Page Cache.
5908** KEYWORDS: {page cache}
5909**
5910** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5911** register an alternative page cache implementation by passing in an
5912** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5913** heap memory used by SQLite is used by the page cache to cache data read
5914** from, or ready to be written to, the database file. By implementing a
5915** custom page cache using this API, an application can control more
5916** precisely the amount of memory consumed by SQLite, the way in which
5917** that memory is allocated and released, and the policies used to
5918** determine exactly which parts of a database file are cached and for
5919** how long.
5920**
5921** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5922** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5923** the application may discard the parameter after the call to
5924** [sqlite3_config()] returns.)^
5925**
5926** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5927** (usually only once during the lifetime of the process). ^(The xInit()
5928** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5929** ^The xInit() method can set up up global structures and/or any mutexes
5930** required by the custom page cache implementation.
5931**
5932** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5933** if the application invokes this API. It can be used to clean up
5934** any outstanding resources before process shutdown, if required.
5935**
5936** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5937** the xInit method, so the xInit method need not be threadsafe.  ^The
5938** xShutdown method is only called from [sqlite3_shutdown()] so it does
5939** not need to be threadsafe either.  All other methods must be threadsafe
5940** in multithreaded applications.
5941**
5942** ^SQLite will never invoke xInit() more than once without an intervening
5943** call to xShutdown().
5944**
5945** ^The xCreate() method is used to construct a new cache instance.  SQLite
5946** will typically create one cache instance for each open database file,
5947** though this is not guaranteed. ^The
5948** first parameter, szPage, is the size in bytes of the pages that must
5949** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5950** will the page size of the database file that is to be cached plus an
5951** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5952** extra R bytes on each page to store metadata about the underlying
5953** database page on disk.  The value of R depends
5954** on the SQLite version, the target platform, and how SQLite was compiled.
5955** ^R is constant for a particular build of SQLite.  ^The second argument to
5956** xCreate(), bPurgeable, is true if the cache being created will
5957** be used to cache database pages of a file stored on disk, or
5958** false if it is used for an in-memory database. ^The cache implementation
5959** does not have to do anything special based with the value of bPurgeable;
5960** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5961** never invoke xUnpin() except to deliberately delete a page.
5962** ^In other words, a cache created with bPurgeable set to false will
5963** never contain any unpinned pages.
5964**
5965** ^(The xCachesize() method may be called at any time by SQLite to set the
5966** suggested maximum cache-size (number of pages stored by) the cache
5967** instance passed as the first argument. This is the value configured using
5968** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5969** parameter, the implementation is not required to do anything with this
5970** value; it is advisory only.
5971**
5972** ^The xPagecount() method should return the number of pages currently
5973** stored in the cache.
5974**
5975** ^The xFetch() method is used to fetch a page and return a pointer to it.
5976** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5977** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5978** mimimum key value is 1. After it has been retrieved using xFetch, the page
5979** is considered to be "pinned".
5980**
5981** ^If the requested page is already in the page cache, then the page cache
5982** implementation must return a pointer to the page buffer with its content
5983** intact.  ^(If the requested page is not already in the cache, then the
5984** behavior of the cache implementation is determined by the value of the
5985** createFlag parameter passed to xFetch, according to the following table:
5986**
5987** <table border=1 width=85% align=center>
5988** <tr><th> createFlag <th> Behaviour when page is not already in cache
5989** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5990** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5991**                 Otherwise return NULL.
5992** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5993**                 NULL if allocating a new page is effectively impossible.
5994** </table>)^
5995**
5996** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5997** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5998** attempt to unpin one or more cache pages by spilling the content of
5999** pinned pages to disk and synching the operating system disk cache. After
6000** attempting to unpin pages, the xFetch() method will be invoked again with
6001** a createFlag of 2.
6002**
6003** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6004** as its second argument. ^(If the third parameter, discard, is non-zero,
6005** then the page should be evicted from the cache. In this case SQLite
6006** assumes that the next time the page is retrieved from the cache using
6007** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
6008** zero, then the page is considered to be unpinned. ^The cache implementation
6009** may choose to evict unpinned pages at any time.
6010**
6011** ^(The cache is not required to perform any reference counting. A single
6012** call to xUnpin() unpins the page regardless of the number of prior calls
6013** to xFetch().)^
6014**
6015** ^The xRekey() method is used to change the key value associated with the
6016** page passed as the second argument from oldKey to newKey. ^If the cache
6017** previously contains an entry associated with newKey, it should be
6018** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6019** to be pinned.
6020**
6021** ^When SQLite calls the xTruncate() method, the cache must discard all
6022** existing cache entries with page numbers (keys) greater than or equal
6023** to the value of the iLimit parameter passed to xTruncate(). ^If any
6024** of these pages are pinned, they are implicitly unpinned, meaning that
6025** they can be safely discarded.
6026**
6027** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6028** All resources associated with the specified cache should be freed. ^After
6029** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6030** handle invalid, and will not use it with any other sqlite3_pcache_methods
6031** functions.
6032*/
6033typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6034struct sqlite3_pcache_methods {
6035  void *pArg;
6036  int (*xInit)(void*);
6037  void (*xShutdown)(void*);
6038  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6039  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6040  int (*xPagecount)(sqlite3_pcache*);
6041  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6042  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6043  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6044  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6045  void (*xDestroy)(sqlite3_pcache*);
6046};
6047
6048/*
6049** CAPI3REF: Online Backup Object
6050**
6051** The sqlite3_backup object records state information about an ongoing
6052** online backup operation.  ^The sqlite3_backup object is created by
6053** a call to [sqlite3_backup_init()] and is destroyed by a call to
6054** [sqlite3_backup_finish()].
6055**
6056** See Also: [Using the SQLite Online Backup API]
6057*/
6058typedef struct sqlite3_backup sqlite3_backup;
6059
6060/*
6061** CAPI3REF: Online Backup API.
6062**
6063** The backup API copies the content of one database into another.
6064** It is useful either for creating backups of databases or
6065** for copying in-memory databases to or from persistent files.
6066**
6067** See Also: [Using the SQLite Online Backup API]
6068**
6069** ^Exclusive access is required to the destination database for the
6070** duration of the operation. ^However the source database is only
6071** read-locked while it is actually being read; it is not locked
6072** continuously for the entire backup operation. ^Thus, the backup may be
6073** performed on a live source database without preventing other users from
6074** reading or writing to the source database while the backup is underway.
6075**
6076** ^(To perform a backup operation:
6077**   <ol>
6078**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6079**         backup,
6080**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6081**         the data between the two databases, and finally
6082**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6083**         associated with the backup operation.
6084**   </ol>)^
6085** There should be exactly one call to sqlite3_backup_finish() for each
6086** successful call to sqlite3_backup_init().
6087**
6088** <b>sqlite3_backup_init()</b>
6089**
6090** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6091** [database connection] associated with the destination database
6092** and the database name, respectively.
6093** ^The database name is "main" for the main database, "temp" for the
6094** temporary database, or the name specified after the AS keyword in
6095** an [ATTACH] statement for an attached database.
6096** ^The S and M arguments passed to
6097** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6098** and database name of the source database, respectively.
6099** ^The source and destination [database connections] (parameters S and D)
6100** must be different or else sqlite3_backup_init(D,N,S,M) will file with
6101** an error.
6102**
6103** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6104** returned and an error code and error message are store3d in the
6105** destination [database connection] D.
6106** ^The error code and message for the failed call to sqlite3_backup_init()
6107** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6108** [sqlite3_errmsg16()] functions.
6109** ^A successful call to sqlite3_backup_init() returns a pointer to an
6110** [sqlite3_backup] object.
6111** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6112** sqlite3_backup_finish() functions to perform the specified backup
6113** operation.
6114**
6115** <b>sqlite3_backup_step()</b>
6116**
6117** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6118** the source and destination databases specified by [sqlite3_backup] object B.
6119** ^If N is negative, all remaining source pages are copied.
6120** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6121** are still more pages to be copied, then the function resturns [SQLITE_OK].
6122** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6123** from source to destination, then it returns [SQLITE_DONE].
6124** ^If an error occurs while running sqlite3_backup_step(B,N),
6125** then an [error code] is returned. ^As well as [SQLITE_OK] and
6126** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6127** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6128** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6129**
6130** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6131** <ol>
6132** <li> the destination database was opened read-only, or
6133** <li> the destination database is using write-ahead-log journaling
6134** and the destination and source page sizes differ, or
6135** <li> The destination database is an in-memory database and the
6136** destination and source page sizes differ.
6137** </ol>)^
6138**
6139** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6140** the [sqlite3_busy_handler | busy-handler function]
6141** is invoked (if one is specified). ^If the
6142** busy-handler returns non-zero before the lock is available, then
6143** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6144** sqlite3_backup_step() can be retried later. ^If the source
6145** [database connection]
6146** is being used to write to the source database when sqlite3_backup_step()
6147** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6148** case the call to sqlite3_backup_step() can be retried later on. ^(If
6149** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6150** [SQLITE_READONLY] is returned, then
6151** there is no point in retrying the call to sqlite3_backup_step(). These
6152** errors are considered fatal.)^  The application must accept
6153** that the backup operation has failed and pass the backup operation handle
6154** to the sqlite3_backup_finish() to release associated resources.
6155**
6156** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6157** on the destination file. ^The exclusive lock is not released until either
6158** sqlite3_backup_finish() is called or the backup operation is complete
6159** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6160** sqlite3_backup_step() obtains a [shared lock] on the source database that
6161** lasts for the duration of the sqlite3_backup_step() call.
6162** ^Because the source database is not locked between calls to
6163** sqlite3_backup_step(), the source database may be modified mid-way
6164** through the backup process.  ^If the source database is modified by an
6165** external process or via a database connection other than the one being
6166** used by the backup operation, then the backup will be automatically
6167** restarted by the next call to sqlite3_backup_step(). ^If the source
6168** database is modified by the using the same database connection as is used
6169** by the backup operation, then the backup database is automatically
6170** updated at the same time.
6171**
6172** <b>sqlite3_backup_finish()</b>
6173**
6174** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6175** application wishes to abandon the backup operation, the application
6176** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6177** ^The sqlite3_backup_finish() interfaces releases all
6178** resources associated with the [sqlite3_backup] object.
6179** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6180** active write-transaction on the destination database is rolled back.
6181** The [sqlite3_backup] object is invalid
6182** and may not be used following a call to sqlite3_backup_finish().
6183**
6184** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6185** sqlite3_backup_step() errors occurred, regardless or whether or not
6186** sqlite3_backup_step() completed.
6187** ^If an out-of-memory condition or IO error occurred during any prior
6188** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6189** sqlite3_backup_finish() returns the corresponding [error code].
6190**
6191** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6192** is not a permanent error and does not affect the return value of
6193** sqlite3_backup_finish().
6194**
6195** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6196**
6197** ^Each call to sqlite3_backup_step() sets two values inside
6198** the [sqlite3_backup] object: the number of pages still to be backed
6199** up and the total number of pages in the source database file.
6200** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6201** retrieve these two values, respectively.
6202**
6203** ^The values returned by these functions are only updated by
6204** sqlite3_backup_step(). ^If the source database is modified during a backup
6205** operation, then the values are not updated to account for any extra
6206** pages that need to be updated or the size of the source database file
6207** changing.
6208**
6209** <b>Concurrent Usage of Database Handles</b>
6210**
6211** ^The source [database connection] may be used by the application for other
6212** purposes while a backup operation is underway or being initialized.
6213** ^If SQLite is compiled and configured to support threadsafe database
6214** connections, then the source database connection may be used concurrently
6215** from within other threads.
6216**
6217** However, the application must guarantee that the destination
6218** [database connection] is not passed to any other API (by any thread) after
6219** sqlite3_backup_init() is called and before the corresponding call to
6220** sqlite3_backup_finish().  SQLite does not currently check to see
6221** if the application incorrectly accesses the destination [database connection]
6222** and so no error code is reported, but the operations may malfunction
6223** nevertheless.  Use of the destination database connection while a
6224** backup is in progress might also also cause a mutex deadlock.
6225**
6226** If running in [shared cache mode], the application must
6227** guarantee that the shared cache used by the destination database
6228** is not accessed while the backup is running. In practice this means
6229** that the application must guarantee that the disk file being
6230** backed up to is not accessed by any connection within the process,
6231** not just the specific connection that was passed to sqlite3_backup_init().
6232**
6233** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6234** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6235** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6236** APIs are not strictly speaking threadsafe. If they are invoked at the
6237** same time as another thread is invoking sqlite3_backup_step() it is
6238** possible that they return invalid values.
6239*/
6240SQLITE_API sqlite3_backup *sqlite3_backup_init(
6241  sqlite3 *pDest,                        /* Destination database handle */
6242  const char *zDestName,                 /* Destination database name */
6243  sqlite3 *pSource,                      /* Source database handle */
6244  const char *zSourceName                /* Source database name */
6245);
6246SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6247SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6248SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6249SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6250
6251/*
6252** CAPI3REF: Unlock Notification
6253**
6254** ^When running in shared-cache mode, a database operation may fail with
6255** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6256** individual tables within the shared-cache cannot be obtained. See
6257** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6258** ^This API may be used to register a callback that SQLite will invoke
6259** when the connection currently holding the required lock relinquishes it.
6260** ^This API is only available if the library was compiled with the
6261** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6262**
6263** See Also: [Using the SQLite Unlock Notification Feature].
6264**
6265** ^Shared-cache locks are released when a database connection concludes
6266** its current transaction, either by committing it or rolling it back.
6267**
6268** ^When a connection (known as the blocked connection) fails to obtain a
6269** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6270** identity of the database connection (the blocking connection) that
6271** has locked the required resource is stored internally. ^After an
6272** application receives an SQLITE_LOCKED error, it may call the
6273** sqlite3_unlock_notify() method with the blocked connection handle as
6274** the first argument to register for a callback that will be invoked
6275** when the blocking connections current transaction is concluded. ^The
6276** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6277** call that concludes the blocking connections transaction.
6278**
6279** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6280** there is a chance that the blocking connection will have already
6281** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6282** If this happens, then the specified callback is invoked immediately,
6283** from within the call to sqlite3_unlock_notify().)^
6284**
6285** ^If the blocked connection is attempting to obtain a write-lock on a
6286** shared-cache table, and more than one other connection currently holds
6287** a read-lock on the same table, then SQLite arbitrarily selects one of
6288** the other connections to use as the blocking connection.
6289**
6290** ^(There may be at most one unlock-notify callback registered by a
6291** blocked connection. If sqlite3_unlock_notify() is called when the
6292** blocked connection already has a registered unlock-notify callback,
6293** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6294** called with a NULL pointer as its second argument, then any existing
6295** unlock-notify callback is canceled. ^The blocked connections
6296** unlock-notify callback may also be canceled by closing the blocked
6297** connection using [sqlite3_close()].
6298**
6299** The unlock-notify callback is not reentrant. If an application invokes
6300** any sqlite3_xxx API functions from within an unlock-notify callback, a
6301** crash or deadlock may be the result.
6302**
6303** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6304** returns SQLITE_OK.
6305**
6306** <b>Callback Invocation Details</b>
6307**
6308** When an unlock-notify callback is registered, the application provides a
6309** single void* pointer that is passed to the callback when it is invoked.
6310** However, the signature of the callback function allows SQLite to pass
6311** it an array of void* context pointers. The first argument passed to
6312** an unlock-notify callback is a pointer to an array of void* pointers,
6313** and the second is the number of entries in the array.
6314**
6315** When a blocking connections transaction is concluded, there may be
6316** more than one blocked connection that has registered for an unlock-notify
6317** callback. ^If two or more such blocked connections have specified the
6318** same callback function, then instead of invoking the callback function
6319** multiple times, it is invoked once with the set of void* context pointers
6320** specified by the blocked connections bundled together into an array.
6321** This gives the application an opportunity to prioritize any actions
6322** related to the set of unblocked database connections.
6323**
6324** <b>Deadlock Detection</b>
6325**
6326** Assuming that after registering for an unlock-notify callback a
6327** database waits for the callback to be issued before taking any further
6328** action (a reasonable assumption), then using this API may cause the
6329** application to deadlock. For example, if connection X is waiting for
6330** connection Y's transaction to be concluded, and similarly connection
6331** Y is waiting on connection X's transaction, then neither connection
6332** will proceed and the system may remain deadlocked indefinitely.
6333**
6334** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6335** detection. ^If a given call to sqlite3_unlock_notify() would put the
6336** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6337** unlock-notify callback is registered. The system is said to be in
6338** a deadlocked state if connection A has registered for an unlock-notify
6339** callback on the conclusion of connection B's transaction, and connection
6340** B has itself registered for an unlock-notify callback when connection
6341** A's transaction is concluded. ^Indirect deadlock is also detected, so
6342** the system is also considered to be deadlocked if connection B has
6343** registered for an unlock-notify callback on the conclusion of connection
6344** C's transaction, where connection C is waiting on connection A. ^Any
6345** number of levels of indirection are allowed.
6346**
6347** <b>The "DROP TABLE" Exception</b>
6348**
6349** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6350** always appropriate to call sqlite3_unlock_notify(). There is however,
6351** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6352** SQLite checks if there are any currently executing SELECT statements
6353** that belong to the same connection. If there are, SQLITE_LOCKED is
6354** returned. In this case there is no "blocking connection", so invoking
6355** sqlite3_unlock_notify() results in the unlock-notify callback being
6356** invoked immediately. If the application then re-attempts the "DROP TABLE"
6357** or "DROP INDEX" query, an infinite loop might be the result.
6358**
6359** One way around this problem is to check the extended error code returned
6360** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6361** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6362** the special "DROP TABLE/INDEX" case, the extended error code is just
6363** SQLITE_LOCKED.)^
6364*/
6365SQLITE_API int sqlite3_unlock_notify(
6366  sqlite3 *pBlocked,                          /* Waiting connection */
6367  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6368  void *pNotifyArg                            /* Argument to pass to xNotify */
6369);
6370
6371
6372/*
6373** CAPI3REF: String Comparison
6374**
6375** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6376** compare the contents of two buffers containing UTF-8 strings in a
6377** case-independent fashion, using the same definition of case independence
6378** that SQLite uses internally when comparing identifiers.
6379*/
6380SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6381
6382/*
6383** CAPI3REF: Error Logging Interface
6384**
6385** ^The [sqlite3_log()] interface writes a message into the error log
6386** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6387** ^If logging is enabled, the zFormat string and subsequent arguments are
6388** used with [sqlite3_snprintf()] to generate the final output string.
6389**
6390** The sqlite3_log() interface is intended for use by extensions such as
6391** virtual tables, collating functions, and SQL functions.  While there is
6392** nothing to prevent an application from calling sqlite3_log(), doing so
6393** is considered bad form.
6394**
6395** The zFormat string must not be NULL.
6396**
6397** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6398** will not use dynamically allocated memory.  The log message is stored in
6399** a fixed-length buffer on the stack.  If the log message is longer than
6400** a few hundred characters, it will be truncated to the length of the
6401** buffer.
6402*/
6403SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6404
6405/*
6406** CAPI3REF: Write-Ahead Log Commit Hook
6407**
6408** ^The [sqlite3_wal_hook()] function is used to register a callback that
6409** will be invoked each time a database connection commits data to a
6410** [write-ahead log] (i.e. whenever a transaction is committed in
6411** [journal_mode | journal_mode=WAL mode]).
6412**
6413** ^The callback is invoked by SQLite after the commit has taken place and
6414** the associated write-lock on the database released, so the implementation
6415** may read, write or [checkpoint] the database as required.
6416**
6417** ^The first parameter passed to the callback function when it is invoked
6418** is a copy of the third parameter passed to sqlite3_wal_hook() when
6419** registering the callback. ^The second is a copy of the database handle.
6420** ^The third parameter is the name of the database that was written to -
6421** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6422** is the number of pages currently in the write-ahead log file,
6423** including those that were just committed.
6424**
6425** The callback function should normally return [SQLITE_OK].  ^If an error
6426** code is returned, that error will propagate back up through the
6427** SQLite code base to cause the statement that provoked the callback
6428** to report an error, though the commit will have still occurred. If the
6429** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6430** that does not correspond to any valid SQLite error code, the results
6431** are undefined.
6432**
6433** A single database handle may have at most a single write-ahead log callback
6434** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6435** previously registered write-ahead log callback. ^Note that the
6436** [sqlite3_wal_autocheckpoint()] interface and the
6437** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6438** those overwrite any prior [sqlite3_wal_hook()] settings.
6439*/
6440SQLITE_API void *sqlite3_wal_hook(
6441  sqlite3*,
6442  int(*)(void *,sqlite3*,const char*,int),
6443  void*
6444);
6445
6446/*
6447** CAPI3REF: Configure an auto-checkpoint
6448**
6449** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6450** [sqlite3_wal_hook()] that causes any database on [database connection] D
6451** to automatically [checkpoint]
6452** after committing a transaction if there are N or
6453** more frames in the [write-ahead log] file.  ^Passing zero or
6454** a negative value as the nFrame parameter disables automatic
6455** checkpoints entirely.
6456**
6457** ^The callback registered by this function replaces any existing callback
6458** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6459** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6460** configured by this function.
6461**
6462** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6463** from SQL.
6464**
6465** ^Every new [database connection] defaults to having the auto-checkpoint
6466** enabled with a threshold of 1000 pages.  The use of this interface
6467** is only necessary if the default setting is found to be suboptimal
6468** for a particular application.
6469*/
6470SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6471
6472/*
6473** CAPI3REF: Checkpoint a database
6474**
6475** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6476** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6477** empty string, then a checkpoint is run on all databases of
6478** connection D.  ^If the database connection D is not in
6479** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6480**
6481** ^The [wal_checkpoint pragma] can be used to invoke this interface
6482** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6483** [wal_autocheckpoint pragma] can be used to cause this interface to be
6484** run whenever the WAL reaches a certain size threshold.
6485*/
6486SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6487
6488/*
6489** Undo the hack that converts floating point types to integer for
6490** builds on processors without floating point support.
6491*/
6492#ifdef SQLITE_OMIT_FLOATING_POINT
6493# undef double
6494#endif
6495
6496#if 0
6497}  /* End of the 'extern "C"' block */
6498#endif
6499#endif
6500
6501
6502/************** End of sqlite3.h *********************************************/
6503/************** Continuing where we left off in sqliteInt.h ******************/
6504/************** Include hash.h in the middle of sqliteInt.h ******************/
6505/************** Begin file hash.h ********************************************/
6506/*
6507** 2001 September 22
6508**
6509** The author disclaims copyright to this source code.  In place of
6510** a legal notice, here is a blessing:
6511**
6512**    May you do good and not evil.
6513**    May you find forgiveness for yourself and forgive others.
6514**    May you share freely, never taking more than you give.
6515**
6516*************************************************************************
6517** This is the header file for the generic hash-table implemenation
6518** used in SQLite.
6519*/
6520#ifndef _SQLITE_HASH_H_
6521#define _SQLITE_HASH_H_
6522
6523/* Forward declarations of structures. */
6524typedef struct Hash Hash;
6525typedef struct HashElem HashElem;
6526
6527/* A complete hash table is an instance of the following structure.
6528** The internals of this structure are intended to be opaque -- client
6529** code should not attempt to access or modify the fields of this structure
6530** directly.  Change this structure only by using the routines below.
6531** However, some of the "procedures" and "functions" for modifying and
6532** accessing this structure are really macros, so we can't really make
6533** this structure opaque.
6534**
6535** All elements of the hash table are on a single doubly-linked list.
6536** Hash.first points to the head of this list.
6537**
6538** There are Hash.htsize buckets.  Each bucket points to a spot in
6539** the global doubly-linked list.  The contents of the bucket are the
6540** element pointed to plus the next _ht.count-1 elements in the list.
6541**
6542** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6543** by a linear search of the global list.  For small tables, the
6544** Hash.ht table is never allocated because if there are few elements
6545** in the table, it is faster to do a linear search than to manage
6546** the hash table.
6547*/
6548struct Hash {
6549  unsigned int htsize;      /* Number of buckets in the hash table */
6550  unsigned int count;       /* Number of entries in this table */
6551  HashElem *first;          /* The first element of the array */
6552  struct _ht {              /* the hash table */
6553    int count;                 /* Number of entries with this hash */
6554    HashElem *chain;           /* Pointer to first entry with this hash */
6555  } *ht;
6556};
6557
6558/* Each element in the hash table is an instance of the following
6559** structure.  All elements are stored on a single doubly-linked list.
6560**
6561** Again, this structure is intended to be opaque, but it can't really
6562** be opaque because it is used by macros.
6563*/
6564struct HashElem {
6565  HashElem *next, *prev;       /* Next and previous elements in the table */
6566  void *data;                  /* Data associated with this element */
6567  const char *pKey; int nKey;  /* Key associated with this element */
6568};
6569
6570/*
6571** Access routines.  To delete, insert a NULL pointer.
6572*/
6573SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6574SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6575SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6576SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6577
6578/*
6579** Macros for looping over all elements of a hash table.  The idiom is
6580** like this:
6581**
6582**   Hash h;
6583**   HashElem *p;
6584**   ...
6585**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6586**     SomeStructure *pData = sqliteHashData(p);
6587**     // do something with pData
6588**   }
6589*/
6590#define sqliteHashFirst(H)  ((H)->first)
6591#define sqliteHashNext(E)   ((E)->next)
6592#define sqliteHashData(E)   ((E)->data)
6593/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6594/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6595
6596/*
6597** Number of entries in a hash table
6598*/
6599/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6600
6601#endif /* _SQLITE_HASH_H_ */
6602
6603/************** End of hash.h ************************************************/
6604/************** Continuing where we left off in sqliteInt.h ******************/
6605/************** Include parse.h in the middle of sqliteInt.h *****************/
6606/************** Begin file parse.h *******************************************/
6607#define TK_SEMI                            1
6608#define TK_EXPLAIN                         2
6609#define TK_QUERY                           3
6610#define TK_PLAN                            4
6611#define TK_BEGIN                           5
6612#define TK_TRANSACTION                     6
6613#define TK_DEFERRED                        7
6614#define TK_IMMEDIATE                       8
6615#define TK_EXCLUSIVE                       9
6616#define TK_COMMIT                         10
6617#define TK_END                            11
6618#define TK_ROLLBACK                       12
6619#define TK_SAVEPOINT                      13
6620#define TK_RELEASE                        14
6621#define TK_TO                             15
6622#define TK_TABLE                          16
6623#define TK_CREATE                         17
6624#define TK_IF                             18
6625#define TK_NOT                            19
6626#define TK_EXISTS                         20
6627#define TK_TEMP                           21
6628#define TK_LP                             22
6629#define TK_RP                             23
6630#define TK_AS                             24
6631#define TK_COMMA                          25
6632#define TK_ID                             26
6633#define TK_INDEXED                        27
6634#define TK_ABORT                          28
6635#define TK_ACTION                         29
6636#define TK_AFTER                          30
6637#define TK_ANALYZE                        31
6638#define TK_ASC                            32
6639#define TK_ATTACH                         33
6640#define TK_BEFORE                         34
6641#define TK_BY                             35
6642#define TK_CASCADE                        36
6643#define TK_CAST                           37
6644#define TK_COLUMNKW                       38
6645#define TK_CONFLICT                       39
6646#define TK_DATABASE                       40
6647#define TK_DESC                           41
6648#define TK_DETACH                         42
6649#define TK_EACH                           43
6650#define TK_FAIL                           44
6651#define TK_FOR                            45
6652#define TK_IGNORE                         46
6653#define TK_INITIALLY                      47
6654#define TK_INSTEAD                        48
6655#define TK_LIKE_KW                        49
6656#define TK_MATCH                          50
6657#define TK_NO                             51
6658#define TK_KEY                            52
6659#define TK_OF                             53
6660#define TK_OFFSET                         54
6661#define TK_PRAGMA                         55
6662#define TK_RAISE                          56
6663#define TK_REPLACE                        57
6664#define TK_RESTRICT                       58
6665#define TK_ROW                            59
6666#define TK_TRIGGER                        60
6667#define TK_VACUUM                         61
6668#define TK_VIEW                           62
6669#define TK_VIRTUAL                        63
6670#define TK_REINDEX                        64
6671#define TK_RENAME                         65
6672#define TK_CTIME_KW                       66
6673#define TK_ANY                            67
6674#define TK_OR                             68
6675#define TK_AND                            69
6676#define TK_IS                             70
6677#define TK_BETWEEN                        71
6678#define TK_IN                             72
6679#define TK_ISNULL                         73
6680#define TK_NOTNULL                        74
6681#define TK_NE                             75
6682#define TK_EQ                             76
6683#define TK_GT                             77
6684#define TK_LE                             78
6685#define TK_LT                             79
6686#define TK_GE                             80
6687#define TK_ESCAPE                         81
6688#define TK_BITAND                         82
6689#define TK_BITOR                          83
6690#define TK_LSHIFT                         84
6691#define TK_RSHIFT                         85
6692#define TK_PLUS                           86
6693#define TK_MINUS                          87
6694#define TK_STAR                           88
6695#define TK_SLASH                          89
6696#define TK_REM                            90
6697#define TK_CONCAT                         91
6698#define TK_COLLATE                        92
6699#define TK_BITNOT                         93
6700#define TK_STRING                         94
6701#define TK_JOIN_KW                        95
6702#define TK_CONSTRAINT                     96
6703#define TK_DEFAULT                        97
6704#define TK_NULL                           98
6705#define TK_PRIMARY                        99
6706#define TK_UNIQUE                         100
6707#define TK_CHECK                          101
6708#define TK_REFERENCES                     102
6709#define TK_AUTOINCR                       103
6710#define TK_ON                             104
6711#define TK_INSERT                         105
6712#define TK_DELETE                         106
6713#define TK_UPDATE                         107
6714#define TK_SET                            108
6715#define TK_DEFERRABLE                     109
6716#define TK_FOREIGN                        110
6717#define TK_DROP                           111
6718#define TK_UNION                          112
6719#define TK_ALL                            113
6720#define TK_EXCEPT                         114
6721#define TK_INTERSECT                      115
6722#define TK_SELECT                         116
6723#define TK_DISTINCT                       117
6724#define TK_DOT                            118
6725#define TK_FROM                           119
6726#define TK_JOIN                           120
6727#define TK_USING                          121
6728#define TK_ORDER                          122
6729#define TK_GROUP                          123
6730#define TK_HAVING                         124
6731#define TK_LIMIT                          125
6732#define TK_WHERE                          126
6733#define TK_INTO                           127
6734#define TK_VALUES                         128
6735#define TK_INTEGER                        129
6736#define TK_FLOAT                          130
6737#define TK_BLOB                           131
6738#define TK_REGISTER                       132
6739#define TK_VARIABLE                       133
6740#define TK_CASE                           134
6741#define TK_WHEN                           135
6742#define TK_THEN                           136
6743#define TK_ELSE                           137
6744#define TK_INDEX                          138
6745#define TK_ALTER                          139
6746#define TK_ADD                            140
6747#define TK_TO_TEXT                        141
6748#define TK_TO_BLOB                        142
6749#define TK_TO_NUMERIC                     143
6750#define TK_TO_INT                         144
6751#define TK_TO_REAL                        145
6752#define TK_ISNOT                          146
6753#define TK_END_OF_FILE                    147
6754#define TK_ILLEGAL                        148
6755#define TK_SPACE                          149
6756#define TK_UNCLOSED_STRING                150
6757#define TK_FUNCTION                       151
6758#define TK_COLUMN                         152
6759#define TK_AGG_FUNCTION                   153
6760#define TK_AGG_COLUMN                     154
6761#define TK_CONST_FUNC                     155
6762#define TK_UMINUS                         156
6763#define TK_UPLUS                          157
6764
6765/************** End of parse.h ***********************************************/
6766/************** Continuing where we left off in sqliteInt.h ******************/
6767#include <stdio.h>
6768#include <stdlib.h>
6769#include <string.h>
6770#include <assert.h>
6771#include <stddef.h>
6772
6773/*
6774** If compiling for a processor that lacks floating point support,
6775** substitute integer for floating-point
6776*/
6777#ifdef SQLITE_OMIT_FLOATING_POINT
6778# define double sqlite_int64
6779# define float sqlite_int64
6780# define LONGDOUBLE_TYPE sqlite_int64
6781# ifndef SQLITE_BIG_DBL
6782#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6783# endif
6784# define SQLITE_OMIT_DATETIME_FUNCS 1
6785# define SQLITE_OMIT_TRACE 1
6786# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6787# undef SQLITE_HAVE_ISNAN
6788#endif
6789#ifndef SQLITE_BIG_DBL
6790# define SQLITE_BIG_DBL (1e99)
6791#endif
6792
6793/*
6794** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6795** afterward. Having this macro allows us to cause the C compiler
6796** to omit code used by TEMP tables without messy #ifndef statements.
6797*/
6798#ifdef SQLITE_OMIT_TEMPDB
6799#define OMIT_TEMPDB 1
6800#else
6801#define OMIT_TEMPDB 0
6802#endif
6803
6804/*
6805** The "file format" number is an integer that is incremented whenever
6806** the VDBE-level file format changes.  The following macros define the
6807** the default file format for new databases and the maximum file format
6808** that the library can read.
6809*/
6810#define SQLITE_MAX_FILE_FORMAT 4
6811#ifndef SQLITE_DEFAULT_FILE_FORMAT
6812# define SQLITE_DEFAULT_FILE_FORMAT 1
6813#endif
6814
6815/*
6816** Determine whether triggers are recursive by default.  This can be
6817** changed at run-time using a pragma.
6818*/
6819#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6820# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6821#endif
6822
6823/*
6824** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6825** on the command-line
6826*/
6827#ifndef SQLITE_TEMP_STORE
6828# define SQLITE_TEMP_STORE 1
6829#endif
6830
6831/*
6832** GCC does not define the offsetof() macro so we'll have to do it
6833** ourselves.
6834*/
6835#ifndef offsetof
6836#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6837#endif
6838
6839/*
6840** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6841** not, there are still machines out there that use EBCDIC.)
6842*/
6843#if 'A' == '\301'
6844# define SQLITE_EBCDIC 1
6845#else
6846# define SQLITE_ASCII 1
6847#endif
6848
6849/*
6850** Integers of known sizes.  These typedefs might change for architectures
6851** where the sizes very.  Preprocessor macros are available so that the
6852** types can be conveniently redefined at compile-type.  Like this:
6853**
6854**         cc '-DUINTPTR_TYPE=long long int' ...
6855*/
6856#ifndef UINT32_TYPE
6857# ifdef HAVE_UINT32_T
6858#  define UINT32_TYPE uint32_t
6859# else
6860#  define UINT32_TYPE unsigned int
6861# endif
6862#endif
6863#ifndef UINT16_TYPE
6864# ifdef HAVE_UINT16_T
6865#  define UINT16_TYPE uint16_t
6866# else
6867#  define UINT16_TYPE unsigned short int
6868# endif
6869#endif
6870#ifndef INT16_TYPE
6871# ifdef HAVE_INT16_T
6872#  define INT16_TYPE int16_t
6873# else
6874#  define INT16_TYPE short int
6875# endif
6876#endif
6877#ifndef UINT8_TYPE
6878# ifdef HAVE_UINT8_T
6879#  define UINT8_TYPE uint8_t
6880# else
6881#  define UINT8_TYPE unsigned char
6882# endif
6883#endif
6884#ifndef INT8_TYPE
6885# ifdef HAVE_INT8_T
6886#  define INT8_TYPE int8_t
6887# else
6888#  define INT8_TYPE signed char
6889# endif
6890#endif
6891#ifndef LONGDOUBLE_TYPE
6892# define LONGDOUBLE_TYPE long double
6893#endif
6894typedef sqlite_int64 i64;          /* 8-byte signed integer */
6895typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6896typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6897typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6898typedef INT16_TYPE i16;            /* 2-byte signed integer */
6899typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6900typedef INT8_TYPE i8;              /* 1-byte signed integer */
6901
6902/*
6903** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6904** that can be stored in a u32 without loss of data.  The value
6905** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6906** have to specify the value in the less intuitive manner shown:
6907*/
6908#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6909
6910/*
6911** Macros to determine whether the machine is big or little endian,
6912** evaluated at runtime.
6913*/
6914#ifdef SQLITE_AMALGAMATION
6915SQLITE_PRIVATE const int sqlite3one = 1;
6916#else
6917SQLITE_PRIVATE const int sqlite3one;
6918#endif
6919#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6920                             || defined(__x86_64) || defined(__x86_64__)
6921# define SQLITE_BIGENDIAN    0
6922# define SQLITE_LITTLEENDIAN 1
6923# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6924#else
6925# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6926# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6927# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6928#endif
6929
6930/*
6931** Constants for the largest and smallest possible 64-bit signed integers.
6932** These macros are designed to work correctly on both 32-bit and 64-bit
6933** compilers.
6934*/
6935#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6936#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6937
6938/*
6939** Round up a number to the next larger multiple of 8.  This is used
6940** to force 8-byte alignment on 64-bit architectures.
6941*/
6942#define ROUND8(x)     (((x)+7)&~7)
6943
6944/*
6945** Round down to the nearest multiple of 8
6946*/
6947#define ROUNDDOWN8(x) ((x)&~7)
6948
6949/*
6950** Assert that the pointer X is aligned to an 8-byte boundary.  This
6951** macro is used only within assert() to verify that the code gets
6952** all alignment restrictions correct.
6953**
6954** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6955** underlying malloc() implemention might return us 4-byte aligned
6956** pointers.  In that case, only verify 4-byte alignment.
6957*/
6958#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6959# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6960#else
6961# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6962#endif
6963
6964
6965/*
6966** An instance of the following structure is used to store the busy-handler
6967** callback for a given sqlite handle.
6968**
6969** The sqlite.busyHandler member of the sqlite struct contains the busy
6970** callback for the database handle. Each pager opened via the sqlite
6971** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6972** callback is currently invoked only from within pager.c.
6973*/
6974typedef struct BusyHandler BusyHandler;
6975struct BusyHandler {
6976  int (*xFunc)(void *,int);  /* The busy callback */
6977  void *pArg;                /* First arg to busy callback */
6978  int nBusy;                 /* Incremented with each busy call */
6979};
6980
6981/*
6982** Name of the master database table.  The master database table
6983** is a special table that holds the names and attributes of all
6984** user tables and indices.
6985*/
6986#define MASTER_NAME       "sqlite_master"
6987#define TEMP_MASTER_NAME  "sqlite_temp_master"
6988
6989/*
6990** The root-page of the master database table.
6991*/
6992#define MASTER_ROOT       1
6993
6994/*
6995** The name of the schema table.
6996*/
6997#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6998
6999/*
7000** A convenience macro that returns the number of elements in
7001** an array.
7002*/
7003#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7004
7005/*
7006** The following value as a destructor means to use sqlite3DbFree().
7007** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7008*/
7009#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7010
7011/*
7012** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7013** not support Writable Static Data (WSD) such as global and static variables.
7014** All variables must either be on the stack or dynamically allocated from
7015** the heap.  When WSD is unsupported, the variable declarations scattered
7016** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7017** macro is used for this purpose.  And instead of referencing the variable
7018** directly, we use its constant as a key to lookup the run-time allocated
7019** buffer that holds real variable.  The constant is also the initializer
7020** for the run-time allocated buffer.
7021**
7022** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7023** macros become no-ops and have zero performance impact.
7024*/
7025#ifdef SQLITE_OMIT_WSD
7026  #define SQLITE_WSD const
7027  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7028  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7029SQLITE_API   int sqlite3_wsd_init(int N, int J);
7030SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7031#else
7032  #define SQLITE_WSD
7033  #define GLOBAL(t,v) v
7034  #define sqlite3GlobalConfig sqlite3Config
7035#endif
7036
7037/*
7038** The following macros are used to suppress compiler warnings and to
7039** make it clear to human readers when a function parameter is deliberately
7040** left unused within the body of a function. This usually happens when
7041** a function is called via a function pointer. For example the
7042** implementation of an SQL aggregate step callback may not use the
7043** parameter indicating the number of arguments passed to the aggregate,
7044** if it knows that this is enforced elsewhere.
7045**
7046** When a function parameter is not used at all within the body of a function,
7047** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7048** However, these macros may also be used to suppress warnings related to
7049** parameters that may or may not be used depending on compilation options.
7050** For example those parameters only used in assert() statements. In these
7051** cases the parameters are named as per the usual conventions.
7052*/
7053#define UNUSED_PARAMETER(x) (void)(x)
7054#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7055
7056/*
7057** Forward references to structures
7058*/
7059typedef struct AggInfo AggInfo;
7060typedef struct AuthContext AuthContext;
7061typedef struct AutoincInfo AutoincInfo;
7062typedef struct Bitvec Bitvec;
7063typedef struct CollSeq CollSeq;
7064typedef struct Column Column;
7065typedef struct Db Db;
7066typedef struct Schema Schema;
7067typedef struct Expr Expr;
7068typedef struct ExprList ExprList;
7069typedef struct ExprSpan ExprSpan;
7070typedef struct FKey FKey;
7071typedef struct FuncDef FuncDef;
7072typedef struct FuncDefHash FuncDefHash;
7073typedef struct IdList IdList;
7074typedef struct Index Index;
7075typedef struct IndexSample IndexSample;
7076typedef struct KeyClass KeyClass;
7077typedef struct KeyInfo KeyInfo;
7078typedef struct Lookaside Lookaside;
7079typedef struct LookasideSlot LookasideSlot;
7080typedef struct Module Module;
7081typedef struct NameContext NameContext;
7082typedef struct Parse Parse;
7083typedef struct RowSet RowSet;
7084typedef struct Savepoint Savepoint;
7085typedef struct Select Select;
7086typedef struct SrcList SrcList;
7087typedef struct StrAccum StrAccum;
7088typedef struct Table Table;
7089typedef struct TableLock TableLock;
7090typedef struct Token Token;
7091typedef struct Trigger Trigger;
7092typedef struct TriggerPrg TriggerPrg;
7093typedef struct TriggerStep TriggerStep;
7094typedef struct UnpackedRecord UnpackedRecord;
7095typedef struct VTable VTable;
7096typedef struct Walker Walker;
7097typedef struct WherePlan WherePlan;
7098typedef struct WhereInfo WhereInfo;
7099typedef struct WhereLevel WhereLevel;
7100
7101/*
7102** Defer sourcing vdbe.h and btree.h until after the "u8" and
7103** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7104** pointer types (i.e. FuncDef) defined above.
7105*/
7106/************** Include btree.h in the middle of sqliteInt.h *****************/
7107/************** Begin file btree.h *******************************************/
7108/*
7109** 2001 September 15
7110**
7111** The author disclaims copyright to this source code.  In place of
7112** a legal notice, here is a blessing:
7113**
7114**    May you do good and not evil.
7115**    May you find forgiveness for yourself and forgive others.
7116**    May you share freely, never taking more than you give.
7117**
7118*************************************************************************
7119** This header file defines the interface that the sqlite B-Tree file
7120** subsystem.  See comments in the source code for a detailed description
7121** of what each interface routine does.
7122*/
7123#ifndef _BTREE_H_
7124#define _BTREE_H_
7125
7126/* TODO: This definition is just included so other modules compile. It
7127** needs to be revisited.
7128*/
7129#define SQLITE_N_BTREE_META 10
7130
7131/*
7132** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7133** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7134*/
7135#ifndef SQLITE_DEFAULT_AUTOVACUUM
7136  #define SQLITE_DEFAULT_AUTOVACUUM 0
7137#endif
7138
7139#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7140#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7141#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7142
7143/*
7144** Forward declarations of structure
7145*/
7146typedef struct Btree Btree;
7147typedef struct BtCursor BtCursor;
7148typedef struct BtShared BtShared;
7149typedef struct BtreeMutexArray BtreeMutexArray;
7150
7151/*
7152** This structure records all of the Btrees that need to hold
7153** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7154** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7155** we can always lock and unlock them all quickly.
7156*/
7157struct BtreeMutexArray {
7158  int nMutex;
7159  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7160};
7161
7162
7163SQLITE_PRIVATE int sqlite3BtreeOpen(
7164  const char *zFilename,   /* Name of database file to open */
7165  sqlite3 *db,             /* Associated database connection */
7166  Btree **ppBtree,         /* Return open Btree* here */
7167  int flags,               /* Flags */
7168  int vfsFlags             /* Flags passed through to VFS open */
7169);
7170
7171/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7172** following values.
7173**
7174** NOTE:  These values must match the corresponding PAGER_ values in
7175** pager.h.
7176*/
7177#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
7178#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7179#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
7180#define BTREE_READONLY      8  /* Open the database in read-only mode */
7181#define BTREE_READWRITE    16  /* Open for both reading and writing */
7182#define BTREE_CREATE       32  /* Create the database if it does not exist */
7183
7184SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7185SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7186SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7187SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7188SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7189SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7190SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7191SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7192SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7193SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7194SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7195SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7196SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7197SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7198SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7199SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7200SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7201SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7202SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7203SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7204SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7205SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7206SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7207SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7208SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7209SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7210
7211SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7212SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7213SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7214
7215SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7216
7217/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7218** of the following flags:
7219*/
7220#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7221#define BTREE_ZERODATA   2    /* Table has keys only - no data */
7222#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
7223
7224SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7225SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7226SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7227
7228SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7229SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7230
7231/*
7232** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7233** should be one of the following values. The integer values are assigned
7234** to constants so that the offset of the corresponding field in an
7235** SQLite database header may be found using the following formula:
7236**
7237**   offset = 36 + (idx * 4)
7238**
7239** For example, the free-page-count field is located at byte offset 36 of
7240** the database file header. The incr-vacuum-flag field is located at
7241** byte offset 64 (== 36+4*7).
7242*/
7243#define BTREE_FREE_PAGE_COUNT     0
7244#define BTREE_SCHEMA_VERSION      1
7245#define BTREE_FILE_FORMAT         2
7246#define BTREE_DEFAULT_CACHE_SIZE  3
7247#define BTREE_LARGEST_ROOT_PAGE   4
7248#define BTREE_TEXT_ENCODING       5
7249#define BTREE_USER_VERSION        6
7250#define BTREE_INCR_VACUUM         7
7251
7252SQLITE_PRIVATE int sqlite3BtreeCursor(
7253  Btree*,                              /* BTree containing table to open */
7254  int iTable,                          /* Index of root page */
7255  int wrFlag,                          /* 1 for writing.  0 for read-only */
7256  struct KeyInfo*,                     /* First argument to compare function */
7257  BtCursor *pCursor                    /* Space to write cursor structure */
7258);
7259SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7260SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7261
7262SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7263SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7264  BtCursor*,
7265  UnpackedRecord *pUnKey,
7266  i64 intKey,
7267  int bias,
7268  int *pRes
7269);
7270SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7271SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7272SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7273                                  const void *pData, int nData,
7274                                  int nZero, int bias, int seekResult);
7275SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7276SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7277SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7278SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7279SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7280SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7281SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7282SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7283SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7284SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7285SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7286SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7287SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7288
7289SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7290SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7291
7292SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7293SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7294SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7295
7296SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7297
7298#ifndef NDEBUG
7299SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7300#endif
7301
7302#ifndef SQLITE_OMIT_BTREECOUNT
7303SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7304#endif
7305
7306#ifdef SQLITE_TEST
7307SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7308SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7309#endif
7310
7311#ifndef SQLITE_OMIT_WAL
7312SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*);
7313#endif
7314
7315/*
7316** If we are not using shared cache, then there is no need to
7317** use mutexes to access the BtShared structures.  So make the
7318** Enter and Leave procedures no-ops.
7319*/
7320#ifndef SQLITE_OMIT_SHARED_CACHE
7321SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7322SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7323#else
7324# define sqlite3BtreeEnter(X)
7325# define sqlite3BtreeEnterAll(X)
7326#endif
7327
7328#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7329SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7330SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7331SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7332SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7333SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7334SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7335SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7336#ifndef NDEBUG
7337  /* These routines are used inside assert() statements only. */
7338SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7339SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7340#endif
7341#else
7342
7343# define sqlite3BtreeLeave(X)
7344# define sqlite3BtreeEnterCursor(X)
7345# define sqlite3BtreeLeaveCursor(X)
7346# define sqlite3BtreeLeaveAll(X)
7347# define sqlite3BtreeMutexArrayEnter(X)
7348# define sqlite3BtreeMutexArrayLeave(X)
7349# define sqlite3BtreeMutexArrayInsert(X,Y)
7350
7351# define sqlite3BtreeHoldsMutex(X) 1
7352# define sqlite3BtreeHoldsAllMutexes(X) 1
7353#endif
7354
7355
7356#endif /* _BTREE_H_ */
7357
7358/************** End of btree.h ***********************************************/
7359/************** Continuing where we left off in sqliteInt.h ******************/
7360/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7361/************** Begin file vdbe.h ********************************************/
7362/*
7363** 2001 September 15
7364**
7365** The author disclaims copyright to this source code.  In place of
7366** a legal notice, here is a blessing:
7367**
7368**    May you do good and not evil.
7369**    May you find forgiveness for yourself and forgive others.
7370**    May you share freely, never taking more than you give.
7371**
7372*************************************************************************
7373** Header file for the Virtual DataBase Engine (VDBE)
7374**
7375** This header defines the interface to the virtual database engine
7376** or VDBE.  The VDBE implements an abstract machine that runs a
7377** simple program to access and modify the underlying database.
7378*/
7379#ifndef _SQLITE_VDBE_H_
7380#define _SQLITE_VDBE_H_
7381
7382/*
7383** A single VDBE is an opaque structure named "Vdbe".  Only routines
7384** in the source file sqliteVdbe.c are allowed to see the insides
7385** of this structure.
7386*/
7387typedef struct Vdbe Vdbe;
7388
7389/*
7390** The names of the following types declared in vdbeInt.h are required
7391** for the VdbeOp definition.
7392*/
7393typedef struct VdbeFunc VdbeFunc;
7394typedef struct Mem Mem;
7395typedef struct SubProgram SubProgram;
7396
7397/*
7398** A single instruction of the virtual machine has an opcode
7399** and as many as three operands.  The instruction is recorded
7400** as an instance of the following structure:
7401*/
7402struct VdbeOp {
7403  u8 opcode;          /* What operation to perform */
7404  signed char p4type; /* One of the P4_xxx constants for p4 */
7405  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7406  u8 p5;              /* Fifth parameter is an unsigned character */
7407  int p1;             /* First operand */
7408  int p2;             /* Second parameter (often the jump destination) */
7409  int p3;             /* The third parameter */
7410  union {             /* fourth parameter */
7411    int i;                 /* Integer value if p4type==P4_INT32 */
7412    void *p;               /* Generic pointer */
7413    char *z;               /* Pointer to data for string (char array) types */
7414    i64 *pI64;             /* Used when p4type is P4_INT64 */
7415    double *pReal;         /* Used when p4type is P4_REAL */
7416    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7417    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7418    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7419    Mem *pMem;             /* Used when p4type is P4_MEM */
7420    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7421    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7422    int *ai;               /* Used when p4type is P4_INTARRAY */
7423    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7424  } p4;
7425#ifdef SQLITE_DEBUG
7426  char *zComment;          /* Comment to improve readability */
7427#endif
7428#ifdef VDBE_PROFILE
7429  int cnt;                 /* Number of times this instruction was executed */
7430  u64 cycles;              /* Total time spent executing this instruction */
7431#endif
7432};
7433typedef struct VdbeOp VdbeOp;
7434
7435
7436/*
7437** A sub-routine used to implement a trigger program.
7438*/
7439struct SubProgram {
7440  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7441  int nOp;                      /* Elements in aOp[] */
7442  int nMem;                     /* Number of memory cells required */
7443  int nCsr;                     /* Number of cursors required */
7444  void *token;                  /* id that may be used to recursive triggers */
7445  SubProgram *pNext;            /* Next sub-program already visited */
7446};
7447
7448/*
7449** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7450** it takes up less space.
7451*/
7452struct VdbeOpList {
7453  u8 opcode;          /* What operation to perform */
7454  signed char p1;     /* First operand */
7455  signed char p2;     /* Second parameter (often the jump destination) */
7456  signed char p3;     /* Third parameter */
7457};
7458typedef struct VdbeOpList VdbeOpList;
7459
7460/*
7461** Allowed values of VdbeOp.p4type
7462*/
7463#define P4_NOTUSED    0   /* The P4 parameter is not used */
7464#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7465#define P4_STATIC   (-2)  /* Pointer to a static string */
7466#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7467#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7468#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7469#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7470#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7471#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7472#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7473#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7474#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7475#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7476#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7477#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7478#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7479
7480/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7481** is made.  That copy is freed when the Vdbe is finalized.  But if the
7482** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7483** gets freed when the Vdbe is finalized so it still should be obtained
7484** from a single sqliteMalloc().  But no copy is made and the calling
7485** function should *not* try to free the KeyInfo.
7486*/
7487#define P4_KEYINFO_HANDOFF (-16)
7488#define P4_KEYINFO_STATIC  (-17)
7489
7490/*
7491** The Vdbe.aColName array contains 5n Mem structures, where n is the
7492** number of columns of data returned by the statement.
7493*/
7494#define COLNAME_NAME     0
7495#define COLNAME_DECLTYPE 1
7496#define COLNAME_DATABASE 2
7497#define COLNAME_TABLE    3
7498#define COLNAME_COLUMN   4
7499#ifdef SQLITE_ENABLE_COLUMN_METADATA
7500# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7501#else
7502# ifdef SQLITE_OMIT_DECLTYPE
7503#   define COLNAME_N      1      /* Store only the name */
7504# else
7505#   define COLNAME_N      2      /* Store the name and decltype */
7506# endif
7507#endif
7508
7509/*
7510** The following macro converts a relative address in the p2 field
7511** of a VdbeOp structure into a negative number so that
7512** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7513** the macro again restores the address.
7514*/
7515#define ADDR(X)  (-1-(X))
7516
7517/*
7518** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7519** header file that defines a number for each opcode used by the VDBE.
7520*/
7521/************** Include opcodes.h in the middle of vdbe.h ********************/
7522/************** Begin file opcodes.h *****************************************/
7523/* Automatically generated.  Do not edit */
7524/* See the mkopcodeh.awk script for details */
7525#define OP_Goto                                 1
7526#define OP_Gosub                                2
7527#define OP_Return                               3
7528#define OP_Yield                                4
7529#define OP_HaltIfNull                           5
7530#define OP_Halt                                 6
7531#define OP_Integer                              7
7532#define OP_Int64                                8
7533#define OP_Real                               130   /* same as TK_FLOAT    */
7534#define OP_String8                             94   /* same as TK_STRING   */
7535#define OP_String                               9
7536#define OP_Null                                10
7537#define OP_Blob                                11
7538#define OP_Variable                            12
7539#define OP_Move                                13
7540#define OP_Copy                                14
7541#define OP_SCopy                               15
7542#define OP_ResultRow                           16
7543#define OP_Concat                              91   /* same as TK_CONCAT   */
7544#define OP_Add                                 86   /* same as TK_PLUS     */
7545#define OP_Subtract                            87   /* same as TK_MINUS    */
7546#define OP_Multiply                            88   /* same as TK_STAR     */
7547#define OP_Divide                              89   /* same as TK_SLASH    */
7548#define OP_Remainder                           90   /* same as TK_REM      */
7549#define OP_CollSeq                             17
7550#define OP_Function                            18
7551#define OP_BitAnd                              82   /* same as TK_BITAND   */
7552#define OP_BitOr                               83   /* same as TK_BITOR    */
7553#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7554#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7555#define OP_AddImm                              20
7556#define OP_MustBeInt                           21
7557#define OP_RealAffinity                        22
7558#define OP_ToText                             141   /* same as TK_TO_TEXT  */
7559#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7560#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7561#define OP_ToInt                              144   /* same as TK_TO_INT   */
7562#define OP_ToReal                             145   /* same as TK_TO_REAL  */
7563#define OP_Eq                                  76   /* same as TK_EQ       */
7564#define OP_Ne                                  75   /* same as TK_NE       */
7565#define OP_Lt                                  79   /* same as TK_LT       */
7566#define OP_Le                                  78   /* same as TK_LE       */
7567#define OP_Gt                                  77   /* same as TK_GT       */
7568#define OP_Ge                                  80   /* same as TK_GE       */
7569#define OP_Permutation                         23
7570#define OP_Compare                             24
7571#define OP_Jump                                25
7572#define OP_And                                 69   /* same as TK_AND      */
7573#define OP_Or                                  68   /* same as TK_OR       */
7574#define OP_Not                                 19   /* same as TK_NOT      */
7575#define OP_BitNot                              93   /* same as TK_BITNOT   */
7576#define OP_If                                  26
7577#define OP_IfNot                               27
7578#define OP_IsNull                              73   /* same as TK_ISNULL   */
7579#define OP_NotNull                             74   /* same as TK_NOTNULL  */
7580#define OP_Column                              28
7581#define OP_Affinity                            29
7582#define OP_MakeRecord                          30
7583#define OP_Count                               31
7584#define OP_Savepoint                           32
7585#define OP_AutoCommit                          33
7586#define OP_Transaction                         34
7587#define OP_ReadCookie                          35
7588#define OP_SetCookie                           36
7589#define OP_VerifyCookie                        37
7590#define OP_OpenRead                            38
7591#define OP_OpenWrite                           39
7592#define OP_OpenAutoindex                       40
7593#define OP_OpenEphemeral                       41
7594#define OP_OpenPseudo                          42
7595#define OP_Close                               43
7596#define OP_SeekLt                              44
7597#define OP_SeekLe                              45
7598#define OP_SeekGe                              46
7599#define OP_SeekGt                              47
7600#define OP_Seek                                48
7601#define OP_NotFound                            49
7602#define OP_Found                               50
7603#define OP_IsUnique                            51
7604#define OP_NotExists                           52
7605#define OP_Sequence                            53
7606#define OP_NewRowid                            54
7607#define OP_Insert                              55
7608#define OP_InsertInt                           56
7609#define OP_Delete                              57
7610#define OP_ResetCount                          58
7611#define OP_RowKey                              59
7612#define OP_RowData                             60
7613#define OP_Rowid                               61
7614#define OP_NullRow                             62
7615#define OP_Last                                63
7616#define OP_Sort                                64
7617#define OP_Rewind                              65
7618#define OP_Prev                                66
7619#define OP_Next                                67
7620#define OP_IdxInsert                           70
7621#define OP_IdxDelete                           71
7622#define OP_IdxRowid                            72
7623#define OP_IdxLT                               81
7624#define OP_IdxGE                               92
7625#define OP_Destroy                             95
7626#define OP_Clear                               96
7627#define OP_CreateIndex                         97
7628#define OP_CreateTable                         98
7629#define OP_ParseSchema                         99
7630#define OP_LoadAnalysis                       100
7631#define OP_DropTable                          101
7632#define OP_DropIndex                          102
7633#define OP_DropTrigger                        103
7634#define OP_IntegrityCk                        104
7635#define OP_RowSetAdd                          105
7636#define OP_RowSetRead                         106
7637#define OP_RowSetTest                         107
7638#define OP_Program                            108
7639#define OP_Param                              109
7640#define OP_FkCounter                          110
7641#define OP_FkIfZero                           111
7642#define OP_MemMax                             112
7643#define OP_IfPos                              113
7644#define OP_IfNeg                              114
7645#define OP_IfZero                             115
7646#define OP_AggStep                            116
7647#define OP_AggFinal                           117
7648#define OP_Checkpoint                         118
7649#define OP_JournalMode                        119
7650#define OP_Vacuum                             120
7651#define OP_IncrVacuum                         121
7652#define OP_Expire                             122
7653#define OP_TableLock                          123
7654#define OP_VBegin                             124
7655#define OP_VCreate                            125
7656#define OP_VDestroy                           126
7657#define OP_VOpen                              127
7658#define OP_VFilter                            128
7659#define OP_VColumn                            129
7660#define OP_VNext                              131
7661#define OP_VRename                            132
7662#define OP_VUpdate                            133
7663#define OP_Pagecount                          134
7664#define OP_Trace                              135
7665#define OP_Noop                               136
7666#define OP_Explain                            137
7667
7668/* The following opcode values are never used */
7669#define OP_NotUsed_138                        138
7670#define OP_NotUsed_139                        139
7671#define OP_NotUsed_140                        140
7672
7673
7674/* Properties such as "out2" or "jump" that are specified in
7675** comments following the "case" for each opcode in the vdbe.c
7676** are encoded into bitvectors as follows:
7677*/
7678#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7679#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7680#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7681#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7682#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7683#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7684#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7685#define OPFLG_INITIALIZER {\
7686/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7687/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7688/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7689/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7690/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7691/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7692/*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7693/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7694/*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
7695/*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7696/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7697/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
7698/*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
7699/* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
7700/* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7701/* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7702/* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x00,\
7703/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7704/* 144 */ 0x04, 0x04,}
7705
7706/************** End of opcodes.h *********************************************/
7707/************** Continuing where we left off in vdbe.h ***********************/
7708
7709/*
7710** Prototypes for the VDBE interface.  See comments on the implementation
7711** for a description of what each of these routines does.
7712*/
7713SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7714SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7715SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7716SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7717SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7718SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7719SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7720SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7721SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7722SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7723SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7724SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7725SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7726SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7727SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7728SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7729SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7730SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7731SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7732SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7733SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
7734SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7735SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7736SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7737SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7738#ifdef SQLITE_DEBUG
7739SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7740SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7741#endif
7742SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7743SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7744SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7745SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7746SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7747SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7748SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7749SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7750SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7751SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7752SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7753#ifndef SQLITE_OMIT_TRACE
7754SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7755#endif
7756
7757SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7758SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7759SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7760
7761#ifndef SQLITE_OMIT_TRIGGER
7762SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
7763#endif
7764
7765
7766#ifndef NDEBUG
7767SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7768# define VdbeComment(X)  sqlite3VdbeComment X
7769SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7770# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7771#else
7772# define VdbeComment(X)
7773# define VdbeNoopComment(X)
7774#endif
7775
7776#endif
7777
7778/************** End of vdbe.h ************************************************/
7779/************** Continuing where we left off in sqliteInt.h ******************/
7780/************** Include pager.h in the middle of sqliteInt.h *****************/
7781/************** Begin file pager.h *******************************************/
7782/*
7783** 2001 September 15
7784**
7785** The author disclaims copyright to this source code.  In place of
7786** a legal notice, here is a blessing:
7787**
7788**    May you do good and not evil.
7789**    May you find forgiveness for yourself and forgive others.
7790**    May you share freely, never taking more than you give.
7791**
7792*************************************************************************
7793** This header file defines the interface that the sqlite page cache
7794** subsystem.  The page cache subsystem reads and writes a file a page
7795** at a time and provides a journal for rollback.
7796*/
7797
7798#ifndef _PAGER_H_
7799#define _PAGER_H_
7800
7801/*
7802** Default maximum size for persistent journal files. A negative
7803** value means no limit. This value may be overridden using the
7804** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7805*/
7806#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7807  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7808#endif
7809
7810/*
7811** The type used to represent a page number.  The first page in a file
7812** is called page 1.  0 is used to represent "not a page".
7813*/
7814typedef u32 Pgno;
7815
7816/*
7817** Each open file is managed by a separate instance of the "Pager" structure.
7818*/
7819typedef struct Pager Pager;
7820
7821/*
7822** Handle type for pages.
7823*/
7824typedef struct PgHdr DbPage;
7825
7826/*
7827** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7828** reserved for working around a windows/posix incompatibility). It is
7829** used in the journal to signify that the remainder of the journal file
7830** is devoted to storing a master journal name - there are no more pages to
7831** roll back. See comments for function writeMasterJournal() in pager.c
7832** for details.
7833*/
7834#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7835
7836/*
7837** Allowed values for the flags parameter to sqlite3PagerOpen().
7838**
7839** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7840*/
7841#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7842#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7843
7844/*
7845** Valid values for the second argument to sqlite3PagerLockingMode().
7846*/
7847#define PAGER_LOCKINGMODE_QUERY      -1
7848#define PAGER_LOCKINGMODE_NORMAL      0
7849#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7850
7851/*
7852** Numeric constants that encode the journalmode.
7853*/
7854#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
7855#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7856#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7857#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7858#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7859#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7860#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
7861
7862/*
7863** The remainder of this file contains the declarations of the functions
7864** that make up the Pager sub-system API. See source code comments for
7865** a detailed description of each routine.
7866*/
7867
7868/* Open and close a Pager connection. */
7869SQLITE_PRIVATE int sqlite3PagerOpen(
7870  sqlite3_vfs*,
7871  Pager **ppPager,
7872  const char*,
7873  int,
7874  int,
7875  int,
7876  void(*)(DbPage*)
7877);
7878SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7879SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7880
7881/* Functions used to configure a Pager object. */
7882SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7883SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
7884SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7885SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7886SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7887SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7888SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
7889SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
7890SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
7891SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7892SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7893
7894/* Functions used to obtain and release page references. */
7895SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7896#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7897SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7898SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7899SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7900
7901/* Operations on page references. */
7902SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7903SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7904SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7905SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7906SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7907SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7908
7909/* Functions used to manage pager transactions and savepoints. */
7910SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
7911SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7912SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7913SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
7914SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7915SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7916SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7917SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7918SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7919SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7920
7921SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
7922SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
7923SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
7924SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
7925SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
7926
7927/* Functions used to query pager state and configuration. */
7928SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7929SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7930SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
7931SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7932SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7933SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7934SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7935SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7936SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7937SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7938
7939/* Functions used to truncate the database file. */
7940SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7941
7942#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
7943SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
7944#endif
7945
7946/* Functions to support testing and debugging. */
7947#if !defined(NDEBUG) || defined(SQLITE_TEST)
7948SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7949SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7950#endif
7951#ifdef SQLITE_TEST
7952SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7953SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7954  void disable_simulated_io_errors(void);
7955  void enable_simulated_io_errors(void);
7956#else
7957# define disable_simulated_io_errors()
7958# define enable_simulated_io_errors()
7959#endif
7960
7961#endif /* _PAGER_H_ */
7962
7963/************** End of pager.h ***********************************************/
7964/************** Continuing where we left off in sqliteInt.h ******************/
7965/************** Include pcache.h in the middle of sqliteInt.h ****************/
7966/************** Begin file pcache.h ******************************************/
7967/*
7968** 2008 August 05
7969**
7970** The author disclaims copyright to this source code.  In place of
7971** a legal notice, here is a blessing:
7972**
7973**    May you do good and not evil.
7974**    May you find forgiveness for yourself and forgive others.
7975**    May you share freely, never taking more than you give.
7976**
7977*************************************************************************
7978** This header file defines the interface that the sqlite page cache
7979** subsystem.
7980*/
7981
7982#ifndef _PCACHE_H_
7983
7984typedef struct PgHdr PgHdr;
7985typedef struct PCache PCache;
7986
7987/*
7988** Every page in the cache is controlled by an instance of the following
7989** structure.
7990*/
7991struct PgHdr {
7992  void *pData;                   /* Content of this page */
7993  void *pExtra;                  /* Extra content */
7994  PgHdr *pDirty;                 /* Transient list of dirty pages */
7995  Pgno pgno;                     /* Page number for this page */
7996  Pager *pPager;                 /* The pager this page is part of */
7997#ifdef SQLITE_CHECK_PAGES
7998  u32 pageHash;                  /* Hash of page content */
7999#endif
8000  u16 flags;                     /* PGHDR flags defined below */
8001
8002  /**********************************************************************
8003  ** Elements above are public.  All that follows is private to pcache.c
8004  ** and should not be accessed by other modules.
8005  */
8006  i16 nRef;                      /* Number of users of this page */
8007  PCache *pCache;                /* Cache that owns this page */
8008
8009  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8010  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8011};
8012
8013/* Bit values for PgHdr.flags */
8014#define PGHDR_DIRTY             0x002  /* Page has changed */
8015#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8016                                       ** writing this page to the database */
8017#define PGHDR_NEED_READ         0x008  /* Content is unread */
8018#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8019#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8020
8021/* Initialize and shutdown the page cache subsystem */
8022SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8023SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8024
8025/* Page cache buffer management:
8026** These routines implement SQLITE_CONFIG_PAGECACHE.
8027*/
8028SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8029
8030/* Create a new pager cache.
8031** Under memory stress, invoke xStress to try to make pages clean.
8032** Only clean and unpinned pages can be reclaimed.
8033*/
8034SQLITE_PRIVATE void sqlite3PcacheOpen(
8035  int szPage,                    /* Size of every page */
8036  int szExtra,                   /* Extra space associated with each page */
8037  int bPurgeable,                /* True if pages are on backing store */
8038  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8039  void *pStress,                 /* Argument to xStress */
8040  PCache *pToInit                /* Preallocated space for the PCache */
8041);
8042
8043/* Modify the page-size after the cache has been created. */
8044SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8045
8046/* Return the size in bytes of a PCache object.  Used to preallocate
8047** storage space.
8048*/
8049SQLITE_PRIVATE int sqlite3PcacheSize(void);
8050
8051/* One release per successful fetch.  Page is pinned until released.
8052** Reference counted.
8053*/
8054SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8055SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8056
8057SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8058SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8059SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8060SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8061
8062/* Change a page number.  Used by incr-vacuum. */
8063SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8064
8065/* Remove all pages with pgno>x.  Reset the cache if x==0 */
8066SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8067
8068/* Get a list of all dirty pages in the cache, sorted by page number */
8069SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8070
8071/* Reset and close the cache object */
8072SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8073
8074/* Clear flags from pages of the page cache */
8075SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8076
8077/* Discard the contents of the cache */
8078SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8079
8080/* Return the total number of outstanding page references */
8081SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8082
8083/* Increment the reference count of an existing page */
8084SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8085
8086SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8087
8088/* Return the total number of pages stored in the cache */
8089SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8090
8091#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8092/* Iterate through all dirty pages currently stored in the cache. This
8093** interface is only available if SQLITE_CHECK_PAGES is defined when the
8094** library is built.
8095*/
8096SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8097#endif
8098
8099/* Set and get the suggested cache-size for the specified pager-cache.
8100**
8101** If no global maximum is configured, then the system attempts to limit
8102** the total number of pages cached by purgeable pager-caches to the sum
8103** of the suggested cache-sizes.
8104*/
8105SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8106#ifdef SQLITE_TEST
8107SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8108#endif
8109
8110#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8111/* Try to return memory used by the pcache module to the main memory heap */
8112SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8113#endif
8114
8115#ifdef SQLITE_TEST
8116SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8117#endif
8118
8119SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8120
8121#endif /* _PCACHE_H_ */
8122
8123/************** End of pcache.h **********************************************/
8124/************** Continuing where we left off in sqliteInt.h ******************/
8125
8126/************** Include os.h in the middle of sqliteInt.h ********************/
8127/************** Begin file os.h **********************************************/
8128/*
8129** 2001 September 16
8130**
8131** The author disclaims copyright to this source code.  In place of
8132** a legal notice, here is a blessing:
8133**
8134**    May you do good and not evil.
8135**    May you find forgiveness for yourself and forgive others.
8136**    May you share freely, never taking more than you give.
8137**
8138******************************************************************************
8139**
8140** This header file (together with is companion C source-code file
8141** "os.c") attempt to abstract the underlying operating system so that
8142** the SQLite library will work on both POSIX and windows systems.
8143**
8144** This header file is #include-ed by sqliteInt.h and thus ends up
8145** being included by every source file.
8146*/
8147#ifndef _SQLITE_OS_H_
8148#define _SQLITE_OS_H_
8149
8150/*
8151** Figure out if we are dealing with Unix, Windows, or some other
8152** operating system.  After the following block of preprocess macros,
8153** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
8154** will defined to either 1 or 0.  One of the four will be 1.  The other
8155** three will be 0.
8156*/
8157#if defined(SQLITE_OS_OTHER)
8158# if SQLITE_OS_OTHER==1
8159#   undef SQLITE_OS_UNIX
8160#   define SQLITE_OS_UNIX 0
8161#   undef SQLITE_OS_WIN
8162#   define SQLITE_OS_WIN 0
8163#   undef SQLITE_OS_OS2
8164#   define SQLITE_OS_OS2 0
8165# else
8166#   undef SQLITE_OS_OTHER
8167# endif
8168#endif
8169#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8170# define SQLITE_OS_OTHER 0
8171# ifndef SQLITE_OS_WIN
8172#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8173#     define SQLITE_OS_WIN 1
8174#     define SQLITE_OS_UNIX 0
8175#     define SQLITE_OS_OS2 0
8176#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8177#     define SQLITE_OS_WIN 0
8178#     define SQLITE_OS_UNIX 0
8179#     define SQLITE_OS_OS2 1
8180#   else
8181#     define SQLITE_OS_WIN 0
8182#     define SQLITE_OS_UNIX 1
8183#     define SQLITE_OS_OS2 0
8184#  endif
8185# else
8186#  define SQLITE_OS_UNIX 0
8187#  define SQLITE_OS_OS2 0
8188# endif
8189#else
8190# ifndef SQLITE_OS_WIN
8191#  define SQLITE_OS_WIN 0
8192# endif
8193#endif
8194
8195/*
8196** Determine if we are dealing with WindowsCE - which has a much
8197** reduced API.
8198*/
8199#if defined(_WIN32_WCE)
8200# define SQLITE_OS_WINCE 1
8201#else
8202# define SQLITE_OS_WINCE 0
8203#endif
8204
8205
8206/*
8207** Define the maximum size of a temporary filename
8208*/
8209#if SQLITE_OS_WIN
8210# include <windows.h>
8211# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8212#elif SQLITE_OS_OS2
8213# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8214#  include <os2safe.h> /* has to be included before os2.h for linking to work */
8215# endif
8216# define INCL_DOSDATETIME
8217# define INCL_DOSFILEMGR
8218# define INCL_DOSERRORS
8219# define INCL_DOSMISC
8220# define INCL_DOSPROCESS
8221# define INCL_DOSMODULEMGR
8222# define INCL_DOSSEMAPHORES
8223# include <os2.h>
8224# include <uconv.h>
8225# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8226#else
8227# define SQLITE_TEMPNAME_SIZE 200
8228#endif
8229
8230/* If the SET_FULLSYNC macro is not defined above, then make it
8231** a no-op
8232*/
8233#ifndef SET_FULLSYNC
8234# define SET_FULLSYNC(x,y)
8235#endif
8236
8237/*
8238** The default size of a disk sector
8239*/
8240#ifndef SQLITE_DEFAULT_SECTOR_SIZE
8241# define SQLITE_DEFAULT_SECTOR_SIZE 512
8242#endif
8243
8244/*
8245** Temporary files are named starting with this prefix followed by 16 random
8246** alphanumeric characters, and no file extension. They are stored in the
8247** OS's standard temporary file directory, and are deleted prior to exit.
8248** If sqlite is being embedded in another program, you may wish to change the
8249** prefix to reflect your program's name, so that if your program exits
8250** prematurely, old temporary files can be easily identified. This can be done
8251** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8252**
8253** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8254** Mcafee started using SQLite in their anti-virus product and it
8255** started putting files with the "sqlite" name in the c:/temp folder.
8256** This annoyed many windows users.  Those users would then do a
8257** Google search for "sqlite", find the telephone numbers of the
8258** developers and call to wake them up at night and complain.
8259** For this reason, the default name prefix is changed to be "sqlite"
8260** spelled backwards.  So the temp files are still identified, but
8261** anybody smart enough to figure out the code is also likely smart
8262** enough to know that calling the developer will not help get rid
8263** of the file.
8264*/
8265#ifndef SQLITE_TEMP_FILE_PREFIX
8266# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8267#endif
8268
8269/*
8270** The following values may be passed as the second argument to
8271** sqlite3OsLock(). The various locks exhibit the following semantics:
8272**
8273** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8274** RESERVED:  A single process may hold a RESERVED lock on a file at
8275**            any time. Other processes may hold and obtain new SHARED locks.
8276** PENDING:   A single process may hold a PENDING lock on a file at
8277**            any one time. Existing SHARED locks may persist, but no new
8278**            SHARED locks may be obtained by other processes.
8279** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8280**
8281** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8282** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8283** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8284** sqlite3OsLock().
8285*/
8286#define NO_LOCK         0
8287#define SHARED_LOCK     1
8288#define RESERVED_LOCK   2
8289#define PENDING_LOCK    3
8290#define EXCLUSIVE_LOCK  4
8291
8292/*
8293** File Locking Notes:  (Mostly about windows but also some info for Unix)
8294**
8295** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8296** those functions are not available.  So we use only LockFile() and
8297** UnlockFile().
8298**
8299** LockFile() prevents not just writing but also reading by other processes.
8300** A SHARED_LOCK is obtained by locking a single randomly-chosen
8301** byte out of a specific range of bytes. The lock byte is obtained at
8302** random so two separate readers can probably access the file at the
8303** same time, unless they are unlucky and choose the same lock byte.
8304** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8305** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8306** a single byte of the file that is designated as the reserved lock byte.
8307** A PENDING_LOCK is obtained by locking a designated byte different from
8308** the RESERVED_LOCK byte.
8309**
8310** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8311** which means we can use reader/writer locks.  When reader/writer locks
8312** are used, the lock is placed on the same range of bytes that is used
8313** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8314** will support two or more Win95 readers or two or more WinNT readers.
8315** But a single Win95 reader will lock out all WinNT readers and a single
8316** WinNT reader will lock out all other Win95 readers.
8317**
8318** The following #defines specify the range of bytes used for locking.
8319** SHARED_SIZE is the number of bytes available in the pool from which
8320** a random byte is selected for a shared lock.  The pool of bytes for
8321** shared locks begins at SHARED_FIRST.
8322**
8323** The same locking strategy and
8324** byte ranges are used for Unix.  This leaves open the possiblity of having
8325** clients on win95, winNT, and unix all talking to the same shared file
8326** and all locking correctly.  To do so would require that samba (or whatever
8327** tool is being used for file sharing) implements locks correctly between
8328** windows and unix.  I'm guessing that isn't likely to happen, but by
8329** using the same locking range we are at least open to the possibility.
8330**
8331** Locking in windows is manditory.  For this reason, we cannot store
8332** actual data in the bytes used for locking.  The pager never allocates
8333** the pages involved in locking therefore.  SHARED_SIZE is selected so
8334** that all locks will fit on a single page even at the minimum page size.
8335** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8336** is set high so that we don't have to allocate an unused page except
8337** for very large databases.  But one should test the page skipping logic
8338** by setting PENDING_BYTE low and running the entire regression suite.
8339**
8340** Changing the value of PENDING_BYTE results in a subtly incompatible
8341** file format.  Depending on how it is changed, you might not notice
8342** the incompatibility right away, even running a full regression test.
8343** The default location of PENDING_BYTE is the first byte past the
8344** 1GB boundary.
8345**
8346*/
8347#ifdef SQLITE_OMIT_WSD
8348# define PENDING_BYTE     (0x40000000)
8349#else
8350# define PENDING_BYTE      sqlite3PendingByte
8351#endif
8352#define RESERVED_BYTE     (PENDING_BYTE+1)
8353#define SHARED_FIRST      (PENDING_BYTE+2)
8354#define SHARED_SIZE       510
8355
8356/*
8357** Wrapper around OS specific sqlite3_os_init() function.
8358*/
8359SQLITE_PRIVATE int sqlite3OsInit(void);
8360
8361/*
8362** Functions for accessing sqlite3_file methods
8363*/
8364SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8365SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8366SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8367SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8368SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8369SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8370SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8371SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8372SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8373SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8374#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8375SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8376SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8377SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8378SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8379SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8380SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8381
8382/*
8383** Functions for accessing sqlite3_vfs methods
8384*/
8385SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8386SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8387SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8388SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8389#ifndef SQLITE_OMIT_LOAD_EXTENSION
8390SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8391SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8392SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8393SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8394#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8395SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8396SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8397SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8398
8399/*
8400** Convenience functions for opening and closing files using
8401** sqlite3_malloc() to obtain space for the file-handle structure.
8402*/
8403SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8404SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8405
8406#endif /* _SQLITE_OS_H_ */
8407
8408/************** End of os.h **************************************************/
8409/************** Continuing where we left off in sqliteInt.h ******************/
8410/************** Include mutex.h in the middle of sqliteInt.h *****************/
8411/************** Begin file mutex.h *******************************************/
8412/*
8413** 2007 August 28
8414**
8415** The author disclaims copyright to this source code.  In place of
8416** a legal notice, here is a blessing:
8417**
8418**    May you do good and not evil.
8419**    May you find forgiveness for yourself and forgive others.
8420**    May you share freely, never taking more than you give.
8421**
8422*************************************************************************
8423**
8424** This file contains the common header for all mutex implementations.
8425** The sqliteInt.h header #includes this file so that it is available
8426** to all source files.  We break it out in an effort to keep the code
8427** better organized.
8428**
8429** NOTE:  source files should *not* #include this header file directly.
8430** Source files should #include the sqliteInt.h file and let that file
8431** include this one indirectly.
8432*/
8433
8434
8435/*
8436** Figure out what version of the code to use.  The choices are
8437**
8438**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8439**                             mutexes implemention cannot be overridden
8440**                             at start-time.
8441**
8442**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8443**                             mutual exclusion is provided.  But this
8444**                             implementation can be overridden at
8445**                             start-time.
8446**
8447**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8448**
8449**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8450**
8451**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8452*/
8453#if !SQLITE_THREADSAFE
8454# define SQLITE_MUTEX_OMIT
8455#endif
8456#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8457#  if SQLITE_OS_UNIX
8458#    define SQLITE_MUTEX_PTHREADS
8459#  elif SQLITE_OS_WIN
8460#    define SQLITE_MUTEX_W32
8461#  elif SQLITE_OS_OS2
8462#    define SQLITE_MUTEX_OS2
8463#  else
8464#    define SQLITE_MUTEX_NOOP
8465#  endif
8466#endif
8467
8468#ifdef SQLITE_MUTEX_OMIT
8469/*
8470** If this is a no-op implementation, implement everything as macros.
8471*/
8472#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8473#define sqlite3_mutex_free(X)
8474#define sqlite3_mutex_enter(X)
8475#define sqlite3_mutex_try(X)      SQLITE_OK
8476#define sqlite3_mutex_leave(X)
8477#define sqlite3_mutex_held(X)     1
8478#define sqlite3_mutex_notheld(X)  1
8479#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8480#define sqlite3MutexInit()        SQLITE_OK
8481#define sqlite3MutexEnd()
8482#endif /* defined(SQLITE_MUTEX_OMIT) */
8483
8484/************** End of mutex.h ***********************************************/
8485/************** Continuing where we left off in sqliteInt.h ******************/
8486
8487
8488/*
8489** Each database file to be accessed by the system is an instance
8490** of the following structure.  There are normally two of these structures
8491** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8492** aDb[1] is the database file used to hold temporary tables.  Additional
8493** databases may be attached.
8494*/
8495struct Db {
8496  char *zName;         /* Name of this database */
8497  Btree *pBt;          /* The B*Tree structure for this database file */
8498  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8499  u8 safety_level;     /* How aggressive at syncing data to disk */
8500  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8501};
8502
8503/*
8504** An instance of the following structure stores a database schema.
8505*/
8506struct Schema {
8507  int schema_cookie;   /* Database schema version number for this file */
8508  Hash tblHash;        /* All tables indexed by name */
8509  Hash idxHash;        /* All (named) indices indexed by name */
8510  Hash trigHash;       /* All triggers indexed by name */
8511  Hash fkeyHash;       /* All foreign keys by referenced table name */
8512  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8513  u8 file_format;      /* Schema format version for this file */
8514  u8 enc;              /* Text encoding used by this database */
8515  u16 flags;           /* Flags associated with this schema */
8516  int cache_size;      /* Number of pages to use in the cache */
8517};
8518
8519/*
8520** These macros can be used to test, set, or clear bits in the
8521** Db.pSchema->flags field.
8522*/
8523#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8524#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8525#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8526#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8527
8528/*
8529** Allowed values for the DB.pSchema->flags field.
8530**
8531** The DB_SchemaLoaded flag is set after the database schema has been
8532** read into internal hash tables.
8533**
8534** DB_UnresetViews means that one or more views have column names that
8535** have been filled out.  If the schema changes, these column names might
8536** changes and so the view will need to be reset.
8537*/
8538#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8539#define DB_UnresetViews    0x0002  /* Some views have defined column names */
8540#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8541
8542/*
8543** The number of different kinds of things that can be limited
8544** using the sqlite3_limit() interface.
8545*/
8546#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8547
8548/*
8549** Lookaside malloc is a set of fixed-size buffers that can be used
8550** to satisfy small transient memory allocation requests for objects
8551** associated with a particular database connection.  The use of
8552** lookaside malloc provides a significant performance enhancement
8553** (approx 10%) by avoiding numerous malloc/free requests while parsing
8554** SQL statements.
8555**
8556** The Lookaside structure holds configuration information about the
8557** lookaside malloc subsystem.  Each available memory allocation in
8558** the lookaside subsystem is stored on a linked list of LookasideSlot
8559** objects.
8560**
8561** Lookaside allocations are only allowed for objects that are associated
8562** with a particular database connection.  Hence, schema information cannot
8563** be stored in lookaside because in shared cache mode the schema information
8564** is shared by multiple database connections.  Therefore, while parsing
8565** schema information, the Lookaside.bEnabled flag is cleared so that
8566** lookaside allocations are not used to construct the schema objects.
8567*/
8568struct Lookaside {
8569  u16 sz;                 /* Size of each buffer in bytes */
8570  u8 bEnabled;            /* False to disable new lookaside allocations */
8571  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8572  int nOut;               /* Number of buffers currently checked out */
8573  int mxOut;              /* Highwater mark for nOut */
8574  LookasideSlot *pFree;   /* List of available buffers */
8575  void *pStart;           /* First byte of available memory space */
8576  void *pEnd;             /* First byte past end of available space */
8577};
8578struct LookasideSlot {
8579  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8580};
8581
8582/*
8583** A hash table for function definitions.
8584**
8585** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8586** Collisions are on the FuncDef.pHash chain.
8587*/
8588struct FuncDefHash {
8589  FuncDef *a[23];       /* Hash table for functions */
8590};
8591
8592/*
8593** Each database connection is an instance of the following structure.
8594**
8595** The sqlite.lastRowid records the last insert rowid generated by an
8596** insert statement.  Inserts on views do not affect its value.  Each
8597** trigger has its own context, so that lastRowid can be updated inside
8598** triggers as usual.  The previous value will be restored once the trigger
8599** exits.  Upon entering a before or instead of trigger, lastRowid is no
8600** longer (since after version 2.8.12) reset to -1.
8601**
8602** The sqlite.nChange does not count changes within triggers and keeps no
8603** context.  It is reset at start of sqlite3_exec.
8604** The sqlite.lsChange represents the number of changes made by the last
8605** insert, update, or delete statement.  It remains constant throughout the
8606** length of a statement and is then updated by OP_SetCounts.  It keeps a
8607** context stack just like lastRowid so that the count of changes
8608** within a trigger is not seen outside the trigger.  Changes to views do not
8609** affect the value of lsChange.
8610** The sqlite.csChange keeps track of the number of current changes (since
8611** the last statement) and is used to update sqlite_lsChange.
8612**
8613** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8614** store the most recent error code and, if applicable, string. The
8615** internal function sqlite3Error() is used to set these variables
8616** consistently.
8617*/
8618struct sqlite3 {
8619  sqlite3_vfs *pVfs;            /* OS Interface */
8620  int nDb;                      /* Number of backends currently in use */
8621  Db *aDb;                      /* All backends */
8622  int flags;                    /* Miscellaneous flags. See below */
8623  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8624  int errCode;                  /* Most recent error code (SQLITE_*) */
8625  int errMask;                  /* & result codes with this before returning */
8626  u8 autoCommit;                /* The auto-commit flag. */
8627  u8 temp_store;                /* 1: file 2: memory 0: default */
8628  u8 mallocFailed;              /* True if we have seen a malloc failure */
8629  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8630  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8631  u8 suppressErr;               /* Do not issue error messages if true */
8632  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8633  int nTable;                   /* Number of tables in the database */
8634  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8635  i64 lastRowid;                /* ROWID of most recent insert (see above) */
8636  u32 magic;                    /* Magic number for detect library misuse */
8637  int nChange;                  /* Value returned by sqlite3_changes() */
8638  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8639  sqlite3_mutex *mutex;         /* Connection mutex */
8640  int aLimit[SQLITE_N_LIMIT];   /* Limits */
8641  struct sqlite3InitInfo {      /* Information used during initialization */
8642    int iDb;                    /* When back is being initialized */
8643    int newTnum;                /* Rootpage of table being initialized */
8644    u8 busy;                    /* TRUE if currently initializing */
8645    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8646  } init;
8647  int nExtension;               /* Number of loaded extensions */
8648  void **aExtension;            /* Array of shared library handles */
8649  struct Vdbe *pVdbe;           /* List of active virtual machines */
8650  int activeVdbeCnt;            /* Number of VDBEs currently executing */
8651  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8652  void (*xTrace)(void*,const char*);        /* Trace function */
8653  void *pTraceArg;                          /* Argument to the trace function */
8654  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8655  void *pProfileArg;                        /* Argument to profile function */
8656  void *pCommitArg;                 /* Argument to xCommitCallback() */
8657  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8658  void *pRollbackArg;               /* Argument to xRollbackCallback() */
8659  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8660  void *pUpdateArg;
8661  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8662#ifndef SQLITE_OMIT_WAL
8663  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8664  void *pWalArg;
8665#endif
8666  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8667  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8668  void *pCollNeededArg;
8669  sqlite3_value *pErr;          /* Most recent error message */
8670  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8671  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8672  union {
8673    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8674    double notUsed1;            /* Spacer */
8675  } u1;
8676  Lookaside lookaside;          /* Lookaside malloc configuration */
8677#ifndef SQLITE_OMIT_AUTHORIZATION
8678  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8679                                /* Access authorization function */
8680  void *pAuthArg;               /* 1st argument to the access auth function */
8681#endif
8682#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8683  int (*xProgress)(void *);     /* The progress callback */
8684  void *pProgressArg;           /* Argument to the progress callback */
8685  int nProgressOps;             /* Number of opcodes for progress callback */
8686#endif
8687#ifndef SQLITE_OMIT_VIRTUALTABLE
8688  Hash aModule;                 /* populated by sqlite3_create_module() */
8689  Table *pVTab;                 /* vtab with active Connect/Create method */
8690  VTable **aVTrans;             /* Virtual tables with open transactions */
8691  int nVTrans;                  /* Allocated size of aVTrans */
8692  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8693#endif
8694  FuncDefHash aFunc;            /* Hash table of connection functions */
8695  Hash aCollSeq;                /* All collating sequences */
8696  BusyHandler busyHandler;      /* Busy callback */
8697  int busyTimeout;              /* Busy handler timeout, in msec */
8698  Db aDbStatic[2];              /* Static space for the 2 default backends */
8699  Savepoint *pSavepoint;        /* List of active savepoints */
8700  int nSavepoint;               /* Number of non-transaction savepoints */
8701  int nStatement;               /* Number of nested statement-transactions  */
8702  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8703  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8704  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
8705
8706#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8707  /* The following variables are all protected by the STATIC_MASTER
8708  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
8709  **
8710  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8711  ** unlock so that it can proceed.
8712  **
8713  ** When X.pBlockingConnection==Y, that means that something that X tried
8714  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8715  ** held by Y.
8716  */
8717  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8718  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8719  void *pUnlockArg;                     /* Argument to xUnlockNotify */
8720  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8721  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8722#endif
8723};
8724
8725/*
8726** A macro to discover the encoding of a database.
8727*/
8728#define ENC(db) ((db)->aDb[0].pSchema->enc)
8729
8730/*
8731** Possible values for the sqlite3.flags.
8732*/
8733#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8734#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8735#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8736#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8737#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8738                                          /*   DELETE, or UPDATE and return */
8739                                          /*   the count using a callback. */
8740#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8741                                          /*   result set is empty */
8742#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8743#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8744#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8745#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
8746                                          ** accessing read-only databases */
8747#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8748#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8749#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8750#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8751#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8752#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8753#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8754#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8755#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8756#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
8757#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
8758
8759/*
8760** Bits of the sqlite3.flags field that are used by the
8761** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8762** These must be the low-order bits of the flags field.
8763*/
8764#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8765#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8766#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8767#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8768#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8769#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
8770#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
8771
8772/*
8773** Possible values for the sqlite.magic field.
8774** The numbers are obtained at random and have no special meaning, other
8775** than being distinct from one another.
8776*/
8777#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8778#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8779#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8780#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8781#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8782
8783/*
8784** Each SQL function is defined by an instance of the following
8785** structure.  A pointer to this structure is stored in the sqlite.aFunc
8786** hash table.  When multiple functions have the same name, the hash table
8787** points to a linked list of these structures.
8788*/
8789struct FuncDef {
8790  i16 nArg;            /* Number of arguments.  -1 means unlimited */
8791  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8792  u8 flags;            /* Some combination of SQLITE_FUNC_* */
8793  void *pUserData;     /* User data parameter */
8794  FuncDef *pNext;      /* Next function with same name */
8795  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8796  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8797  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8798  char *zName;         /* SQL name of the function. */
8799  FuncDef *pHash;      /* Next with a different name but the same hash */
8800};
8801
8802/*
8803** Possible values for FuncDef.flags
8804*/
8805#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8806#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8807#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8808#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8809#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8810#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8811#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8812
8813/*
8814** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8815** used to create the initializers for the FuncDef structures.
8816**
8817**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8818**     Used to create a scalar function definition of a function zName
8819**     implemented by C function xFunc that accepts nArg arguments. The
8820**     value passed as iArg is cast to a (void*) and made available
8821**     as the user-data (sqlite3_user_data()) for the function. If
8822**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8823**
8824**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8825**     Used to create an aggregate function definition implemented by
8826**     the C functions xStep and xFinal. The first four parameters
8827**     are interpreted in the same way as the first 4 parameters to
8828**     FUNCTION().
8829**
8830**   LIKEFUNC(zName, nArg, pArg, flags)
8831**     Used to create a scalar function definition of a function zName
8832**     that accepts nArg arguments and is implemented by a call to C
8833**     function likeFunc. Argument pArg is cast to a (void *) and made
8834**     available as the function user-data (sqlite3_user_data()). The
8835**     FuncDef.flags variable is set to the value passed as the flags
8836**     parameter.
8837*/
8838#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8839  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8840   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8841#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8842  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8843   pArg, 0, xFunc, 0, 0, #zName, 0}
8844#define LIKEFUNC(zName, nArg, arg, flags) \
8845  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8846#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8847  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8848   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8849
8850/*
8851** All current savepoints are stored in a linked list starting at
8852** sqlite3.pSavepoint. The first element in the list is the most recently
8853** opened savepoint. Savepoints are added to the list by the vdbe
8854** OP_Savepoint instruction.
8855*/
8856struct Savepoint {
8857  char *zName;                        /* Savepoint name (nul-terminated) */
8858  i64 nDeferredCons;                  /* Number of deferred fk violations */
8859  Savepoint *pNext;                   /* Parent savepoint (if any) */
8860};
8861
8862/*
8863** The following are used as the second parameter to sqlite3Savepoint(),
8864** and as the P1 argument to the OP_Savepoint instruction.
8865*/
8866#define SAVEPOINT_BEGIN      0
8867#define SAVEPOINT_RELEASE    1
8868#define SAVEPOINT_ROLLBACK   2
8869
8870
8871/*
8872** Each SQLite module (virtual table definition) is defined by an
8873** instance of the following structure, stored in the sqlite3.aModule
8874** hash table.
8875*/
8876struct Module {
8877  const sqlite3_module *pModule;       /* Callback pointers */
8878  const char *zName;                   /* Name passed to create_module() */
8879  void *pAux;                          /* pAux passed to create_module() */
8880  void (*xDestroy)(void *);            /* Module destructor function */
8881};
8882
8883/*
8884** information about each column of an SQL table is held in an instance
8885** of this structure.
8886*/
8887struct Column {
8888  char *zName;     /* Name of this column */
8889  Expr *pDflt;     /* Default value of this column */
8890  char *zDflt;     /* Original text of the default value */
8891  char *zType;     /* Data type for this column */
8892  char *zColl;     /* Collating sequence.  If NULL, use the default */
8893  u8 notNull;      /* True if there is a NOT NULL constraint */
8894  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8895  char affinity;   /* One of the SQLITE_AFF_... values */
8896#ifndef SQLITE_OMIT_VIRTUALTABLE
8897  u8 isHidden;     /* True if this column is 'hidden' */
8898#endif
8899};
8900
8901/*
8902** A "Collating Sequence" is defined by an instance of the following
8903** structure. Conceptually, a collating sequence consists of a name and
8904** a comparison routine that defines the order of that sequence.
8905**
8906** There may two separate implementations of the collation function, one
8907** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8908** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8909** native byte order. When a collation sequence is invoked, SQLite selects
8910** the version that will require the least expensive encoding
8911** translations, if any.
8912**
8913** The CollSeq.pUser member variable is an extra parameter that passed in
8914** as the first argument to the UTF-8 comparison function, xCmp.
8915** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8916** xCmp16.
8917**
8918** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8919** collating sequence is undefined.  Indices built on an undefined
8920** collating sequence may not be read or written.
8921*/
8922struct CollSeq {
8923  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8924  u8 enc;               /* Text encoding handled by xCmp() */
8925  u8 type;              /* One of the SQLITE_COLL_... values below */
8926  void *pUser;          /* First argument to xCmp() */
8927  int (*xCmp)(void*,int, const void*, int, const void*);
8928  void (*xDel)(void*);  /* Destructor for pUser */
8929};
8930
8931/*
8932** Allowed values of CollSeq.type:
8933*/
8934#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8935#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8936#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8937#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8938
8939/*
8940** A sort order can be either ASC or DESC.
8941*/
8942#define SQLITE_SO_ASC       0  /* Sort in ascending order */
8943#define SQLITE_SO_DESC      1  /* Sort in ascending order */
8944
8945/*
8946** Column affinity types.
8947**
8948** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8949** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8950** the speed a little by numbering the values consecutively.
8951**
8952** But rather than start with 0 or 1, we begin with 'a'.  That way,
8953** when multiple affinity types are concatenated into a string and
8954** used as the P4 operand, they will be more readable.
8955**
8956** Note also that the numeric types are grouped together so that testing
8957** for a numeric type is a single comparison.
8958*/
8959#define SQLITE_AFF_TEXT     'a'
8960#define SQLITE_AFF_NONE     'b'
8961#define SQLITE_AFF_NUMERIC  'c'
8962#define SQLITE_AFF_INTEGER  'd'
8963#define SQLITE_AFF_REAL     'e'
8964
8965#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8966
8967/*
8968** The SQLITE_AFF_MASK values masks off the significant bits of an
8969** affinity value.
8970*/
8971#define SQLITE_AFF_MASK     0x67
8972
8973/*
8974** Additional bit values that can be ORed with an affinity without
8975** changing the affinity.
8976*/
8977#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8978#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8979#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8980
8981/*
8982** An object of this type is created for each virtual table present in
8983** the database schema.
8984**
8985** If the database schema is shared, then there is one instance of this
8986** structure for each database connection (sqlite3*) that uses the shared
8987** schema. This is because each database connection requires its own unique
8988** instance of the sqlite3_vtab* handle used to access the virtual table
8989** implementation. sqlite3_vtab* handles can not be shared between
8990** database connections, even when the rest of the in-memory database
8991** schema is shared, as the implementation often stores the database
8992** connection handle passed to it via the xConnect() or xCreate() method
8993** during initialization internally. This database connection handle may
8994** then used by the virtual table implementation to access real tables
8995** within the database. So that they appear as part of the callers
8996** transaction, these accesses need to be made via the same database
8997** connection as that used to execute SQL operations on the virtual table.
8998**
8999** All VTable objects that correspond to a single table in a shared
9000** database schema are initially stored in a linked-list pointed to by
9001** the Table.pVTable member variable of the corresponding Table object.
9002** When an sqlite3_prepare() operation is required to access the virtual
9003** table, it searches the list for the VTable that corresponds to the
9004** database connection doing the preparing so as to use the correct
9005** sqlite3_vtab* handle in the compiled query.
9006**
9007** When an in-memory Table object is deleted (for example when the
9008** schema is being reloaded for some reason), the VTable objects are not
9009** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
9010** immediately. Instead, they are moved from the Table.pVTable list to
9011** another linked list headed by the sqlite3.pDisconnect member of the
9012** corresponding sqlite3 structure. They are then deleted/xDisconnected
9013** next time a statement is prepared using said sqlite3*. This is done
9014** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9015** Refer to comments above function sqlite3VtabUnlockList() for an
9016** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9017** list without holding the corresponding sqlite3.mutex mutex.
9018**
9019** The memory for objects of this type is always allocated by
9020** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
9021** the first argument.
9022*/
9023struct VTable {
9024  sqlite3 *db;              /* Database connection associated with this table */
9025  Module *pMod;             /* Pointer to module implementation */
9026  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9027  int nRef;                 /* Number of pointers to this structure */
9028  VTable *pNext;            /* Next in linked list (see above) */
9029};
9030
9031/*
9032** Each SQL table is represented in memory by an instance of the
9033** following structure.
9034**
9035** Table.zName is the name of the table.  The case of the original
9036** CREATE TABLE statement is stored, but case is not significant for
9037** comparisons.
9038**
9039** Table.nCol is the number of columns in this table.  Table.aCol is a
9040** pointer to an array of Column structures, one for each column.
9041**
9042** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9043** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9044** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9045** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9046** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9047** is generated for each row of the table.  TF_HasPrimaryKey is set if
9048** the table has any PRIMARY KEY, INTEGER or otherwise.
9049**
9050** Table.tnum is the page number for the root BTree page of the table in the
9051** database file.  If Table.iDb is the index of the database table backend
9052** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9053** holds temporary tables and indices.  If TF_Ephemeral is set
9054** then the table is stored in a file that is automatically deleted
9055** when the VDBE cursor to the table is closed.  In this case Table.tnum
9056** refers VDBE cursor number that holds the table open, not to the root
9057** page number.  Transient tables are used to hold the results of a
9058** sub-query that appears instead of a real table name in the FROM clause
9059** of a SELECT statement.
9060*/
9061struct Table {
9062  char *zName;         /* Name of the table or view */
9063  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9064  int nCol;            /* Number of columns in this table */
9065  Column *aCol;        /* Information about each column */
9066  Index *pIndex;       /* List of SQL indexes on this table. */
9067  int tnum;            /* Root BTree node for this table (see note above) */
9068  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9069  u16 nRef;            /* Number of pointers to this Table */
9070  u8 tabFlags;         /* Mask of TF_* values */
9071  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9072  FKey *pFKey;         /* Linked list of all foreign keys in this table */
9073  char *zColAff;       /* String defining the affinity of each column */
9074#ifndef SQLITE_OMIT_CHECK
9075  Expr *pCheck;        /* The AND of all CHECK constraints */
9076#endif
9077#ifndef SQLITE_OMIT_ALTERTABLE
9078  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9079#endif
9080#ifndef SQLITE_OMIT_VIRTUALTABLE
9081  VTable *pVTable;     /* List of VTable objects. */
9082  int nModuleArg;      /* Number of arguments to the module */
9083  char **azModuleArg;  /* Text of all module args. [0] is module name */
9084#endif
9085  Trigger *pTrigger;   /* List of triggers stored in pSchema */
9086  Schema *pSchema;     /* Schema that contains this table */
9087  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9088};
9089
9090/*
9091** Allowed values for Tabe.tabFlags.
9092*/
9093#define TF_Readonly        0x01    /* Read-only system table */
9094#define TF_Ephemeral       0x02    /* An ephemeral table */
9095#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9096#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9097#define TF_Virtual         0x10    /* Is a virtual table */
9098#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9099
9100
9101
9102/*
9103** Test to see whether or not a table is a virtual table.  This is
9104** done as a macro so that it will be optimized out when virtual
9105** table support is omitted from the build.
9106*/
9107#ifndef SQLITE_OMIT_VIRTUALTABLE
9108#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9109#  define IsHiddenColumn(X) ((X)->isHidden)
9110#else
9111#  define IsVirtual(X)      0
9112#  define IsHiddenColumn(X) 0
9113#endif
9114
9115/*
9116** Each foreign key constraint is an instance of the following structure.
9117**
9118** A foreign key is associated with two tables.  The "from" table is
9119** the table that contains the REFERENCES clause that creates the foreign
9120** key.  The "to" table is the table that is named in the REFERENCES clause.
9121** Consider this example:
9122**
9123**     CREATE TABLE ex1(
9124**       a INTEGER PRIMARY KEY,
9125**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9126**     );
9127**
9128** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9129**
9130** Each REFERENCES clause generates an instance of the following structure
9131** which is attached to the from-table.  The to-table need not exist when
9132** the from-table is created.  The existence of the to-table is not checked.
9133*/
9134struct FKey {
9135  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9136  FKey *pNextFrom;  /* Next foreign key in pFrom */
9137  char *zTo;        /* Name of table that the key points to (aka: Parent) */
9138  FKey *pNextTo;    /* Next foreign key on table named zTo */
9139  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9140  int nCol;         /* Number of columns in this key */
9141  /* EV: R-30323-21917 */
9142  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9143  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9144  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9145  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9146    int iFrom;         /* Index of column in pFrom */
9147    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9148  } aCol[1];        /* One entry for each of nCol column s */
9149};
9150
9151/*
9152** SQLite supports many different ways to resolve a constraint
9153** error.  ROLLBACK processing means that a constraint violation
9154** causes the operation in process to fail and for the current transaction
9155** to be rolled back.  ABORT processing means the operation in process
9156** fails and any prior changes from that one operation are backed out,
9157** but the transaction is not rolled back.  FAIL processing means that
9158** the operation in progress stops and returns an error code.  But prior
9159** changes due to the same operation are not backed out and no rollback
9160** occurs.  IGNORE means that the particular row that caused the constraint
9161** error is not inserted or updated.  Processing continues and no error
9162** is returned.  REPLACE means that preexisting database rows that caused
9163** a UNIQUE constraint violation are removed so that the new insert or
9164** update can proceed.  Processing continues and no error is reported.
9165**
9166** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9167** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9168** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9169** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9170** referenced table row is propagated into the row that holds the
9171** foreign key.
9172**
9173** The following symbolic values are used to record which type
9174** of action to take.
9175*/
9176#define OE_None     0   /* There is no constraint to check */
9177#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9178#define OE_Abort    2   /* Back out changes but do no rollback transaction */
9179#define OE_Fail     3   /* Stop the operation but leave all prior changes */
9180#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9181#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9182
9183#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9184#define OE_SetNull  7   /* Set the foreign key value to NULL */
9185#define OE_SetDflt  8   /* Set the foreign key value to its default */
9186#define OE_Cascade  9   /* Cascade the changes */
9187
9188#define OE_Default  99  /* Do whatever the default action is */
9189
9190
9191/*
9192** An instance of the following structure is passed as the first
9193** argument to sqlite3VdbeKeyCompare and is used to control the
9194** comparison of the two index keys.
9195*/
9196struct KeyInfo {
9197  sqlite3 *db;        /* The database connection */
9198  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9199  u16 nField;         /* Number of entries in aColl[] */
9200  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9201  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9202};
9203
9204/*
9205** An instance of the following structure holds information about a
9206** single index record that has already been parsed out into individual
9207** values.
9208**
9209** A record is an object that contains one or more fields of data.
9210** Records are used to store the content of a table row and to store
9211** the key of an index.  A blob encoding of a record is created by
9212** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9213** OP_Column opcode.
9214**
9215** This structure holds a record that has already been disassembled
9216** into its constituent fields.
9217*/
9218struct UnpackedRecord {
9219  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9220  u16 nField;         /* Number of entries in apMem[] */
9221  u16 flags;          /* Boolean settings.  UNPACKED_... below */
9222  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9223  Mem *aMem;          /* Values */
9224};
9225
9226/*
9227** Allowed values of UnpackedRecord.flags
9228*/
9229#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9230#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9231#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9232#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9233#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9234#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9235
9236/*
9237** Each SQL index is represented in memory by an
9238** instance of the following structure.
9239**
9240** The columns of the table that are to be indexed are described
9241** by the aiColumn[] field of this structure.  For example, suppose
9242** we have the following table and index:
9243**
9244**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9245**     CREATE INDEX Ex2 ON Ex1(c3,c1);
9246**
9247** In the Table structure describing Ex1, nCol==3 because there are
9248** three columns in the table.  In the Index structure describing
9249** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9250** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
9251** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9252** The second column to be indexed (c1) has an index of 0 in
9253** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9254**
9255** The Index.onError field determines whether or not the indexed columns
9256** must be unique and what to do if they are not.  When Index.onError=OE_None,
9257** it means this is not a unique index.  Otherwise it is a unique index
9258** and the value of Index.onError indicate the which conflict resolution
9259** algorithm to employ whenever an attempt is made to insert a non-unique
9260** element.
9261*/
9262struct Index {
9263  char *zName;     /* Name of this index */
9264  int nColumn;     /* Number of columns in the table used by this index */
9265  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9266  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9267  Table *pTable;   /* The SQL table being indexed */
9268  int tnum;        /* Page containing root of this index in database file */
9269  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9270  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9271  char *zColAff;   /* String defining the affinity of each column */
9272  Index *pNext;    /* The next index associated with the same table */
9273  Schema *pSchema; /* Schema containing this index */
9274  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9275  char **azColl;   /* Array of collation sequence names for index */
9276  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9277};
9278
9279/*
9280** Each sample stored in the sqlite_stat2 table is represented in memory
9281** using a structure of this type.
9282*/
9283struct IndexSample {
9284  union {
9285    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9286    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9287  } u;
9288  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9289  u8 nByte;         /* Size in byte of text or blob. */
9290};
9291
9292/*
9293** Each token coming out of the lexer is an instance of
9294** this structure.  Tokens are also used as part of an expression.
9295**
9296** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9297** may contain random values.  Do not make any assumptions about Token.dyn
9298** and Token.n when Token.z==0.
9299*/
9300struct Token {
9301  const char *z;     /* Text of the token.  Not NULL-terminated! */
9302  unsigned int n;    /* Number of characters in this token */
9303};
9304
9305/*
9306** An instance of this structure contains information needed to generate
9307** code for a SELECT that contains aggregate functions.
9308**
9309** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9310** pointer to this structure.  The Expr.iColumn field is the index in
9311** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9312** code for that node.
9313**
9314** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9315** original Select structure that describes the SELECT statement.  These
9316** fields do not need to be freed when deallocating the AggInfo structure.
9317*/
9318struct AggInfo {
9319  u8 directMode;          /* Direct rendering mode means take data directly
9320                          ** from source tables rather than from accumulators */
9321  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9322                          ** than the source table */
9323  int sortingIdx;         /* Cursor number of the sorting index */
9324  ExprList *pGroupBy;     /* The group by clause */
9325  int nSortingColumn;     /* Number of columns in the sorting index */
9326  struct AggInfo_col {    /* For each column used in source tables */
9327    Table *pTab;             /* Source table */
9328    int iTable;              /* Cursor number of the source table */
9329    int iColumn;             /* Column number within the source table */
9330    int iSorterColumn;       /* Column number in the sorting index */
9331    int iMem;                /* Memory location that acts as accumulator */
9332    Expr *pExpr;             /* The original expression */
9333  } *aCol;
9334  int nColumn;            /* Number of used entries in aCol[] */
9335  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9336  int nAccumulator;       /* Number of columns that show through to the output.
9337                          ** Additional columns are used only as parameters to
9338                          ** aggregate functions */
9339  struct AggInfo_func {   /* For each aggregate function */
9340    Expr *pExpr;             /* Expression encoding the function */
9341    FuncDef *pFunc;          /* The aggregate function implementation */
9342    int iMem;                /* Memory location that acts as accumulator */
9343    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9344  } *aFunc;
9345  int nFunc;              /* Number of entries in aFunc[] */
9346  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9347};
9348
9349/*
9350** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9351** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9352** than 32767 we have to make it 32-bit.  16-bit is preferred because
9353** it uses less memory in the Expr object, which is a big memory user
9354** in systems with lots of prepared statements.  And few applications
9355** need more than about 10 or 20 variables.  But some extreme users want
9356** to have prepared statements with over 32767 variables, and for them
9357** the option is available (at compile-time).
9358*/
9359#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9360typedef i16 ynVar;
9361#else
9362typedef int ynVar;
9363#endif
9364
9365/*
9366** Each node of an expression in the parse tree is an instance
9367** of this structure.
9368**
9369** Expr.op is the opcode. The integer parser token codes are reused
9370** as opcodes here. For example, the parser defines TK_GE to be an integer
9371** code representing the ">=" operator. This same integer code is reused
9372** to represent the greater-than-or-equal-to operator in the expression
9373** tree.
9374**
9375** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9376** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9377** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9378** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9379** then Expr.token contains the name of the function.
9380**
9381** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9382** binary operator. Either or both may be NULL.
9383**
9384** Expr.x.pList is a list of arguments if the expression is an SQL function,
9385** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9386** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9387** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9388** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9389** valid.
9390**
9391** An expression of the form ID or ID.ID refers to a column in a table.
9392** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9393** the integer cursor number of a VDBE cursor pointing to that table and
9394** Expr.iColumn is the column number for the specific column.  If the
9395** expression is used as a result in an aggregate SELECT, then the
9396** value is also stored in the Expr.iAgg column in the aggregate so that
9397** it can be accessed after all aggregates are computed.
9398**
9399** If the expression is an unbound variable marker (a question mark
9400** character '?' in the original SQL) then the Expr.iTable holds the index
9401** number for that variable.
9402**
9403** If the expression is a subquery then Expr.iColumn holds an integer
9404** register number containing the result of the subquery.  If the
9405** subquery gives a constant result, then iTable is -1.  If the subquery
9406** gives a different answer at different times during statement processing
9407** then iTable is the address of a subroutine that computes the subquery.
9408**
9409** If the Expr is of type OP_Column, and the table it is selecting from
9410** is a disk table or the "old.*" pseudo-table, then pTab points to the
9411** corresponding table definition.
9412**
9413** ALLOCATION NOTES:
9414**
9415** Expr objects can use a lot of memory space in database schema.  To
9416** help reduce memory requirements, sometimes an Expr object will be
9417** truncated.  And to reduce the number of memory allocations, sometimes
9418** two or more Expr objects will be stored in a single memory allocation,
9419** together with Expr.zToken strings.
9420**
9421** If the EP_Reduced and EP_TokenOnly flags are set when
9422** an Expr object is truncated.  When EP_Reduced is set, then all
9423** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9424** are contained within the same memory allocation.  Note, however, that
9425** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9426** allocated, regardless of whether or not EP_Reduced is set.
9427*/
9428struct Expr {
9429  u8 op;                 /* Operation performed by this node */
9430  char affinity;         /* The affinity of the column or 0 if not a column */
9431  u16 flags;             /* Various flags.  EP_* See below */
9432  union {
9433    char *zToken;          /* Token value. Zero terminated and dequoted */
9434    int iValue;            /* Integer value if EP_IntValue */
9435  } u;
9436
9437  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9438  ** space is allocated for the fields below this point. An attempt to
9439  ** access them will result in a segfault or malfunction.
9440  *********************************************************************/
9441
9442  Expr *pLeft;           /* Left subnode */
9443  Expr *pRight;          /* Right subnode */
9444  union {
9445    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9446    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9447  } x;
9448  CollSeq *pColl;        /* The collation type of the column or 0 */
9449
9450  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9451  ** space is allocated for the fields below this point. An attempt to
9452  ** access them will result in a segfault or malfunction.
9453  *********************************************************************/
9454
9455  int iTable;            /* TK_COLUMN: cursor number of table holding column
9456                         ** TK_REGISTER: register number
9457                         ** TK_TRIGGER: 1 -> new, 0 -> old */
9458  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9459                         ** TK_VARIABLE: variable number (always >= 1). */
9460  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9461  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9462  u8 flags2;             /* Second set of flags.  EP2_... */
9463  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9464  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9465  Table *pTab;           /* Table for TK_COLUMN expressions. */
9466#if SQLITE_MAX_EXPR_DEPTH>0
9467  int nHeight;           /* Height of the tree headed by this node */
9468#endif
9469};
9470
9471/*
9472** The following are the meanings of bits in the Expr.flags field.
9473*/
9474#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9475#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9476#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9477#define EP_Error      0x0008  /* Expression contains one or more errors */
9478#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9479#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9480#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9481#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9482#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9483#define EP_FixedDest  0x0200  /* Result needed in a specific register */
9484#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9485#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9486
9487#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9488#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9489#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9490
9491/*
9492** The following are the meanings of bits in the Expr.flags2 field.
9493*/
9494#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9495#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9496
9497/*
9498** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9499** flag on an expression structure.  This flag is used for VV&A only.  The
9500** routine is implemented as a macro that only works when in debugging mode,
9501** so as not to burden production code.
9502*/
9503#ifdef SQLITE_DEBUG
9504# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9505#else
9506# define ExprSetIrreducible(X)
9507#endif
9508
9509/*
9510** These macros can be used to test, set, or clear bits in the
9511** Expr.flags field.
9512*/
9513#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9514#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9515#define ExprSetProperty(E,P)     (E)->flags|=(P)
9516#define ExprClearProperty(E,P)   (E)->flags&=~(P)
9517
9518/*
9519** Macros to determine the number of bytes required by a normal Expr
9520** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
9521** and an Expr struct with the EP_TokenOnly flag set.
9522*/
9523#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9524#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9525#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9526
9527/*
9528** Flags passed to the sqlite3ExprDup() function. See the header comment
9529** above sqlite3ExprDup() for details.
9530*/
9531#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9532
9533/*
9534** A list of expressions.  Each expression may optionally have a
9535** name.  An expr/name combination can be used in several ways, such
9536** as the list of "expr AS ID" fields following a "SELECT" or in the
9537** list of "ID = expr" items in an UPDATE.  A list of expressions can
9538** also be used as the argument to a function, in which case the a.zName
9539** field is not used.
9540*/
9541struct ExprList {
9542  int nExpr;             /* Number of expressions on the list */
9543  int nAlloc;            /* Number of entries allocated below */
9544  int iECursor;          /* VDBE Cursor associated with this ExprList */
9545  struct ExprList_item {
9546    Expr *pExpr;           /* The list of expressions */
9547    char *zName;           /* Token associated with this expression */
9548    char *zSpan;           /* Original text of the expression */
9549    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9550    u8 done;               /* A flag to indicate when processing is finished */
9551    u16 iCol;              /* For ORDER BY, column number in result set */
9552    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9553  } *a;                  /* One entry for each expression */
9554};
9555
9556/*
9557** An instance of this structure is used by the parser to record both
9558** the parse tree for an expression and the span of input text for an
9559** expression.
9560*/
9561struct ExprSpan {
9562  Expr *pExpr;          /* The expression parse tree */
9563  const char *zStart;   /* First character of input text */
9564  const char *zEnd;     /* One character past the end of input text */
9565};
9566
9567/*
9568** An instance of this structure can hold a simple list of identifiers,
9569** such as the list "a,b,c" in the following statements:
9570**
9571**      INSERT INTO t(a,b,c) VALUES ...;
9572**      CREATE INDEX idx ON t(a,b,c);
9573**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9574**
9575** The IdList.a.idx field is used when the IdList represents the list of
9576** column names after a table name in an INSERT statement.  In the statement
9577**
9578**     INSERT INTO t(a,b,c) ...
9579**
9580** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9581*/
9582struct IdList {
9583  struct IdList_item {
9584    char *zName;      /* Name of the identifier */
9585    int idx;          /* Index in some Table.aCol[] of a column named zName */
9586  } *a;
9587  int nId;         /* Number of identifiers on the list */
9588  int nAlloc;      /* Number of entries allocated for a[] below */
9589};
9590
9591/*
9592** The bitmask datatype defined below is used for various optimizations.
9593**
9594** Changing this from a 64-bit to a 32-bit type limits the number of
9595** tables in a join to 32 instead of 64.  But it also reduces the size
9596** of the library by 738 bytes on ix86.
9597*/
9598typedef u64 Bitmask;
9599
9600/*
9601** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9602*/
9603#define BMS  ((int)(sizeof(Bitmask)*8))
9604
9605/*
9606** The following structure describes the FROM clause of a SELECT statement.
9607** Each table or subquery in the FROM clause is a separate element of
9608** the SrcList.a[] array.
9609**
9610** With the addition of multiple database support, the following structure
9611** can also be used to describe a particular table such as the table that
9612** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9613** such a table must be a simple name: ID.  But in SQLite, the table can
9614** now be identified by a database name, a dot, then the table name: ID.ID.
9615**
9616** The jointype starts out showing the join type between the current table
9617** and the next table on the list.  The parser builds the list this way.
9618** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9619** jointype expresses the join between the table and the previous table.
9620**
9621** In the colUsed field, the high-order bit (bit 63) is set if the table
9622** contains more than 63 columns and the 64-th or later column is used.
9623*/
9624struct SrcList {
9625  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9626  i16 nAlloc;      /* Number of entries allocated in a[] below */
9627  struct SrcList_item {
9628    char *zDatabase;  /* Name of database holding this table */
9629    char *zName;      /* Name of the table */
9630    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9631    Table *pTab;      /* An SQL table corresponding to zName */
9632    Select *pSelect;  /* A SELECT statement used in place of a table name */
9633    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9634    u8 jointype;      /* Type of join between this able and the previous */
9635    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9636    int iCursor;      /* The VDBE cursor number used to access this table */
9637    Expr *pOn;        /* The ON clause of a join */
9638    IdList *pUsing;   /* The USING clause of a join */
9639    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9640    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9641    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9642  } a[1];             /* One entry for each identifier on the list */
9643};
9644
9645/*
9646** Permitted values of the SrcList.a.jointype field
9647*/
9648#define JT_INNER     0x0001    /* Any kind of inner or cross join */
9649#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9650#define JT_NATURAL   0x0004    /* True for a "natural" join */
9651#define JT_LEFT      0x0008    /* Left outer join */
9652#define JT_RIGHT     0x0010    /* Right outer join */
9653#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9654#define JT_ERROR     0x0040    /* unknown or unsupported join type */
9655
9656
9657/*
9658** A WherePlan object holds information that describes a lookup
9659** strategy.
9660**
9661** This object is intended to be opaque outside of the where.c module.
9662** It is included here only so that that compiler will know how big it
9663** is.  None of the fields in this object should be used outside of
9664** the where.c module.
9665**
9666** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9667** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9668** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9669** case that more than one of these conditions is true.
9670*/
9671struct WherePlan {
9672  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9673  u32 nEq;                       /* Number of == constraints */
9674  union {
9675    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9676    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9677    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9678  } u;
9679};
9680
9681/*
9682** For each nested loop in a WHERE clause implementation, the WhereInfo
9683** structure contains a single instance of this structure.  This structure
9684** is intended to be private the the where.c module and should not be
9685** access or modified by other modules.
9686**
9687** The pIdxInfo field is used to help pick the best index on a
9688** virtual table.  The pIdxInfo pointer contains indexing
9689** information for the i-th table in the FROM clause before reordering.
9690** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9691** All other information in the i-th WhereLevel object for the i-th table
9692** after FROM clause ordering.
9693*/
9694struct WhereLevel {
9695  WherePlan plan;       /* query plan for this element of the FROM clause */
9696  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9697  int iTabCur;          /* The VDBE cursor used to access the table */
9698  int iIdxCur;          /* The VDBE cursor used to access pIdx */
9699  int addrBrk;          /* Jump here to break out of the loop */
9700  int addrNxt;          /* Jump here to start the next IN combination */
9701  int addrCont;         /* Jump here to continue with the next loop cycle */
9702  int addrFirst;        /* First instruction of interior of the loop */
9703  u8 iFrom;             /* Which entry in the FROM clause */
9704  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9705  int p1, p2;           /* Operands of the opcode used to ends the loop */
9706  union {               /* Information that depends on plan.wsFlags */
9707    struct {
9708      int nIn;              /* Number of entries in aInLoop[] */
9709      struct InLoop {
9710        int iCur;              /* The VDBE cursor used by this IN operator */
9711        int addrInTop;         /* Top of the IN loop */
9712      } *aInLoop;           /* Information about each nested IN operator */
9713    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9714  } u;
9715
9716  /* The following field is really not part of the current level.  But
9717  ** we need a place to cache virtual table index information for each
9718  ** virtual table in the FROM clause and the WhereLevel structure is
9719  ** a convenient place since there is one WhereLevel for each FROM clause
9720  ** element.
9721  */
9722  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9723};
9724
9725/*
9726** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9727** and the WhereInfo.wctrlFlags member.
9728*/
9729#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9730#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9731#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9732#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9733#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9734#define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
9735#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9736#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9737#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9738
9739/*
9740** The WHERE clause processing routine has two halves.  The
9741** first part does the start of the WHERE loop and the second
9742** half does the tail of the WHERE loop.  An instance of
9743** this structure is returned by the first half and passed
9744** into the second half to give some continuity.
9745*/
9746struct WhereInfo {
9747  Parse *pParse;       /* Parsing and code generating context */
9748  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9749  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9750  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9751  SrcList *pTabList;             /* List of tables in the join */
9752  int iTop;                      /* The very beginning of the WHERE loop */
9753  int iContinue;                 /* Jump here to continue with next record */
9754  int iBreak;                    /* Jump here to break out of the loop */
9755  int nLevel;                    /* Number of nested loop */
9756  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9757  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
9758  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9759};
9760
9761/*
9762** A NameContext defines a context in which to resolve table and column
9763** names.  The context consists of a list of tables (the pSrcList) field and
9764** a list of named expression (pEList).  The named expression list may
9765** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9766** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9767** pEList corresponds to the result set of a SELECT and is NULL for
9768** other statements.
9769**
9770** NameContexts can be nested.  When resolving names, the inner-most
9771** context is searched first.  If no match is found, the next outer
9772** context is checked.  If there is still no match, the next context
9773** is checked.  This process continues until either a match is found
9774** or all contexts are check.  When a match is found, the nRef member of
9775** the context containing the match is incremented.
9776**
9777** Each subquery gets a new NameContext.  The pNext field points to the
9778** NameContext in the parent query.  Thus the process of scanning the
9779** NameContext list corresponds to searching through successively outer
9780** subqueries looking for a match.
9781*/
9782struct NameContext {
9783  Parse *pParse;       /* The parser */
9784  SrcList *pSrcList;   /* One or more tables used to resolve names */
9785  ExprList *pEList;    /* Optional list of named expressions */
9786  int nRef;            /* Number of names resolved by this context */
9787  int nErr;            /* Number of errors encountered while resolving names */
9788  u8 allowAgg;         /* Aggregate functions allowed here */
9789  u8 hasAgg;           /* True if aggregates are seen */
9790  u8 isCheck;          /* True if resolving names in a CHECK constraint */
9791  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9792  AggInfo *pAggInfo;   /* Information about aggregates at this level */
9793  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9794};
9795
9796/*
9797** An instance of the following structure contains all information
9798** needed to generate code for a single SELECT statement.
9799**
9800** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9801** If there is a LIMIT clause, the parser sets nLimit to the value of the
9802** limit and nOffset to the value of the offset (or 0 if there is not
9803** offset).  But later on, nLimit and nOffset become the memory locations
9804** in the VDBE that record the limit and offset counters.
9805**
9806** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9807** These addresses must be stored so that we can go back and fill in
9808** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9809** the number of columns in P2 can be computed at the same time
9810** as the OP_OpenEphm instruction is coded because not
9811** enough information about the compound query is known at that point.
9812** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9813** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9814** sequences for the ORDER BY clause.
9815*/
9816struct Select {
9817  ExprList *pEList;      /* The fields of the result */
9818  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9819  char affinity;         /* MakeRecord with this affinity for SRT_Set */
9820  u16 selFlags;          /* Various SF_* values */
9821  SrcList *pSrc;         /* The FROM clause */
9822  Expr *pWhere;          /* The WHERE clause */
9823  ExprList *pGroupBy;    /* The GROUP BY clause */
9824  Expr *pHaving;         /* The HAVING clause */
9825  ExprList *pOrderBy;    /* The ORDER BY clause */
9826  Select *pPrior;        /* Prior select in a compound select statement */
9827  Select *pNext;         /* Next select to the left in a compound */
9828  Select *pRightmost;    /* Right-most select in a compound select statement */
9829  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9830  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9831  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9832  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9833};
9834
9835/*
9836** Allowed values for Select.selFlags.  The "SF" prefix stands for
9837** "Select Flag".
9838*/
9839#define SF_Distinct        0x0001  /* Output should be DISTINCT */
9840#define SF_Resolved        0x0002  /* Identifiers have been resolved */
9841#define SF_Aggregate       0x0004  /* Contains aggregate functions */
9842#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9843#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9844#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9845
9846
9847/*
9848** The results of a select can be distributed in several ways.  The
9849** "SRT" prefix means "SELECT Result Type".
9850*/
9851#define SRT_Union        1  /* Store result as keys in an index */
9852#define SRT_Except       2  /* Remove result from a UNION index */
9853#define SRT_Exists       3  /* Store 1 if the result is not empty */
9854#define SRT_Discard      4  /* Do not save the results anywhere */
9855
9856/* The ORDER BY clause is ignored for all of the above */
9857#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9858
9859#define SRT_Output       5  /* Output each row of result */
9860#define SRT_Mem          6  /* Store result in a memory cell */
9861#define SRT_Set          7  /* Store results as keys in an index */
9862#define SRT_Table        8  /* Store result as data with an automatic rowid */
9863#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9864#define SRT_Coroutine   10  /* Generate a single row of result */
9865
9866/*
9867** A structure used to customize the behavior of sqlite3Select(). See
9868** comments above sqlite3Select() for details.
9869*/
9870typedef struct SelectDest SelectDest;
9871struct SelectDest {
9872  u8 eDest;         /* How to dispose of the results */
9873  u8 affinity;      /* Affinity used when eDest==SRT_Set */
9874  int iParm;        /* A parameter used by the eDest disposal method */
9875  int iMem;         /* Base register where results are written */
9876  int nMem;         /* Number of registers allocated */
9877};
9878
9879/*
9880** During code generation of statements that do inserts into AUTOINCREMENT
9881** tables, the following information is attached to the Table.u.autoInc.p
9882** pointer of each autoincrement table to record some side information that
9883** the code generator needs.  We have to keep per-table autoincrement
9884** information in case inserts are down within triggers.  Triggers do not
9885** normally coordinate their activities, but we do need to coordinate the
9886** loading and saving of autoincrement information.
9887*/
9888struct AutoincInfo {
9889  AutoincInfo *pNext;   /* Next info block in a list of them all */
9890  Table *pTab;          /* Table this info block refers to */
9891  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9892  int regCtr;           /* Memory register holding the rowid counter */
9893};
9894
9895/*
9896** Size of the column cache
9897*/
9898#ifndef SQLITE_N_COLCACHE
9899# define SQLITE_N_COLCACHE 10
9900#endif
9901
9902/*
9903** At least one instance of the following structure is created for each
9904** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9905** statement. All such objects are stored in the linked list headed at
9906** Parse.pTriggerPrg and deleted once statement compilation has been
9907** completed.
9908**
9909** A Vdbe sub-program that implements the body and WHEN clause of trigger
9910** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9911** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9912** The Parse.pTriggerPrg list never contains two entries with the same
9913** values for both pTrigger and orconf.
9914**
9915** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9916** accessed (or set to 0 for triggers fired as a result of INSERT
9917** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9918** a mask of new.* columns used by the program.
9919*/
9920struct TriggerPrg {
9921  Trigger *pTrigger;      /* Trigger this program was coded from */
9922  int orconf;             /* Default ON CONFLICT policy */
9923  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9924  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9925  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9926};
9927
9928/*
9929** An SQL parser context.  A copy of this structure is passed through
9930** the parser and down into all the parser action routine in order to
9931** carry around information that is global to the entire parse.
9932**
9933** The structure is divided into two parts.  When the parser and code
9934** generate call themselves recursively, the first part of the structure
9935** is constant but the second part is reset at the beginning and end of
9936** each recursion.
9937**
9938** The nTableLock and aTableLock variables are only used if the shared-cache
9939** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9940** used to store the set of table-locks required by the statement being
9941** compiled. Function sqlite3TableLock() is used to add entries to the
9942** list.
9943*/
9944struct Parse {
9945  sqlite3 *db;         /* The main database structure */
9946  int rc;              /* Return code from execution */
9947  char *zErrMsg;       /* An error message */
9948  Vdbe *pVdbe;         /* An engine for executing database bytecode */
9949  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9950  u8 nameClash;        /* A permanent table name clashes with temp table name */
9951  u8 checkSchema;      /* Causes schema cookie check after an error */
9952  u8 nested;           /* Number of nested calls to the parser/code generator */
9953  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9954  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9955  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9956  int aTempReg[8];     /* Holding area for temporary registers */
9957  int nRangeReg;       /* Size of the temporary register block */
9958  int iRangeReg;       /* First register in temporary register block */
9959  int nErr;            /* Number of errors seen */
9960  int nTab;            /* Number of previously allocated VDBE cursors */
9961  int nMem;            /* Number of memory cells used so far */
9962  int nSet;            /* Number of sets used so far */
9963  int ckBase;          /* Base register of data during check constraints */
9964  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9965  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9966  u8 nColCache;        /* Number of entries in the column cache */
9967  u8 iColCache;        /* Next entry of the cache to replace */
9968  struct yColCache {
9969    int iTable;           /* Table cursor number */
9970    int iColumn;          /* Table column number */
9971    u8 tempReg;           /* iReg is a temp register that needs to be freed */
9972    int iLevel;           /* Nesting level */
9973    int iReg;             /* Reg with value of this column. 0 means none. */
9974    int lru;              /* Least recently used entry has the smallest value */
9975  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9976  u32 writeMask;       /* Start a write transaction on these databases */
9977  u32 cookieMask;      /* Bitmask of schema verified databases */
9978  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9979  u8 mayAbort;         /* True if statement may throw an ABORT exception */
9980  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9981  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9982#ifndef SQLITE_OMIT_SHARED_CACHE
9983  int nTableLock;        /* Number of locks in aTableLock */
9984  TableLock *aTableLock; /* Required table locks for shared-cache mode */
9985#endif
9986  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9987  int regRoot;         /* Register holding root page number for new objects */
9988  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9989  int nMaxArg;         /* Max args passed to user function by sub-program */
9990
9991  /* Information used while coding trigger programs. */
9992  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9993  Table *pTriggerTab;  /* Table triggers are being coded for */
9994  u32 oldmask;         /* Mask of old.* columns referenced */
9995  u32 newmask;         /* Mask of new.* columns referenced */
9996  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9997  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9998  u8 disableTriggers;  /* True to disable triggers */
9999  double nQueryLoop;   /* Estimated number of iterations of a query */
10000
10001  /* Above is constant between recursions.  Below is reset before and after
10002  ** each recursion */
10003
10004  int nVar;            /* Number of '?' variables seen in the SQL so far */
10005  int nVarExpr;        /* Number of used slots in apVarExpr[] */
10006  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10007  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10008  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10009  int nAlias;          /* Number of aliased result set columns */
10010  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10011  int *aAlias;         /* Register used to hold aliased result */
10012  u8 explain;          /* True if the EXPLAIN flag is found on the query */
10013  Token sNameToken;    /* Token with unqualified schema object name */
10014  Token sLastToken;    /* The last token parsed */
10015  const char *zTail;   /* All SQL text past the last semicolon parsed */
10016  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10017  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10018  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10019#ifndef SQLITE_OMIT_VIRTUALTABLE
10020  Token sArg;                /* Complete text of a module argument */
10021  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10022  int nVtabLock;             /* Number of virtual tables to lock */
10023  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10024#endif
10025  int nHeight;            /* Expression tree height of current sub-select */
10026  Table *pZombieTab;      /* List of Table objects to delete after code gen */
10027  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10028};
10029
10030#ifdef SQLITE_OMIT_VIRTUALTABLE
10031  #define IN_DECLARE_VTAB 0
10032#else
10033  #define IN_DECLARE_VTAB (pParse->declareVtab)
10034#endif
10035
10036/*
10037** An instance of the following structure can be declared on a stack and used
10038** to save the Parse.zAuthContext value so that it can be restored later.
10039*/
10040struct AuthContext {
10041  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10042  Parse *pParse;              /* The Parse structure */
10043};
10044
10045/*
10046** Bitfield flags for P5 value in OP_Insert and OP_Delete
10047*/
10048#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10049#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10050#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10051#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10052#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10053#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10054
10055/*
10056 * Each trigger present in the database schema is stored as an instance of
10057 * struct Trigger.
10058 *
10059 * Pointers to instances of struct Trigger are stored in two ways.
10060 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
10061 *    database). This allows Trigger structures to be retrieved by name.
10062 * 2. All triggers associated with a single table form a linked list, using the
10063 *    pNext member of struct Trigger. A pointer to the first element of the
10064 *    linked list is stored as the "pTrigger" member of the associated
10065 *    struct Table.
10066 *
10067 * The "step_list" member points to the first element of a linked list
10068 * containing the SQL statements specified as the trigger program.
10069 */
10070struct Trigger {
10071  char *zName;            /* The name of the trigger                        */
10072  char *table;            /* The table or view to which the trigger applies */
10073  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10074  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10075  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10076  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10077                             the <column-list> is stored here */
10078  Schema *pSchema;        /* Schema containing the trigger */
10079  Schema *pTabSchema;     /* Schema containing the table */
10080  TriggerStep *step_list; /* Link list of trigger program steps             */
10081  Trigger *pNext;         /* Next trigger associated with the table */
10082};
10083
10084/*
10085** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10086** determine which.
10087**
10088** If there are multiple triggers, you might of some BEFORE and some AFTER.
10089** In that cases, the constants below can be ORed together.
10090*/
10091#define TRIGGER_BEFORE  1
10092#define TRIGGER_AFTER   2
10093
10094/*
10095 * An instance of struct TriggerStep is used to store a single SQL statement
10096 * that is a part of a trigger-program.
10097 *
10098 * Instances of struct TriggerStep are stored in a singly linked list (linked
10099 * using the "pNext" member) referenced by the "step_list" member of the
10100 * associated struct Trigger instance. The first element of the linked list is
10101 * the first step of the trigger-program.
10102 *
10103 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10104 * "SELECT" statement. The meanings of the other members is determined by the
10105 * value of "op" as follows:
10106 *
10107 * (op == TK_INSERT)
10108 * orconf    -> stores the ON CONFLICT algorithm
10109 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10110 *              this stores a pointer to the SELECT statement. Otherwise NULL.
10111 * target    -> A token holding the quoted name of the table to insert into.
10112 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10113 *              this stores values to be inserted. Otherwise NULL.
10114 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
10115 *              statement, then this stores the column-names to be
10116 *              inserted into.
10117 *
10118 * (op == TK_DELETE)
10119 * target    -> A token holding the quoted name of the table to delete from.
10120 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10121 *              Otherwise NULL.
10122 *
10123 * (op == TK_UPDATE)
10124 * target    -> A token holding the quoted name of the table to update rows of.
10125 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10126 *              Otherwise NULL.
10127 * pExprList -> A list of the columns to update and the expressions to update
10128 *              them to. See sqlite3Update() documentation of "pChanges"
10129 *              argument.
10130 *
10131 */
10132struct TriggerStep {
10133  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10134  u8 orconf;           /* OE_Rollback etc. */
10135  Trigger *pTrig;      /* The trigger that this step is a part of */
10136  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10137  Token target;        /* Target table for DELETE, UPDATE, INSERT */
10138  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10139  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10140  IdList *pIdList;     /* Column names for INSERT */
10141  TriggerStep *pNext;  /* Next in the link-list */
10142  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10143};
10144
10145/*
10146** The following structure contains information used by the sqliteFix...
10147** routines as they walk the parse tree to make database references
10148** explicit.
10149*/
10150typedef struct DbFixer DbFixer;
10151struct DbFixer {
10152  Parse *pParse;      /* The parsing context.  Error messages written here */
10153  const char *zDb;    /* Make sure all objects are contained in this database */
10154  const char *zType;  /* Type of the container - used for error messages */
10155  const Token *pName; /* Name of the container - used for error messages */
10156};
10157
10158/*
10159** An objected used to accumulate the text of a string where we
10160** do not necessarily know how big the string will be in the end.
10161*/
10162struct StrAccum {
10163  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10164  char *zBase;         /* A base allocation.  Not from malloc. */
10165  char *zText;         /* The string collected so far */
10166  int  nChar;          /* Length of the string so far */
10167  int  nAlloc;         /* Amount of space allocated in zText */
10168  int  mxAlloc;        /* Maximum allowed string length */
10169  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10170  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10171  u8   tooBig;         /* Becomes true if string size exceeds limits */
10172};
10173
10174/*
10175** A pointer to this structure is used to communicate information
10176** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10177*/
10178typedef struct {
10179  sqlite3 *db;        /* The database being initialized */
10180  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10181  char **pzErrMsg;    /* Error message stored here */
10182  int rc;             /* Result code stored here */
10183} InitData;
10184
10185/*
10186** Structure containing global configuration data for the SQLite library.
10187**
10188** This structure also contains some state information.
10189*/
10190struct Sqlite3Config {
10191  int bMemstat;                     /* True to enable memory status */
10192  int bCoreMutex;                   /* True to enable core mutexing */
10193  int bFullMutex;                   /* True to enable full mutexing */
10194  int mxStrlen;                     /* Maximum string length */
10195  int szLookaside;                  /* Default lookaside buffer size */
10196  int nLookaside;                   /* Default lookaside buffer count */
10197  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10198  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10199  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10200  void *pHeap;                      /* Heap storage space */
10201  int nHeap;                        /* Size of pHeap[] */
10202  int mnReq, mxReq;                 /* Min and max heap requests sizes */
10203  void *pScratch;                   /* Scratch memory */
10204  int szScratch;                    /* Size of each scratch buffer */
10205  int nScratch;                     /* Number of scratch buffers */
10206  void *pPage;                      /* Page cache memory */
10207  int szPage;                       /* Size of each page in pPage[] */
10208  int nPage;                        /* Number of pages in pPage[] */
10209  int mxParserStack;                /* maximum depth of the parser stack */
10210  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10211  /* The above might be initialized to non-zero.  The following need to always
10212  ** initially be zero, however. */
10213  int isInit;                       /* True after initialization has finished */
10214  int inProgress;                   /* True while initialization in progress */
10215  int isMutexInit;                  /* True after mutexes are initialized */
10216  int isMallocInit;                 /* True after malloc is initialized */
10217  int isPCacheInit;                 /* True after malloc is initialized */
10218  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10219  int nRefInitMutex;                /* Number of users of pInitMutex */
10220  void (*xLog)(void*,int,const char*); /* Function for logging */
10221  void *pLogArg;                       /* First argument to xLog() */
10222};
10223
10224/*
10225** Context pointer passed down through the tree-walk.
10226*/
10227struct Walker {
10228  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10229  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10230  Parse *pParse;                            /* Parser context.  */
10231  union {                                   /* Extra data for callback */
10232    NameContext *pNC;                          /* Naming context */
10233    int i;                                     /* Integer value */
10234  } u;
10235};
10236
10237/* Forward declarations */
10238SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10239SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10240SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10241SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10242SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10243
10244/*
10245** Return code from the parse-tree walking primitives and their
10246** callbacks.
10247*/
10248#define WRC_Continue    0   /* Continue down into children */
10249#define WRC_Prune       1   /* Omit children but continue walking siblings */
10250#define WRC_Abort       2   /* Abandon the tree walk */
10251
10252/*
10253** Assuming zIn points to the first byte of a UTF-8 character,
10254** advance zIn to point to the first byte of the next UTF-8 character.
10255*/
10256#define SQLITE_SKIP_UTF8(zIn) {                        \
10257  if( (*(zIn++))>=0xc0 ){                              \
10258    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10259  }                                                    \
10260}
10261
10262/*
10263** The SQLITE_*_BKPT macros are substitutes for the error codes with
10264** the same name but without the _BKPT suffix.  These macros invoke
10265** routines that report the line-number on which the error originated
10266** using sqlite3_log().  The routines also provide a convenient place
10267** to set a debugger breakpoint.
10268*/
10269SQLITE_PRIVATE int sqlite3CorruptError(int);
10270SQLITE_PRIVATE int sqlite3MisuseError(int);
10271SQLITE_PRIVATE int sqlite3CantopenError(int);
10272#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10273#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10274#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10275
10276
10277/*
10278** FTS4 is really an extension for FTS3.  It is enabled using the
10279** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10280** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10281*/
10282#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10283# define SQLITE_ENABLE_FTS3
10284#endif
10285
10286/*
10287** The ctype.h header is needed for non-ASCII systems.  It is also
10288** needed by FTS3 when FTS3 is included in the amalgamation.
10289*/
10290#if !defined(SQLITE_ASCII) || \
10291    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10292# include <ctype.h>
10293#endif
10294
10295/*
10296** The following macros mimic the standard library functions toupper(),
10297** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10298** sqlite versions only work for ASCII characters, regardless of locale.
10299*/
10300#ifdef SQLITE_ASCII
10301# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10302# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10303# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10304# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10305# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10306# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10307# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10308#else
10309# define sqlite3Toupper(x)   toupper((unsigned char)(x))
10310# define sqlite3Isspace(x)   isspace((unsigned char)(x))
10311# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10312# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10313# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10314# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10315# define sqlite3Tolower(x)   tolower((unsigned char)(x))
10316#endif
10317
10318/*
10319** Internal function prototypes
10320*/
10321SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10322SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10323SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10324#define sqlite3StrNICmp sqlite3_strnicmp
10325
10326SQLITE_PRIVATE int sqlite3MallocInit(void);
10327SQLITE_PRIVATE void sqlite3MallocEnd(void);
10328SQLITE_PRIVATE void *sqlite3Malloc(int);
10329SQLITE_PRIVATE void *sqlite3MallocZero(int);
10330SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10331SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10332SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10333SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10334SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10335SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10336SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10337SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10338SQLITE_PRIVATE int sqlite3MallocSize(void*);
10339SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10340SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10341SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10342SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10343SQLITE_PRIVATE void sqlite3PageFree(void*);
10344SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10345SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10346SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10347
10348/*
10349** On systems with ample stack space and that support alloca(), make
10350** use of alloca() to obtain space for large automatic objects.  By default,
10351** obtain space from malloc().
10352**
10353** The alloca() routine never returns NULL.  This will cause code paths
10354** that deal with sqlite3StackAlloc() failures to be unreachable.
10355*/
10356#ifdef SQLITE_USE_ALLOCA
10357# define sqlite3StackAllocRaw(D,N)   alloca(N)
10358# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10359# define sqlite3StackFree(D,P)
10360#else
10361# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10362# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10363# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10364#endif
10365
10366#ifdef SQLITE_ENABLE_MEMSYS3
10367SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10368#endif
10369#ifdef SQLITE_ENABLE_MEMSYS5
10370SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10371#endif
10372
10373
10374#ifndef SQLITE_MUTEX_OMIT
10375SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10376SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10377SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10378SQLITE_PRIVATE   int sqlite3MutexInit(void);
10379SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10380#endif
10381
10382SQLITE_PRIVATE int sqlite3StatusValue(int);
10383SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10384SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10385
10386#ifndef SQLITE_OMIT_FLOATING_POINT
10387SQLITE_PRIVATE   int sqlite3IsNaN(double);
10388#else
10389# define sqlite3IsNaN(X)  0
10390#endif
10391
10392SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10393#ifndef SQLITE_OMIT_TRACE
10394SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10395#endif
10396SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10397SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10398SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10399#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10400SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10401#endif
10402#if defined(SQLITE_TEST)
10403SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10404#endif
10405SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10406SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10407SQLITE_PRIVATE int sqlite3Dequote(char*);
10408SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10409SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10410SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10411SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10412SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10413SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10414SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10415SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10416SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10417SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10418SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10419SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10420SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10421SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10422SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10423SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10424SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10425SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10426SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10427SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10428SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10429SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10430SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10431SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10432SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10433SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10434SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10435SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10436SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10437SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10438SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10439SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10440SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10441SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10442SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10443SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10444
10445SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10446SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10447SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10448SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10449SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10450SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10451SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10452
10453SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10454SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10455SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10456SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10457SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10458
10459SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10460
10461#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10462SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10463#else
10464# define sqlite3ViewGetColumnNames(A,B) 0
10465#endif
10466
10467SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10468SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
10469#ifndef SQLITE_OMIT_AUTOINCREMENT
10470SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10471SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10472#else
10473# define sqlite3AutoincrementBegin(X)
10474# define sqlite3AutoincrementEnd(X)
10475#endif
10476SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10477SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10478SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10479SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10480SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10481SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10482SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10483                                      Token*, Select*, Expr*, IdList*);
10484SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10485SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10486SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10487SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10488SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10489SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10490SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10491                        Token*, int, int);
10492SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10493SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10494SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10495                         Expr*,ExprList*,int,Expr*,Expr*);
10496SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10497SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10498SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10499SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10500#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10501SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10502#endif
10503SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10504SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10505SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10506SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10507SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10508SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10509SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10510SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10511SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10512SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10513SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10514SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10515SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10516SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10517SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10518SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10519SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10520SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10521SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10522SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10523SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10524SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10525SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10526SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10527SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10528SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10529SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10530SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10531SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10532SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10533SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10534SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10535SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10536SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10537SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10538SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10539SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10540SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10541SQLITE_PRIVATE void sqlite3PrngResetState(void);
10542SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10543SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10544SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10545SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10546SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10547SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10548SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10549SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10550SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10551SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10552SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10553SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10554SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10555SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10556SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10557SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10558SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10559SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10560SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10561                                     int*,int,int,int,int,int*);
10562SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10563SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10564SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10565SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10566SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10567SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10568SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10569SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10570SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10571SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10572SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10573SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10574SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10575SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10576SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10577SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10578SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10579SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10580SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10581
10582#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10583SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10584#endif
10585
10586#ifndef SQLITE_OMIT_TRIGGER
10587SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10588                           Expr*,int, int);
10589SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10590SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10591SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10592SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10593SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10594SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10595                            int, int, int);
10596SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10597  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10598SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10599SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10600SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10601                                        ExprList*,Select*,u8);
10602SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10603SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10604SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10605SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10606SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10607# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10608#else
10609# define sqlite3TriggersExist(B,C,D,E,F) 0
10610# define sqlite3DeleteTrigger(A,B)
10611# define sqlite3DropTriggerPtr(A,B)
10612# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10613# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10614# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10615# define sqlite3TriggerList(X, Y) 0
10616# define sqlite3ParseToplevel(p) p
10617# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10618#endif
10619
10620SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10621SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10622SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10623#ifndef SQLITE_OMIT_AUTHORIZATION
10624SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10625SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10626SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10627SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10628SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10629#else
10630# define sqlite3AuthRead(a,b,c,d)
10631# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10632# define sqlite3AuthContextPush(a,b,c)
10633# define sqlite3AuthContextPop(a)  ((void)(a))
10634#endif
10635SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10636SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10637SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10638                       int omitJournal, int nCache, int flags, Btree **ppBtree);
10639SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10640SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10641SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10642SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10643SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10644SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10645SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10646SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10647SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10648SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10649SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10650SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10651
10652/*
10653** Routines to read and write variable-length integers.  These used to
10654** be defined locally, but now we use the varint routines in the util.c
10655** file.  Code should use the MACRO forms below, as the Varint32 versions
10656** are coded to assume the single byte case is already handled (which
10657** the MACRO form does).
10658*/
10659SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10660SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10661SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10662SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10663SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10664
10665/*
10666** The header of a record consists of a sequence variable-length integers.
10667** These integers are almost always small and are encoded as a single byte.
10668** The following macros take advantage this fact to provide a fast encode
10669** and decode of the integers in a record header.  It is faster for the common
10670** case where the integer is a single byte.  It is a little slower when the
10671** integer is two or more bytes.  But overall it is faster.
10672**
10673** The following expressions are equivalent:
10674**
10675**     x = sqlite3GetVarint32( A, &B );
10676**     x = sqlite3PutVarint32( A, B );
10677**
10678**     x = getVarint32( A, B );
10679**     x = putVarint32( A, B );
10680**
10681*/
10682#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10683#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10684#define getVarint    sqlite3GetVarint
10685#define putVarint    sqlite3PutVarint
10686
10687
10688SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10689SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10690SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10691SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10692SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10693SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10694SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10695SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10696SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10697SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10698SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10699SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10700SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10701SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10702SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
10703SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
10704SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10705SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10706SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10707
10708SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10709SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10710SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
10711                        void(*)(void*));
10712SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10713SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10714SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
10715#ifdef SQLITE_ENABLE_STAT2
10716SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10717#endif
10718SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10719SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10720#ifndef SQLITE_AMALGAMATION
10721SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10722SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10723SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10724SQLITE_PRIVATE const Token sqlite3IntTokens[];
10725SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10726SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10727#ifndef SQLITE_OMIT_WSD
10728SQLITE_PRIVATE int sqlite3PendingByte;
10729#endif
10730#endif
10731SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10732SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10733SQLITE_PRIVATE void sqlite3AlterFunctions(void);
10734SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10735SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10736SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10737SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10738SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10739SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10740SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10741SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10742SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10743SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10744SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10745SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10746SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10747SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10748SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10749SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10750SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10751SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10752SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10753SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
10754SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10755SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10756SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10757SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10758SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10759SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10760SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10761SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10762SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10763  void (*)(sqlite3_context*,int,sqlite3_value **),
10764  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10765SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10766SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10767
10768SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10769SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10770SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10771SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10772SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10773SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10774
10775SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10776SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10777
10778/*
10779** The interface to the LEMON-generated parser
10780*/
10781SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10782SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10783SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10784#ifdef YYTRACKMAXSTACKDEPTH
10785SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10786#endif
10787
10788SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10789#ifndef SQLITE_OMIT_LOAD_EXTENSION
10790SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10791#else
10792# define sqlite3CloseExtensions(X)
10793#endif
10794
10795#ifndef SQLITE_OMIT_SHARED_CACHE
10796SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10797#else
10798  #define sqlite3TableLock(v,w,x,y,z)
10799#endif
10800
10801#ifdef SQLITE_TEST
10802SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10803#endif
10804
10805#ifdef SQLITE_OMIT_VIRTUALTABLE
10806#  define sqlite3VtabClear(Y)
10807#  define sqlite3VtabSync(X,Y) SQLITE_OK
10808#  define sqlite3VtabRollback(X)
10809#  define sqlite3VtabCommit(X)
10810#  define sqlite3VtabInSync(db) 0
10811#  define sqlite3VtabLock(X)
10812#  define sqlite3VtabUnlock(X)
10813#  define sqlite3VtabUnlockList(X)
10814#else
10815SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
10816SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10817SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10818SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10819SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10820SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10821SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10822#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10823#endif
10824SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10825SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10826SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10827SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10828SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10829SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10830SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10831SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10832SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10833SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10834SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10835SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10836SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10837SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10838SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10839SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10840SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10841SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10842SQLITE_PRIVATE const char *sqlite3JournalModename(int);
10843SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
10844SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
10845
10846/* Declarations for functions in fkey.c. All of these are replaced by
10847** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10848** key functionality is available. If OMIT_TRIGGER is defined but
10849** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10850** this case foreign keys are parsed, but no other functionality is
10851** provided (enforcement of FK constraints requires the triggers sub-system).
10852*/
10853#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10854SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10855SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10856SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10857SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10858SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10859SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10860#else
10861  #define sqlite3FkActions(a,b,c,d)
10862  #define sqlite3FkCheck(a,b,c,d)
10863  #define sqlite3FkDropTable(a,b,c)
10864  #define sqlite3FkOldmask(a,b)      0
10865  #define sqlite3FkRequired(a,b,c,d) 0
10866#endif
10867#ifndef SQLITE_OMIT_FOREIGN_KEY
10868SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
10869#else
10870  #define sqlite3FkDelete(a,b)
10871#endif
10872
10873
10874/*
10875** Available fault injectors.  Should be numbered beginning with 0.
10876*/
10877#define SQLITE_FAULTINJECTOR_MALLOC     0
10878#define SQLITE_FAULTINJECTOR_COUNT      1
10879
10880/*
10881** The interface to the code in fault.c used for identifying "benign"
10882** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10883** is not defined.
10884*/
10885#ifndef SQLITE_OMIT_BUILTIN_TEST
10886SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10887SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10888#else
10889  #define sqlite3BeginBenignMalloc()
10890  #define sqlite3EndBenignMalloc()
10891#endif
10892
10893#define IN_INDEX_ROWID           1
10894#define IN_INDEX_EPH             2
10895#define IN_INDEX_INDEX           3
10896SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10897
10898#ifdef SQLITE_ENABLE_ATOMIC_WRITE
10899SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10900SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10901SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10902#else
10903  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10904#endif
10905
10906SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10907SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10908SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10909
10910#if SQLITE_MAX_EXPR_DEPTH>0
10911SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10912SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10913SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10914#else
10915  #define sqlite3ExprSetHeight(x,y)
10916  #define sqlite3SelectExprHeight(x) 0
10917  #define sqlite3ExprCheckHeight(x,y)
10918#endif
10919
10920SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10921SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10922
10923#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10924SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10925SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10926SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10927#else
10928  #define sqlite3ConnectionBlocked(x,y)
10929  #define sqlite3ConnectionUnlocked(x)
10930  #define sqlite3ConnectionClosed(x)
10931#endif
10932
10933#ifdef SQLITE_DEBUG
10934SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10935#endif
10936
10937/*
10938** If the SQLITE_ENABLE IOTRACE exists then the global variable
10939** sqlite3IoTrace is a pointer to a printf-like routine used to
10940** print I/O tracing messages.
10941*/
10942#ifdef SQLITE_ENABLE_IOTRACE
10943# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10944SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10945SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10946#else
10947# define IOTRACE(A)
10948# define sqlite3VdbeIOTraceSql(X)
10949#endif
10950
10951/*
10952** These routines are available for the mem2.c debugging memory allocator
10953** only.  They are used to verify that different "types" of memory
10954** allocations are properly tracked by the system.
10955**
10956** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
10957** the MEMTYPE_* macros defined below.  The type must be a bitmask with
10958** a single bit set.
10959**
10960** sqlite3MemdebugHasType() returns true if any of the bits in its second
10961** argument match the type set by the previous sqlite3MemdebugSetType().
10962** sqlite3MemdebugHasType() is intended for use inside assert() statements.
10963**
10964** sqlite3MemdebugNoType() returns true if none of the bits in its second
10965** argument match the type set by the previous sqlite3MemdebugSetType().
10966**
10967** Perhaps the most important point is the difference between MEMTYPE_HEAP
10968** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
10969** it might have been allocated by lookaside, except the allocation was
10970** too large or lookaside was already full.  It is important to verify
10971** that allocations that might have been satisfied by lookaside are not
10972** passed back to non-lookaside free() routines.  Asserts such as the
10973** example above are placed on the non-lookaside free() routines to verify
10974** this constraint.
10975**
10976** All of this is no-op for a production build.  It only comes into
10977** play when the SQLITE_MEMDEBUG compile-time option is used.
10978*/
10979#ifdef SQLITE_MEMDEBUG
10980SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
10981SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
10982SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
10983#else
10984# define sqlite3MemdebugSetType(X,Y)  /* no-op */
10985# define sqlite3MemdebugHasType(X,Y)  1
10986# define sqlite3MemdebugNoType(X,Y)   1
10987#endif
10988#define MEMTYPE_HEAP       0x01  /* General heap allocations */
10989#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
10990#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
10991#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
10992#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
10993
10994#endif /* _SQLITEINT_H_ */
10995
10996/************** End of sqliteInt.h *******************************************/
10997/************** Begin file global.c ******************************************/
10998/*
10999** 2008 June 13
11000**
11001** The author disclaims copyright to this source code.  In place of
11002** a legal notice, here is a blessing:
11003**
11004**    May you do good and not evil.
11005**    May you find forgiveness for yourself and forgive others.
11006**    May you share freely, never taking more than you give.
11007**
11008*************************************************************************
11009**
11010** This file contains definitions of global variables and contants.
11011*/
11012
11013/* An array to map all upper-case characters into their corresponding
11014** lower-case character.
11015**
11016** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11017** handle case conversions for the UTF character set since the tables
11018** involved are nearly as big or bigger than SQLite itself.
11019*/
11020SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11021#ifdef SQLITE_ASCII
11022      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11023     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11024     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11025     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11026    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11027    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11028    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11029    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11030    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11031    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11032    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11033    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11034    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11035    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11036    252,253,254,255
11037#endif
11038#ifdef SQLITE_EBCDIC
11039      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11040     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11041     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11042     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11043     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11044     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11045     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11046    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11047    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11048    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11049    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11050    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11051    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11052    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11053    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11054    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11055#endif
11056};
11057
11058/*
11059** The following 256 byte lookup table is used to support SQLites built-in
11060** equivalents to the following standard library functions:
11061**
11062**   isspace()                        0x01
11063**   isalpha()                        0x02
11064**   isdigit()                        0x04
11065**   isalnum()                        0x06
11066**   isxdigit()                       0x08
11067**   toupper()                        0x20
11068**   SQLite identifier character      0x40
11069**
11070** Bit 0x20 is set if the mapped character requires translation to upper
11071** case. i.e. if the character is a lower-case ASCII character.
11072** If x is a lower-case ASCII character, then its upper-case equivalent
11073** is (x - 0x20). Therefore toupper() can be implemented as:
11074**
11075**   (x & ~(map[x]&0x20))
11076**
11077** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11078** array. tolower() is used more often than toupper() by SQLite.
11079**
11080** Bit 0x40 is set if the character non-alphanumeric and can be used in an
11081** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11082** non-ASCII UTF character. Hence the test for whether or not a character is
11083** part of an identifier is 0x46.
11084**
11085** SQLite's versions are identical to the standard versions assuming a
11086** locale of "C". They are implemented as macros in sqliteInt.h.
11087*/
11088#ifdef SQLITE_ASCII
11089SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11090  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11091  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11092  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11093  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11094  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11095  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11096  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11097  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11098
11099  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11100  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11101  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11102  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11103  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11104  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11105  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11106  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11107
11108  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11109  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11110  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11111  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11112  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11113  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11114  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11115  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11116
11117  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11118  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11119  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11120  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11121  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11122  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11123  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11124  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11125};
11126#endif
11127
11128
11129
11130/*
11131** The following singleton contains the global configuration for
11132** the SQLite library.
11133*/
11134SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11135   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11136   1,                         /* bCoreMutex */
11137   SQLITE_THREADSAFE==1,      /* bFullMutex */
11138   0x7ffffffe,                /* mxStrlen */
11139   100,                       /* szLookaside */
11140   500,                       /* nLookaside */
11141   {0,0,0,0,0,0,0,0},         /* m */
11142   {0,0,0,0,0,0,0,0,0},       /* mutex */
11143   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11144   (void*)0,                  /* pHeap */
11145   0,                         /* nHeap */
11146   0, 0,                      /* mnHeap, mxHeap */
11147   (void*)0,                  /* pScratch */
11148   0,                         /* szScratch */
11149   0,                         /* nScratch */
11150   (void*)0,                  /* pPage */
11151   0,                         /* szPage */
11152   0,                         /* nPage */
11153   0,                         /* mxParserStack */
11154   0,                         /* sharedCacheEnabled */
11155   /* All the rest should always be initialized to zero */
11156   0,                         /* isInit */
11157   0,                         /* inProgress */
11158   0,                         /* isMutexInit */
11159   0,                         /* isMallocInit */
11160   0,                         /* isPCacheInit */
11161   0,                         /* pInitMutex */
11162   0,                         /* nRefInitMutex */
11163   0,                         /* xLog */
11164   0,                         /* pLogArg */
11165};
11166
11167
11168/*
11169** Hash table for global functions - functions common to all
11170** database connections.  After initialization, this table is
11171** read-only.
11172*/
11173SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11174
11175/*
11176** Constant tokens for values 0 and 1.
11177*/
11178SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11179   { "0", 1 },
11180   { "1", 1 }
11181};
11182
11183
11184/*
11185** The value of the "pending" byte must be 0x40000000 (1 byte past the
11186** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11187** the database page that contains the pending byte.  It never attempts
11188** to read or write that page.  The pending byte page is set assign
11189** for use by the VFS layers as space for managing file locks.
11190**
11191** During testing, it is often desirable to move the pending byte to
11192** a different position in the file.  This allows code that has to
11193** deal with the pending byte to run on files that are much smaller
11194** than 1 GiB.  The sqlite3_test_control() interface can be used to
11195** move the pending byte.
11196**
11197** IMPORTANT:  Changing the pending byte to any value other than
11198** 0x40000000 results in an incompatible database file format!
11199** Changing the pending byte during operating results in undefined
11200** and dileterious behavior.
11201*/
11202#ifndef SQLITE_OMIT_WSD
11203SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11204#endif
11205
11206/*
11207** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11208** created by mkopcodeh.awk during compilation.  Data is obtained
11209** from the comments following the "case OP_xxxx:" statements in
11210** the vdbe.c file.
11211*/
11212SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11213
11214/************** End of global.c **********************************************/
11215/************** Begin file ctime.c *******************************************/
11216/*
11217** 2010 February 23
11218**
11219** The author disclaims copyright to this source code.  In place of
11220** a legal notice, here is a blessing:
11221**
11222**    May you do good and not evil.
11223**    May you find forgiveness for yourself and forgive others.
11224**    May you share freely, never taking more than you give.
11225**
11226*************************************************************************
11227**
11228** This file implements routines used to report what compile-time options
11229** SQLite was built with.
11230*/
11231
11232#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11233
11234
11235/*
11236** An array of names of all compile-time options.  This array should
11237** be sorted A-Z.
11238**
11239** This array looks large, but in a typical installation actually uses
11240** only a handful of compile-time options, so most times this array is usually
11241** rather short and uses little memory space.
11242*/
11243static const char * const azCompileOpt[] = {
11244
11245/* These macros are provided to "stringify" the value of the define
11246** for those options in which the value is meaningful. */
11247#define CTIMEOPT_VAL_(opt) #opt
11248#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11249
11250#ifdef SQLITE_32BIT_ROWID
11251  "32BIT_ROWID",
11252#endif
11253#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11254  "4_BYTE_ALIGNED_MALLOC",
11255#endif
11256#ifdef SQLITE_CASE_SENSITIVE_LIKE
11257  "CASE_SENSITIVE_LIKE",
11258#endif
11259#ifdef SQLITE_CHECK_PAGES
11260  "CHECK_PAGES",
11261#endif
11262#ifdef SQLITE_COVERAGE_TEST
11263  "COVERAGE_TEST",
11264#endif
11265#ifdef SQLITE_DEBUG
11266  "DEBUG",
11267#endif
11268#ifdef SQLITE_DEFAULT_LOCKING_MODE
11269  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11270#endif
11271#ifdef SQLITE_DISABLE_DIRSYNC
11272  "DISABLE_DIRSYNC",
11273#endif
11274#ifdef SQLITE_DISABLE_LFS
11275  "DISABLE_LFS",
11276#endif
11277#ifdef SQLITE_ENABLE_ATOMIC_WRITE
11278  "ENABLE_ATOMIC_WRITE",
11279#endif
11280#ifdef SQLITE_ENABLE_CEROD
11281  "ENABLE_CEROD",
11282#endif
11283#ifdef SQLITE_ENABLE_COLUMN_METADATA
11284  "ENABLE_COLUMN_METADATA",
11285#endif
11286#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11287  "ENABLE_EXPENSIVE_ASSERT",
11288#endif
11289#ifdef SQLITE_ENABLE_FTS1
11290  "ENABLE_FTS1",
11291#endif
11292#ifdef SQLITE_ENABLE_FTS2
11293  "ENABLE_FTS2",
11294#endif
11295#ifdef SQLITE_ENABLE_FTS3
11296  "ENABLE_FTS3",
11297#endif
11298#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11299  "ENABLE_FTS3_PARENTHESIS",
11300#endif
11301#ifdef SQLITE_ENABLE_FTS4
11302  "ENABLE_FTS4",
11303#endif
11304#ifdef SQLITE_ENABLE_ICU
11305  "ENABLE_ICU",
11306#endif
11307#ifdef SQLITE_ENABLE_IOTRACE
11308  "ENABLE_IOTRACE",
11309#endif
11310#ifdef SQLITE_ENABLE_LOAD_EXTENSION
11311  "ENABLE_LOAD_EXTENSION",
11312#endif
11313#ifdef SQLITE_ENABLE_LOCKING_STYLE
11314  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11315#endif
11316#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11317  "ENABLE_MEMORY_MANAGEMENT",
11318#endif
11319#ifdef SQLITE_ENABLE_MEMSYS3
11320  "ENABLE_MEMSYS3",
11321#endif
11322#ifdef SQLITE_ENABLE_MEMSYS5
11323  "ENABLE_MEMSYS5",
11324#endif
11325#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11326  "ENABLE_OVERSIZE_CELL_CHECK",
11327#endif
11328#ifdef SQLITE_ENABLE_RTREE
11329  "ENABLE_RTREE",
11330#endif
11331#ifdef SQLITE_ENABLE_STAT2
11332  "ENABLE_STAT2",
11333#endif
11334#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11335  "ENABLE_UNLOCK_NOTIFY",
11336#endif
11337#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11338  "ENABLE_UPDATE_DELETE_LIMIT",
11339#endif
11340#ifdef SQLITE_HAS_CODEC
11341  "HAS_CODEC",
11342#endif
11343#ifdef SQLITE_HAVE_ISNAN
11344  "HAVE_ISNAN",
11345#endif
11346#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11347  "HOMEGROWN_RECURSIVE_MUTEX",
11348#endif
11349#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11350  "IGNORE_AFP_LOCK_ERRORS",
11351#endif
11352#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11353  "IGNORE_FLOCK_LOCK_ERRORS",
11354#endif
11355#ifdef SQLITE_INT64_TYPE
11356  "INT64_TYPE",
11357#endif
11358#ifdef SQLITE_LOCK_TRACE
11359  "LOCK_TRACE",
11360#endif
11361#ifdef SQLITE_MEMDEBUG
11362  "MEMDEBUG",
11363#endif
11364#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11365  "MIXED_ENDIAN_64BIT_FLOAT",
11366#endif
11367#ifdef SQLITE_NO_SYNC
11368  "NO_SYNC",
11369#endif
11370#ifdef SQLITE_OMIT_ALTERTABLE
11371  "OMIT_ALTERTABLE",
11372#endif
11373#ifdef SQLITE_OMIT_ANALYZE
11374  "OMIT_ANALYZE",
11375#endif
11376#ifdef SQLITE_OMIT_ATTACH
11377  "OMIT_ATTACH",
11378#endif
11379#ifdef SQLITE_OMIT_AUTHORIZATION
11380  "OMIT_AUTHORIZATION",
11381#endif
11382#ifdef SQLITE_OMIT_AUTOINCREMENT
11383  "OMIT_AUTOINCREMENT",
11384#endif
11385#ifdef SQLITE_OMIT_AUTOINIT
11386  "OMIT_AUTOINIT",
11387#endif
11388#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11389  "OMIT_AUTOMATIC_INDEX",
11390#endif
11391#ifdef SQLITE_OMIT_AUTOVACUUM
11392  "OMIT_AUTOVACUUM",
11393#endif
11394#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11395  "OMIT_BETWEEN_OPTIMIZATION",
11396#endif
11397#ifdef SQLITE_OMIT_BLOB_LITERAL
11398  "OMIT_BLOB_LITERAL",
11399#endif
11400#ifdef SQLITE_OMIT_BTREECOUNT
11401  "OMIT_BTREECOUNT",
11402#endif
11403#ifdef SQLITE_OMIT_BUILTIN_TEST
11404  "OMIT_BUILTIN_TEST",
11405#endif
11406#ifdef SQLITE_OMIT_CAST
11407  "OMIT_CAST",
11408#endif
11409#ifdef SQLITE_OMIT_CHECK
11410  "OMIT_CHECK",
11411#endif
11412/* // redundant
11413** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11414**   "OMIT_COMPILEOPTION_DIAGS",
11415** #endif
11416*/
11417#ifdef SQLITE_OMIT_COMPLETE
11418  "OMIT_COMPLETE",
11419#endif
11420#ifdef SQLITE_OMIT_COMPOUND_SELECT
11421  "OMIT_COMPOUND_SELECT",
11422#endif
11423#ifdef SQLITE_OMIT_DATETIME_FUNCS
11424  "OMIT_DATETIME_FUNCS",
11425#endif
11426#ifdef SQLITE_OMIT_DECLTYPE
11427  "OMIT_DECLTYPE",
11428#endif
11429#ifdef SQLITE_OMIT_DEPRECATED
11430  "OMIT_DEPRECATED",
11431#endif
11432#ifdef SQLITE_OMIT_DISKIO
11433  "OMIT_DISKIO",
11434#endif
11435#ifdef SQLITE_OMIT_EXPLAIN
11436  "OMIT_EXPLAIN",
11437#endif
11438#ifdef SQLITE_OMIT_FLAG_PRAGMAS
11439  "OMIT_FLAG_PRAGMAS",
11440#endif
11441#ifdef SQLITE_OMIT_FLOATING_POINT
11442  "OMIT_FLOATING_POINT",
11443#endif
11444#ifdef SQLITE_OMIT_FOREIGN_KEY
11445  "OMIT_FOREIGN_KEY",
11446#endif
11447#ifdef SQLITE_OMIT_GET_TABLE
11448  "OMIT_GET_TABLE",
11449#endif
11450#ifdef SQLITE_OMIT_INCRBLOB
11451  "OMIT_INCRBLOB",
11452#endif
11453#ifdef SQLITE_OMIT_INTEGRITY_CHECK
11454  "OMIT_INTEGRITY_CHECK",
11455#endif
11456#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11457  "OMIT_LIKE_OPTIMIZATION",
11458#endif
11459#ifdef SQLITE_OMIT_LOAD_EXTENSION
11460  "OMIT_LOAD_EXTENSION",
11461#endif
11462#ifdef SQLITE_OMIT_LOCALTIME
11463  "OMIT_LOCALTIME",
11464#endif
11465#ifdef SQLITE_OMIT_LOOKASIDE
11466  "OMIT_LOOKASIDE",
11467#endif
11468#ifdef SQLITE_OMIT_MEMORYDB
11469  "OMIT_MEMORYDB",
11470#endif
11471#ifdef SQLITE_OMIT_OR_OPTIMIZATION
11472  "OMIT_OR_OPTIMIZATION",
11473#endif
11474#ifdef SQLITE_OMIT_PAGER_PRAGMAS
11475  "OMIT_PAGER_PRAGMAS",
11476#endif
11477#ifdef SQLITE_OMIT_PRAGMA
11478  "OMIT_PRAGMA",
11479#endif
11480#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11481  "OMIT_PROGRESS_CALLBACK",
11482#endif
11483#ifdef SQLITE_OMIT_QUICKBALANCE
11484  "OMIT_QUICKBALANCE",
11485#endif
11486#ifdef SQLITE_OMIT_REINDEX
11487  "OMIT_REINDEX",
11488#endif
11489#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11490  "OMIT_SCHEMA_PRAGMAS",
11491#endif
11492#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11493  "OMIT_SCHEMA_VERSION_PRAGMAS",
11494#endif
11495#ifdef SQLITE_OMIT_SHARED_CACHE
11496  "OMIT_SHARED_CACHE",
11497#endif
11498#ifdef SQLITE_OMIT_SUBQUERY
11499  "OMIT_SUBQUERY",
11500#endif
11501#ifdef SQLITE_OMIT_TCL_VARIABLE
11502  "OMIT_TCL_VARIABLE",
11503#endif
11504#ifdef SQLITE_OMIT_TEMPDB
11505  "OMIT_TEMPDB",
11506#endif
11507#ifdef SQLITE_OMIT_TRACE
11508  "OMIT_TRACE",
11509#endif
11510#ifdef SQLITE_OMIT_TRIGGER
11511  "OMIT_TRIGGER",
11512#endif
11513#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11514  "OMIT_TRUNCATE_OPTIMIZATION",
11515#endif
11516#ifdef SQLITE_OMIT_UTF16
11517  "OMIT_UTF16",
11518#endif
11519#ifdef SQLITE_OMIT_VACUUM
11520  "OMIT_VACUUM",
11521#endif
11522#ifdef SQLITE_OMIT_VIEW
11523  "OMIT_VIEW",
11524#endif
11525#ifdef SQLITE_OMIT_VIRTUALTABLE
11526  "OMIT_VIRTUALTABLE",
11527#endif
11528#ifdef SQLITE_OMIT_WAL
11529  "OMIT_WAL",
11530#endif
11531#ifdef SQLITE_OMIT_WSD
11532  "OMIT_WSD",
11533#endif
11534#ifdef SQLITE_OMIT_XFER_OPT
11535  "OMIT_XFER_OPT",
11536#endif
11537#ifdef SQLITE_PERFORMANCE_TRACE
11538  "PERFORMANCE_TRACE",
11539#endif
11540#ifdef SQLITE_PROXY_DEBUG
11541  "PROXY_DEBUG",
11542#endif
11543#ifdef SQLITE_SECURE_DELETE
11544  "SECURE_DELETE",
11545#endif
11546#ifdef SQLITE_SMALL_STACK
11547  "SMALL_STACK",
11548#endif
11549#ifdef SQLITE_SOUNDEX
11550  "SOUNDEX",
11551#endif
11552#ifdef SQLITE_TCL
11553  "TCL",
11554#endif
11555#ifdef SQLITE_TEMP_STORE
11556  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11557#endif
11558#ifdef SQLITE_TEST
11559  "TEST",
11560#endif
11561#ifdef SQLITE_THREADSAFE
11562  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11563#endif
11564#ifdef SQLITE_USE_ALLOCA
11565  "USE_ALLOCA",
11566#endif
11567#ifdef SQLITE_ZERO_MALLOC
11568  "ZERO_MALLOC"
11569#endif
11570};
11571
11572/*
11573** Given the name of a compile-time option, return true if that option
11574** was used and false if not.
11575**
11576** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11577** is not required for a match.
11578*/
11579SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11580  int i, n;
11581  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11582  n = sqlite3Strlen30(zOptName);
11583
11584  /* Since ArraySize(azCompileOpt) is normally in single digits, a
11585  ** linear search is adequate.  No need for a binary search. */
11586  for(i=0; i<ArraySize(azCompileOpt); i++){
11587    if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11588       && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11589  }
11590  return 0;
11591}
11592
11593/*
11594** Return the N-th compile-time option string.  If N is out of range,
11595** return a NULL pointer.
11596*/
11597SQLITE_API const char *sqlite3_compileoption_get(int N){
11598  if( N>=0 && N<ArraySize(azCompileOpt) ){
11599    return azCompileOpt[N];
11600  }
11601  return 0;
11602}
11603
11604#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11605
11606/************** End of ctime.c ***********************************************/
11607/************** Begin file status.c ******************************************/
11608/*
11609** 2008 June 18
11610**
11611** The author disclaims copyright to this source code.  In place of
11612** a legal notice, here is a blessing:
11613**
11614**    May you do good and not evil.
11615**    May you find forgiveness for yourself and forgive others.
11616**    May you share freely, never taking more than you give.
11617**
11618*************************************************************************
11619**
11620** This module implements the sqlite3_status() interface and related
11621** functionality.
11622*/
11623/************** Include vdbeInt.h in the middle of status.c ******************/
11624/************** Begin file vdbeInt.h *****************************************/
11625/*
11626** 2003 September 6
11627**
11628** The author disclaims copyright to this source code.  In place of
11629** a legal notice, here is a blessing:
11630**
11631**    May you do good and not evil.
11632**    May you find forgiveness for yourself and forgive others.
11633**    May you share freely, never taking more than you give.
11634**
11635*************************************************************************
11636** This is the header file for information that is private to the
11637** VDBE.  This information used to all be at the top of the single
11638** source code file "vdbe.c".  When that file became too big (over
11639** 6000 lines long) it was split up into several smaller files and
11640** this header information was factored out.
11641*/
11642#ifndef _VDBEINT_H_
11643#define _VDBEINT_H_
11644
11645/*
11646** SQL is translated into a sequence of instructions to be
11647** executed by a virtual machine.  Each instruction is an instance
11648** of the following structure.
11649*/
11650typedef struct VdbeOp Op;
11651
11652/*
11653** Boolean values
11654*/
11655typedef unsigned char Bool;
11656
11657/*
11658** A cursor is a pointer into a single BTree within a database file.
11659** The cursor can seek to a BTree entry with a particular key, or
11660** loop over all entries of the Btree.  You can also insert new BTree
11661** entries or retrieve the key or data from the entry that the cursor
11662** is currently pointing to.
11663**
11664** Every cursor that the virtual machine has open is represented by an
11665** instance of the following structure.
11666**
11667** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
11668** really a single row that represents the NEW or OLD pseudo-table of
11669** a row trigger.  The data for the row is stored in VdbeCursor.pData and
11670** the rowid is in VdbeCursor.iKey.
11671*/
11672struct VdbeCursor {
11673  BtCursor *pCursor;    /* The cursor structure of the backend */
11674  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
11675  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
11676  Bool zeroed;          /* True if zeroed out and ready for reuse */
11677  Bool rowidIsValid;    /* True if lastRowid is valid */
11678  Bool atFirst;         /* True if pointing to first entry */
11679  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
11680  Bool nullRow;         /* True if pointing to a row with no data */
11681  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
11682  Bool isTable;         /* True if a table requiring integer keys */
11683  Bool isIndex;         /* True if an index containing keys only - no data */
11684  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
11685  Btree *pBt;           /* Separate file holding temporary table */
11686  int pseudoTableReg;   /* Register holding pseudotable content. */
11687  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
11688  int nField;           /* Number of fields in the header */
11689  i64 seqCount;         /* Sequence counter */
11690  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
11691  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
11692
11693  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
11694  ** OP_IsUnique opcode on this cursor. */
11695  int seekResult;
11696
11697  /* Cached information about the header for the data record that the
11698  ** cursor is currently pointing to.  Only valid if cacheStatus matches
11699  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
11700  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
11701  ** the cache is out of date.
11702  **
11703  ** aRow might point to (ephemeral) data for the current row, or it might
11704  ** be NULL.
11705  */
11706  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
11707  int payloadSize;      /* Total number of bytes in the record */
11708  u32 *aType;           /* Type values for all entries in the record */
11709  u32 *aOffset;         /* Cached offsets to the start of each columns data */
11710  u8 *aRow;             /* Data for the current row, if all on one page */
11711};
11712typedef struct VdbeCursor VdbeCursor;
11713
11714/*
11715** When a sub-program is executed (OP_Program), a structure of this type
11716** is allocated to store the current value of the program counter, as
11717** well as the current memory cell array and various other frame specific
11718** values stored in the Vdbe struct. When the sub-program is finished,
11719** these values are copied back to the Vdbe from the VdbeFrame structure,
11720** restoring the state of the VM to as it was before the sub-program
11721** began executing.
11722**
11723** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
11724** is the parent of the current frame, or zero if the current frame
11725** is the main Vdbe program.
11726*/
11727typedef struct VdbeFrame VdbeFrame;
11728struct VdbeFrame {
11729  Vdbe *v;                /* VM this frame belongs to */
11730  int pc;                 /* Program Counter */
11731  Op *aOp;                /* Program instructions */
11732  int nOp;                /* Size of aOp array */
11733  Mem *aMem;              /* Array of memory cells */
11734  int nMem;               /* Number of entries in aMem */
11735  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
11736  u16 nCursor;            /* Number of entries in apCsr */
11737  void *token;            /* Copy of SubProgram.token */
11738  int nChildMem;          /* Number of memory cells for child frame */
11739  int nChildCsr;          /* Number of cursors for child frame */
11740  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
11741  int nChange;            /* Statement changes (Vdbe.nChanges)     */
11742  VdbeFrame *pParent;     /* Parent of this frame */
11743};
11744
11745#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
11746
11747/*
11748** A value for VdbeCursor.cacheValid that means the cache is always invalid.
11749*/
11750#define CACHE_STALE 0
11751
11752/*
11753** Internally, the vdbe manipulates nearly all SQL values as Mem
11754** structures. Each Mem struct may cache multiple representations (string,
11755** integer etc.) of the same value.  A value (and therefore Mem structure)
11756** has the following properties:
11757**
11758** Each value has a manifest type. The manifest type of the value stored
11759** in a Mem struct is returned by the MemType(Mem*) macro. The type is
11760** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
11761** SQLITE_BLOB.
11762*/
11763struct Mem {
11764  union {
11765    i64 i;              /* Integer value. */
11766    int nZero;          /* Used when bit MEM_Zero is set in flags */
11767    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
11768    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
11769    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
11770  } u;
11771  double r;           /* Real value */
11772  sqlite3 *db;        /* The associated database connection */
11773  char *z;            /* String or BLOB value */
11774  int n;              /* Number of characters in string value, excluding '\0' */
11775  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
11776  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
11777  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
11778  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
11779  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
11780};
11781
11782/* One or more of the following flags are set to indicate the validOK
11783** representations of the value stored in the Mem struct.
11784**
11785** If the MEM_Null flag is set, then the value is an SQL NULL value.
11786** No other flags may be set in this case.
11787**
11788** If the MEM_Str flag is set then Mem.z points at a string representation.
11789** Usually this is encoded in the same unicode encoding as the main
11790** database (see below for exceptions). If the MEM_Term flag is also
11791** set, then the string is nul terminated. The MEM_Int and MEM_Real
11792** flags may coexist with the MEM_Str flag.
11793**
11794** Multiple of these values can appear in Mem.flags.  But only one
11795** at a time can appear in Mem.type.
11796*/
11797#define MEM_Null      0x0001   /* Value is NULL */
11798#define MEM_Str       0x0002   /* Value is a string */
11799#define MEM_Int       0x0004   /* Value is an integer */
11800#define MEM_Real      0x0008   /* Value is a real number */
11801#define MEM_Blob      0x0010   /* Value is a BLOB */
11802#define MEM_RowSet    0x0020   /* Value is a RowSet object */
11803#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
11804#define MEM_TypeMask  0x00ff   /* Mask of type bits */
11805
11806/* Whenever Mem contains a valid string or blob representation, one of
11807** the following flags must be set to determine the memory management
11808** policy for Mem.z.  The MEM_Term flag tells us whether or not the
11809** string is \000 or \u0000 terminated
11810*/
11811#define MEM_Term      0x0200   /* String rep is nul terminated */
11812#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
11813#define MEM_Static    0x0800   /* Mem.z points to a static string */
11814#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
11815#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
11816#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
11817
11818#ifdef SQLITE_OMIT_INCRBLOB
11819  #undef MEM_Zero
11820  #define MEM_Zero 0x0000
11821#endif
11822
11823
11824/*
11825** Clear any existing type flags from a Mem and replace them with f
11826*/
11827#define MemSetTypeFlag(p, f) \
11828   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
11829
11830
11831/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
11832** additional information about auxiliary information bound to arguments
11833** of the function.  This is used to implement the sqlite3_get_auxdata()
11834** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
11835** that can be associated with a constant argument to a function.  This
11836** allows functions such as "regexp" to compile their constant regular
11837** expression argument once and reused the compiled code for multiple
11838** invocations.
11839*/
11840struct VdbeFunc {
11841  FuncDef *pFunc;               /* The definition of the function */
11842  int nAux;                     /* Number of entries allocated for apAux[] */
11843  struct AuxData {
11844    void *pAux;                   /* Aux data for the i-th argument */
11845    void (*xDelete)(void *);      /* Destructor for the aux data */
11846  } apAux[1];                   /* One slot for each function argument */
11847};
11848
11849/*
11850** The "context" argument for a installable function.  A pointer to an
11851** instance of this structure is the first argument to the routines used
11852** implement the SQL functions.
11853**
11854** There is a typedef for this structure in sqlite.h.  So all routines,
11855** even the public interface to SQLite, can use a pointer to this structure.
11856** But this file is the only place where the internal details of this
11857** structure are known.
11858**
11859** This structure is defined inside of vdbeInt.h because it uses substructures
11860** (Mem) which are only defined there.
11861*/
11862struct sqlite3_context {
11863  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
11864  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
11865  Mem s;                /* The return value is stored here */
11866  Mem *pMem;            /* Memory cell used to store aggregate context */
11867  int isError;          /* Error code returned by the function. */
11868  CollSeq *pColl;       /* Collating sequence */
11869};
11870
11871/*
11872** A Set structure is used for quick testing to see if a value
11873** is part of a small set.  Sets are used to implement code like
11874** this:
11875**            x.y IN ('hi','hoo','hum')
11876*/
11877typedef struct Set Set;
11878struct Set {
11879  Hash hash;             /* A set is just a hash table */
11880  HashElem *prev;        /* Previously accessed hash elemen */
11881};
11882
11883/*
11884** An instance of the virtual machine.  This structure contains the complete
11885** state of the virtual machine.
11886**
11887** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
11888** is really a pointer to an instance of this structure.
11889**
11890** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
11891** any virtual table method invocations made by the vdbe program. It is
11892** set to 2 for xDestroy method calls and 1 for all other methods. This
11893** variable is used for two purposes: to allow xDestroy methods to execute
11894** "DROP TABLE" statements and to prevent some nasty side effects of
11895** malloc failure when SQLite is invoked recursively by a virtual table
11896** method function.
11897*/
11898struct Vdbe {
11899  sqlite3 *db;            /* The database connection that owns this statement */
11900  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
11901  int nOp;                /* Number of instructions in the program */
11902  int nOpAlloc;           /* Number of slots allocated for aOp[] */
11903  Op *aOp;                /* Space to hold the virtual machine's program */
11904  int nLabel;             /* Number of labels used */
11905  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
11906  int *aLabel;            /* Space to hold the labels */
11907  Mem **apArg;            /* Arguments to currently executing user function */
11908  Mem *aColName;          /* Column names to return */
11909  Mem *pResultSet;        /* Pointer to an array of results */
11910  u16 nResColumn;         /* Number of columns in one row of the result set */
11911  u16 nCursor;            /* Number of slots in apCsr[] */
11912  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
11913  u8 errorAction;         /* Recovery action to do in case of an error */
11914  u8 okVar;               /* True if azVar[] has been initialized */
11915  ynVar nVar;             /* Number of entries in aVar[] */
11916  Mem *aVar;              /* Values for the OP_Variable opcode. */
11917  char **azVar;           /* Name of variables */
11918  u32 magic;              /* Magic number for sanity checking */
11919  int nMem;               /* Number of memory locations currently allocated */
11920  Mem *aMem;              /* The memory locations */
11921  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
11922  int pc;                 /* The program counter */
11923  int rc;                 /* Value to return */
11924  char *zErrMsg;          /* Error message written here */
11925  u8 explain;             /* True if EXPLAIN present on SQL command */
11926  u8 changeCntOn;         /* True to update the change-counter */
11927  u8 expired;             /* True if the VM needs to be recompiled */
11928  u8 runOnlyOnce;         /* Automatically expire on reset */
11929  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
11930  u8 inVtabMethod;        /* See comments above */
11931  u8 usesStmtJournal;     /* True if uses a statement journal */
11932  u8 readOnly;            /* True for read-only statements */
11933  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
11934  int nChange;            /* Number of db changes made since last reset */
11935  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
11936  i64 startTime;          /* Time when query started - used for profiling */
11937  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
11938  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
11939  char *zSql;             /* Text of the SQL statement that generated this */
11940  void *pFree;            /* Free this when deleting the vdbe */
11941  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
11942  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
11943  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
11944#ifdef SQLITE_DEBUG
11945  FILE *trace;            /* Write an execution trace here, if not NULL */
11946#endif
11947  VdbeFrame *pFrame;      /* Parent frame */
11948  int nFrame;             /* Number of frames in pFrame list */
11949  u32 expmask;            /* Binding to these vars invalidates VM */
11950  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
11951};
11952
11953/*
11954** The following are allowed values for Vdbe.magic
11955*/
11956#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
11957#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
11958#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
11959#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
11960
11961/*
11962** Function prototypes
11963*/
11964SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
11965void sqliteVdbePopStack(Vdbe*,int);
11966SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
11967#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
11968SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
11969#endif
11970SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
11971SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
11972SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
11973SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
11974SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
11975
11976int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
11977SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
11978SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
11979SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
11980SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
11981SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
11982SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
11983SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
11984SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
11985SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
11986SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
11987SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
11988SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
11989SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
11990SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
11991#ifdef SQLITE_OMIT_FLOATING_POINT
11992# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
11993#else
11994SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
11995#endif
11996SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
11997SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
11998SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
11999SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12000SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12001SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12002SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12003SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12004SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12005SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12006SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12007SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12008SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12009SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12010SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12011SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12012SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12013SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12014SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12015SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12016SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12017
12018#ifndef SQLITE_OMIT_FOREIGN_KEY
12019SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12020#else
12021# define sqlite3VdbeCheckFk(p,i) 0
12022#endif
12023
12024#ifndef SQLITE_OMIT_SHARED_CACHE
12025SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
12026#else
12027# define sqlite3VdbeMutexArrayEnter(p)
12028#endif
12029
12030SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12031#ifdef SQLITE_DEBUG
12032SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12033SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12034#endif
12035SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12036
12037#ifndef SQLITE_OMIT_INCRBLOB
12038SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12039#else
12040  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12041#endif
12042
12043#endif /* !defined(_VDBEINT_H_) */
12044
12045/************** End of vdbeInt.h *********************************************/
12046/************** Continuing where we left off in status.c *********************/
12047
12048/*
12049** Variables in which to record status information.
12050*/
12051typedef struct sqlite3StatType sqlite3StatType;
12052static SQLITE_WSD struct sqlite3StatType {
12053  int nowValue[10];         /* Current value */
12054  int mxValue[10];          /* Maximum value */
12055} sqlite3Stat = { {0,}, {0,} };
12056
12057
12058/* The "wsdStat" macro will resolve to the status information
12059** state vector.  If writable static data is unsupported on the target,
12060** we have to locate the state vector at run-time.  In the more common
12061** case where writable static data is supported, wsdStat can refer directly
12062** to the "sqlite3Stat" state vector declared above.
12063*/
12064#ifdef SQLITE_OMIT_WSD
12065# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12066# define wsdStat x[0]
12067#else
12068# define wsdStatInit
12069# define wsdStat sqlite3Stat
12070#endif
12071
12072/*
12073** Return the current value of a status parameter.
12074*/
12075SQLITE_PRIVATE int sqlite3StatusValue(int op){
12076  wsdStatInit;
12077  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12078  return wsdStat.nowValue[op];
12079}
12080
12081/*
12082** Add N to the value of a status record.  It is assumed that the
12083** caller holds appropriate locks.
12084*/
12085SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12086  wsdStatInit;
12087  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12088  wsdStat.nowValue[op] += N;
12089  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12090    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12091  }
12092}
12093
12094/*
12095** Set the value of a status to X.
12096*/
12097SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12098  wsdStatInit;
12099  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12100  wsdStat.nowValue[op] = X;
12101  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12102    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12103  }
12104}
12105
12106/*
12107** Query status information.
12108**
12109** This implementation assumes that reading or writing an aligned
12110** 32-bit integer is an atomic operation.  If that assumption is not true,
12111** then this routine is not threadsafe.
12112*/
12113SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12114  wsdStatInit;
12115  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12116    return SQLITE_MISUSE_BKPT;
12117  }
12118  *pCurrent = wsdStat.nowValue[op];
12119  *pHighwater = wsdStat.mxValue[op];
12120  if( resetFlag ){
12121    wsdStat.mxValue[op] = wsdStat.nowValue[op];
12122  }
12123  return SQLITE_OK;
12124}
12125
12126/*
12127** Query status information for a single database connection
12128*/
12129SQLITE_API int sqlite3_db_status(
12130  sqlite3 *db,          /* The database connection whose status is desired */
12131  int op,               /* Status verb */
12132  int *pCurrent,        /* Write current value here */
12133  int *pHighwater,      /* Write high-water mark here */
12134  int resetFlag         /* Reset high-water mark if true */
12135){
12136  int rc = SQLITE_OK;   /* Return code */
12137  sqlite3_mutex_enter(db->mutex);
12138  switch( op ){
12139    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12140      *pCurrent = db->lookaside.nOut;
12141      *pHighwater = db->lookaside.mxOut;
12142      if( resetFlag ){
12143        db->lookaside.mxOut = db->lookaside.nOut;
12144      }
12145      break;
12146    }
12147
12148    /*
12149    ** Return an approximation for the amount of memory currently used
12150    ** by all pagers associated with the given database connection.  The
12151    ** highwater mark is meaningless and is returned as zero.
12152    */
12153    case SQLITE_DBSTATUS_CACHE_USED: {
12154      int totalUsed = 0;
12155      int i;
12156      sqlite3BtreeEnterAll(db);
12157      for(i=0; i<db->nDb; i++){
12158        Btree *pBt = db->aDb[i].pBt;
12159        if( pBt ){
12160          Pager *pPager = sqlite3BtreePager(pBt);
12161          totalUsed += sqlite3PagerMemUsed(pPager);
12162        }
12163      }
12164      sqlite3BtreeLeaveAll(db);
12165      *pCurrent = totalUsed;
12166      *pHighwater = 0;
12167      break;
12168    }
12169
12170    /*
12171    ** *pCurrent gets an accurate estimate of the amount of memory used
12172    ** to store the schema for all databases (main, temp, and any ATTACHed
12173    ** databases.  *pHighwater is set to zero.
12174    */
12175    case SQLITE_DBSTATUS_SCHEMA_USED: {
12176      int i;                      /* Used to iterate through schemas */
12177      int nByte = 0;              /* Used to accumulate return value */
12178
12179      db->pnBytesFreed = &nByte;
12180      for(i=0; i<db->nDb; i++){
12181        Schema *pSchema = db->aDb[i].pSchema;
12182        if( ALWAYS(pSchema!=0) ){
12183          HashElem *p;
12184
12185          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12186              pSchema->tblHash.count
12187            + pSchema->trigHash.count
12188            + pSchema->idxHash.count
12189            + pSchema->fkeyHash.count
12190          );
12191          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12192          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12193          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12194          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12195
12196          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12197            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12198          }
12199          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12200            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12201          }
12202        }
12203      }
12204      db->pnBytesFreed = 0;
12205
12206      *pHighwater = 0;
12207      *pCurrent = nByte;
12208      break;
12209    }
12210
12211    /*
12212    ** *pCurrent gets an accurate estimate of the amount of memory used
12213    ** to store all prepared statements.
12214    ** *pHighwater is set to zero.
12215    */
12216    case SQLITE_DBSTATUS_STMT_USED: {
12217      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12218      int nByte = 0;              /* Used to accumulate return value */
12219
12220      db->pnBytesFreed = &nByte;
12221      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12222        sqlite3VdbeDeleteObject(db, pVdbe);
12223      }
12224      db->pnBytesFreed = 0;
12225
12226      *pHighwater = 0;
12227      *pCurrent = nByte;
12228
12229      break;
12230    }
12231
12232    default: {
12233      rc = SQLITE_ERROR;
12234    }
12235  }
12236  sqlite3_mutex_leave(db->mutex);
12237  return rc;
12238}
12239
12240/************** End of status.c **********************************************/
12241/************** Begin file date.c ********************************************/
12242/*
12243** 2003 October 31
12244**
12245** The author disclaims copyright to this source code.  In place of
12246** a legal notice, here is a blessing:
12247**
12248**    May you do good and not evil.
12249**    May you find forgiveness for yourself and forgive others.
12250**    May you share freely, never taking more than you give.
12251**
12252*************************************************************************
12253** This file contains the C functions that implement date and time
12254** functions for SQLite.
12255**
12256** There is only one exported symbol in this file - the function
12257** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12258** All other code has file scope.
12259**
12260** SQLite processes all times and dates as Julian Day numbers.  The
12261** dates and times are stored as the number of days since noon
12262** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12263** calendar system.
12264**
12265** 1970-01-01 00:00:00 is JD 2440587.5
12266** 2000-01-01 00:00:00 is JD 2451544.5
12267**
12268** This implemention requires years to be expressed as a 4-digit number
12269** which means that only dates between 0000-01-01 and 9999-12-31 can
12270** be represented, even though julian day numbers allow a much wider
12271** range of dates.
12272**
12273** The Gregorian calendar system is used for all dates and times,
12274** even those that predate the Gregorian calendar.  Historians usually
12275** use the Julian calendar for dates prior to 1582-10-15 and for some
12276** dates afterwards, depending on locale.  Beware of this difference.
12277**
12278** The conversion algorithms are implemented based on descriptions
12279** in the following text:
12280**
12281**      Jean Meeus
12282**      Astronomical Algorithms, 2nd Edition, 1998
12283**      ISBM 0-943396-61-1
12284**      Willmann-Bell, Inc
12285**      Richmond, Virginia (USA)
12286*/
12287#include <time.h>
12288
12289#ifndef SQLITE_OMIT_DATETIME_FUNCS
12290
12291/*
12292** On recent Windows platforms, the localtime_s() function is available
12293** as part of the "Secure CRT". It is essentially equivalent to
12294** localtime_r() available under most POSIX platforms, except that the
12295** order of the parameters is reversed.
12296**
12297** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12298**
12299** If the user has not indicated to use localtime_r() or localtime_s()
12300** already, check for an MSVC build environment that provides
12301** localtime_s().
12302*/
12303#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12304     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12305#define HAVE_LOCALTIME_S 1
12306#endif
12307
12308/*
12309** A structure for holding a single date and time.
12310*/
12311typedef struct DateTime DateTime;
12312struct DateTime {
12313  sqlite3_int64 iJD; /* The julian day number times 86400000 */
12314  int Y, M, D;       /* Year, month, and day */
12315  int h, m;          /* Hour and minutes */
12316  int tz;            /* Timezone offset in minutes */
12317  double s;          /* Seconds */
12318  char validYMD;     /* True (1) if Y,M,D are valid */
12319  char validHMS;     /* True (1) if h,m,s are valid */
12320  char validJD;      /* True (1) if iJD is valid */
12321  char validTZ;      /* True (1) if tz is valid */
12322};
12323
12324
12325/*
12326** Convert zDate into one or more integers.  Additional arguments
12327** come in groups of 5 as follows:
12328**
12329**       N       number of digits in the integer
12330**       min     minimum allowed value of the integer
12331**       max     maximum allowed value of the integer
12332**       nextC   first character after the integer
12333**       pVal    where to write the integers value.
12334**
12335** Conversions continue until one with nextC==0 is encountered.
12336** The function returns the number of successful conversions.
12337*/
12338static int getDigits(const char *zDate, ...){
12339  va_list ap;
12340  int val;
12341  int N;
12342  int min;
12343  int max;
12344  int nextC;
12345  int *pVal;
12346  int cnt = 0;
12347  va_start(ap, zDate);
12348  do{
12349    N = va_arg(ap, int);
12350    min = va_arg(ap, int);
12351    max = va_arg(ap, int);
12352    nextC = va_arg(ap, int);
12353    pVal = va_arg(ap, int*);
12354    val = 0;
12355    while( N-- ){
12356      if( !sqlite3Isdigit(*zDate) ){
12357        goto end_getDigits;
12358      }
12359      val = val*10 + *zDate - '0';
12360      zDate++;
12361    }
12362    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12363      goto end_getDigits;
12364    }
12365    *pVal = val;
12366    zDate++;
12367    cnt++;
12368  }while( nextC );
12369end_getDigits:
12370  va_end(ap);
12371  return cnt;
12372}
12373
12374/*
12375** Read text from z[] and convert into a floating point number.  Return
12376** the number of digits converted.
12377*/
12378#define getValue sqlite3AtoF
12379
12380/*
12381** Parse a timezone extension on the end of a date-time.
12382** The extension is of the form:
12383**
12384**        (+/-)HH:MM
12385**
12386** Or the "zulu" notation:
12387**
12388**        Z
12389**
12390** If the parse is successful, write the number of minutes
12391** of change in p->tz and return 0.  If a parser error occurs,
12392** return non-zero.
12393**
12394** A missing specifier is not considered an error.
12395*/
12396static int parseTimezone(const char *zDate, DateTime *p){
12397  int sgn = 0;
12398  int nHr, nMn;
12399  int c;
12400  while( sqlite3Isspace(*zDate) ){ zDate++; }
12401  p->tz = 0;
12402  c = *zDate;
12403  if( c=='-' ){
12404    sgn = -1;
12405  }else if( c=='+' ){
12406    sgn = +1;
12407  }else if( c=='Z' || c=='z' ){
12408    zDate++;
12409    goto zulu_time;
12410  }else{
12411    return c!=0;
12412  }
12413  zDate++;
12414  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12415    return 1;
12416  }
12417  zDate += 5;
12418  p->tz = sgn*(nMn + nHr*60);
12419zulu_time:
12420  while( sqlite3Isspace(*zDate) ){ zDate++; }
12421  return *zDate!=0;
12422}
12423
12424/*
12425** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
12426** The HH, MM, and SS must each be exactly 2 digits.  The
12427** fractional seconds FFFF can be one or more digits.
12428**
12429** Return 1 if there is a parsing error and 0 on success.
12430*/
12431static int parseHhMmSs(const char *zDate, DateTime *p){
12432  int h, m, s;
12433  double ms = 0.0;
12434  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
12435    return 1;
12436  }
12437  zDate += 5;
12438  if( *zDate==':' ){
12439    zDate++;
12440    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
12441      return 1;
12442    }
12443    zDate += 2;
12444    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
12445      double rScale = 1.0;
12446      zDate++;
12447      while( sqlite3Isdigit(*zDate) ){
12448        ms = ms*10.0 + *zDate - '0';
12449        rScale *= 10.0;
12450        zDate++;
12451      }
12452      ms /= rScale;
12453    }
12454  }else{
12455    s = 0;
12456  }
12457  p->validJD = 0;
12458  p->validHMS = 1;
12459  p->h = h;
12460  p->m = m;
12461  p->s = s + ms;
12462  if( parseTimezone(zDate, p) ) return 1;
12463  p->validTZ = (p->tz!=0)?1:0;
12464  return 0;
12465}
12466
12467/*
12468** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
12469** that the YYYY-MM-DD is according to the Gregorian calendar.
12470**
12471** Reference:  Meeus page 61
12472*/
12473static void computeJD(DateTime *p){
12474  int Y, M, D, A, B, X1, X2;
12475
12476  if( p->validJD ) return;
12477  if( p->validYMD ){
12478    Y = p->Y;
12479    M = p->M;
12480    D = p->D;
12481  }else{
12482    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
12483    M = 1;
12484    D = 1;
12485  }
12486  if( M<=2 ){
12487    Y--;
12488    M += 12;
12489  }
12490  A = Y/100;
12491  B = 2 - A + (A/4);
12492  X1 = 36525*(Y+4716)/100;
12493  X2 = 306001*(M+1)/10000;
12494  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
12495  p->validJD = 1;
12496  if( p->validHMS ){
12497    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
12498    if( p->validTZ ){
12499      p->iJD -= p->tz*60000;
12500      p->validYMD = 0;
12501      p->validHMS = 0;
12502      p->validTZ = 0;
12503    }
12504  }
12505}
12506
12507/*
12508** Parse dates of the form
12509**
12510**     YYYY-MM-DD HH:MM:SS.FFF
12511**     YYYY-MM-DD HH:MM:SS
12512**     YYYY-MM-DD HH:MM
12513**     YYYY-MM-DD
12514**
12515** Write the result into the DateTime structure and return 0
12516** on success and 1 if the input string is not a well-formed
12517** date.
12518*/
12519static int parseYyyyMmDd(const char *zDate, DateTime *p){
12520  int Y, M, D, neg;
12521
12522  if( zDate[0]=='-' ){
12523    zDate++;
12524    neg = 1;
12525  }else{
12526    neg = 0;
12527  }
12528  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
12529    return 1;
12530  }
12531  zDate += 10;
12532  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
12533  if( parseHhMmSs(zDate, p)==0 ){
12534    /* We got the time */
12535  }else if( *zDate==0 ){
12536    p->validHMS = 0;
12537  }else{
12538    return 1;
12539  }
12540  p->validJD = 0;
12541  p->validYMD = 1;
12542  p->Y = neg ? -Y : Y;
12543  p->M = M;
12544  p->D = D;
12545  if( p->validTZ ){
12546    computeJD(p);
12547  }
12548  return 0;
12549}
12550
12551/*
12552** Set the time to the current time reported by the VFS
12553*/
12554static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12555  sqlite3 *db = sqlite3_context_db_handle(context);
12556  sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12557  p->validJD = 1;
12558}
12559
12560/*
12561** Attempt to parse the given string into a Julian Day Number.  Return
12562** the number of errors.
12563**
12564** The following are acceptable forms for the input string:
12565**
12566**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12567**      DDDD.DD
12568**      now
12569**
12570** In the first form, the +/-HH:MM is always optional.  The fractional
12571** seconds extension (the ".FFF") is optional.  The seconds portion
12572** (":SS.FFF") is option.  The year and date can be omitted as long
12573** as there is a time string.  The time string can be omitted as long
12574** as there is a year and date.
12575*/
12576static int parseDateOrTime(
12577  sqlite3_context *context,
12578  const char *zDate,
12579  DateTime *p
12580){
12581  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
12582  if( parseYyyyMmDd(zDate,p)==0 ){
12583    return 0;
12584  }else if( parseHhMmSs(zDate, p)==0 ){
12585    return 0;
12586  }else if( sqlite3StrICmp(zDate,"now")==0){
12587    setDateTimeToCurrent(context, p);
12588    return 0;
12589  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
12590    double r;
12591    getValue(zDate, &r);
12592    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12593    p->validJD = 1;
12594    return 0;
12595  }
12596  return 1;
12597}
12598
12599/*
12600** Compute the Year, Month, and Day from the julian day number.
12601*/
12602static void computeYMD(DateTime *p){
12603  int Z, A, B, C, D, E, X1;
12604  if( p->validYMD ) return;
12605  if( !p->validJD ){
12606    p->Y = 2000;
12607    p->M = 1;
12608    p->D = 1;
12609  }else{
12610    Z = (int)((p->iJD + 43200000)/86400000);
12611    A = (int)((Z - 1867216.25)/36524.25);
12612    A = Z + 1 + A - (A/4);
12613    B = A + 1524;
12614    C = (int)((B - 122.1)/365.25);
12615    D = (36525*C)/100;
12616    E = (int)((B-D)/30.6001);
12617    X1 = (int)(30.6001*E);
12618    p->D = B - D - X1;
12619    p->M = E<14 ? E-1 : E-13;
12620    p->Y = p->M>2 ? C - 4716 : C - 4715;
12621  }
12622  p->validYMD = 1;
12623}
12624
12625/*
12626** Compute the Hour, Minute, and Seconds from the julian day number.
12627*/
12628static void computeHMS(DateTime *p){
12629  int s;
12630  if( p->validHMS ) return;
12631  computeJD(p);
12632  s = (int)((p->iJD + 43200000) % 86400000);
12633  p->s = s/1000.0;
12634  s = (int)p->s;
12635  p->s -= s;
12636  p->h = s/3600;
12637  s -= p->h*3600;
12638  p->m = s/60;
12639  p->s += s - p->m*60;
12640  p->validHMS = 1;
12641}
12642
12643/*
12644** Compute both YMD and HMS
12645*/
12646static void computeYMD_HMS(DateTime *p){
12647  computeYMD(p);
12648  computeHMS(p);
12649}
12650
12651/*
12652** Clear the YMD and HMS and the TZ
12653*/
12654static void clearYMD_HMS_TZ(DateTime *p){
12655  p->validYMD = 0;
12656  p->validHMS = 0;
12657  p->validTZ = 0;
12658}
12659
12660#ifndef SQLITE_OMIT_LOCALTIME
12661/*
12662** Compute the difference (in milliseconds)
12663** between localtime and UTC (a.k.a. GMT)
12664** for the time value p where p is in UTC.
12665*/
12666static sqlite3_int64 localtimeOffset(DateTime *p){
12667  DateTime x, y;
12668  time_t t;
12669  x = *p;
12670  computeYMD_HMS(&x);
12671  if( x.Y<1971 || x.Y>=2038 ){
12672    x.Y = 2000;
12673    x.M = 1;
12674    x.D = 1;
12675    x.h = 0;
12676    x.m = 0;
12677    x.s = 0.0;
12678  } else {
12679    int s = (int)(x.s + 0.5);
12680    x.s = s;
12681  }
12682  x.tz = 0;
12683  x.validJD = 0;
12684  computeJD(&x);
12685  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
12686#ifdef HAVE_LOCALTIME_R
12687  {
12688    struct tm sLocal;
12689    localtime_r(&t, &sLocal);
12690    y.Y = sLocal.tm_year + 1900;
12691    y.M = sLocal.tm_mon + 1;
12692    y.D = sLocal.tm_mday;
12693    y.h = sLocal.tm_hour;
12694    y.m = sLocal.tm_min;
12695    y.s = sLocal.tm_sec;
12696  }
12697#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
12698  {
12699    struct tm sLocal;
12700    localtime_s(&sLocal, &t);
12701    y.Y = sLocal.tm_year + 1900;
12702    y.M = sLocal.tm_mon + 1;
12703    y.D = sLocal.tm_mday;
12704    y.h = sLocal.tm_hour;
12705    y.m = sLocal.tm_min;
12706    y.s = sLocal.tm_sec;
12707  }
12708#else
12709  {
12710    struct tm *pTm;
12711    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12712    pTm = localtime(&t);
12713    y.Y = pTm->tm_year + 1900;
12714    y.M = pTm->tm_mon + 1;
12715    y.D = pTm->tm_mday;
12716    y.h = pTm->tm_hour;
12717    y.m = pTm->tm_min;
12718    y.s = pTm->tm_sec;
12719    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12720  }
12721#endif
12722  y.validYMD = 1;
12723  y.validHMS = 1;
12724  y.validJD = 0;
12725  y.validTZ = 0;
12726  computeJD(&y);
12727  return y.iJD - x.iJD;
12728}
12729#endif /* SQLITE_OMIT_LOCALTIME */
12730
12731/*
12732** Process a modifier to a date-time stamp.  The modifiers are
12733** as follows:
12734**
12735**     NNN days
12736**     NNN hours
12737**     NNN minutes
12738**     NNN.NNNN seconds
12739**     NNN months
12740**     NNN years
12741**     start of month
12742**     start of year
12743**     start of week
12744**     start of day
12745**     weekday N
12746**     unixepoch
12747**     localtime
12748**     utc
12749**
12750** Return 0 on success and 1 if there is any kind of error.
12751*/
12752static int parseModifier(const char *zMod, DateTime *p){
12753  int rc = 1;
12754  int n;
12755  double r;
12756  char *z, zBuf[30];
12757  z = zBuf;
12758  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
12759    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
12760  }
12761  z[n] = 0;
12762  switch( z[0] ){
12763#ifndef SQLITE_OMIT_LOCALTIME
12764    case 'l': {
12765      /*    localtime
12766      **
12767      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
12768      ** show local time.
12769      */
12770      if( strcmp(z, "localtime")==0 ){
12771        computeJD(p);
12772        p->iJD += localtimeOffset(p);
12773        clearYMD_HMS_TZ(p);
12774        rc = 0;
12775      }
12776      break;
12777    }
12778#endif
12779    case 'u': {
12780      /*
12781      **    unixepoch
12782      **
12783      ** Treat the current value of p->iJD as the number of
12784      ** seconds since 1970.  Convert to a real julian day number.
12785      */
12786      if( strcmp(z, "unixepoch")==0 && p->validJD ){
12787        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
12788        clearYMD_HMS_TZ(p);
12789        rc = 0;
12790      }
12791#ifndef SQLITE_OMIT_LOCALTIME
12792      else if( strcmp(z, "utc")==0 ){
12793        sqlite3_int64 c1;
12794        computeJD(p);
12795        c1 = localtimeOffset(p);
12796        p->iJD -= c1;
12797        clearYMD_HMS_TZ(p);
12798        p->iJD += c1 - localtimeOffset(p);
12799        rc = 0;
12800      }
12801#endif
12802      break;
12803    }
12804    case 'w': {
12805      /*
12806      **    weekday N
12807      **
12808      ** Move the date to the same time on the next occurrence of
12809      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
12810      ** date is already on the appropriate weekday, this is a no-op.
12811      */
12812      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
12813                 && (n=(int)r)==r && n>=0 && r<7 ){
12814        sqlite3_int64 Z;
12815        computeYMD_HMS(p);
12816        p->validTZ = 0;
12817        p->validJD = 0;
12818        computeJD(p);
12819        Z = ((p->iJD + 129600000)/86400000) % 7;
12820        if( Z>n ) Z -= 7;
12821        p->iJD += (n - Z)*86400000;
12822        clearYMD_HMS_TZ(p);
12823        rc = 0;
12824      }
12825      break;
12826    }
12827    case 's': {
12828      /*
12829      **    start of TTTTT
12830      **
12831      ** Move the date backwards to the beginning of the current day,
12832      ** or month or year.
12833      */
12834      if( strncmp(z, "start of ", 9)!=0 ) break;
12835      z += 9;
12836      computeYMD(p);
12837      p->validHMS = 1;
12838      p->h = p->m = 0;
12839      p->s = 0.0;
12840      p->validTZ = 0;
12841      p->validJD = 0;
12842      if( strcmp(z,"month")==0 ){
12843        p->D = 1;
12844        rc = 0;
12845      }else if( strcmp(z,"year")==0 ){
12846        computeYMD(p);
12847        p->M = 1;
12848        p->D = 1;
12849        rc = 0;
12850      }else if( strcmp(z,"day")==0 ){
12851        rc = 0;
12852      }
12853      break;
12854    }
12855    case '+':
12856    case '-':
12857    case '0':
12858    case '1':
12859    case '2':
12860    case '3':
12861    case '4':
12862    case '5':
12863    case '6':
12864    case '7':
12865    case '8':
12866    case '9': {
12867      double rRounder;
12868      n = getValue(z, &r);
12869      assert( n>=1 );
12870      if( z[n]==':' ){
12871        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12872        ** specified number of hours, minutes, seconds, and fractional seconds
12873        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12874        ** omitted.
12875        */
12876        const char *z2 = z;
12877        DateTime tx;
12878        sqlite3_int64 day;
12879        if( !sqlite3Isdigit(*z2) ) z2++;
12880        memset(&tx, 0, sizeof(tx));
12881        if( parseHhMmSs(z2, &tx) ) break;
12882        computeJD(&tx);
12883        tx.iJD -= 43200000;
12884        day = tx.iJD/86400000;
12885        tx.iJD -= day*86400000;
12886        if( z[0]=='-' ) tx.iJD = -tx.iJD;
12887        computeJD(p);
12888        clearYMD_HMS_TZ(p);
12889        p->iJD += tx.iJD;
12890        rc = 0;
12891        break;
12892      }
12893      z += n;
12894      while( sqlite3Isspace(*z) ) z++;
12895      n = sqlite3Strlen30(z);
12896      if( n>10 || n<3 ) break;
12897      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12898      computeJD(p);
12899      rc = 0;
12900      rRounder = r<0 ? -0.5 : +0.5;
12901      if( n==3 && strcmp(z,"day")==0 ){
12902        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12903      }else if( n==4 && strcmp(z,"hour")==0 ){
12904        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12905      }else if( n==6 && strcmp(z,"minute")==0 ){
12906        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12907      }else if( n==6 && strcmp(z,"second")==0 ){
12908        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12909      }else if( n==5 && strcmp(z,"month")==0 ){
12910        int x, y;
12911        computeYMD_HMS(p);
12912        p->M += (int)r;
12913        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12914        p->Y += x;
12915        p->M -= x*12;
12916        p->validJD = 0;
12917        computeJD(p);
12918        y = (int)r;
12919        if( y!=r ){
12920          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12921        }
12922      }else if( n==4 && strcmp(z,"year")==0 ){
12923        int y = (int)r;
12924        computeYMD_HMS(p);
12925        p->Y += y;
12926        p->validJD = 0;
12927        computeJD(p);
12928        if( y!=r ){
12929          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12930        }
12931      }else{
12932        rc = 1;
12933      }
12934      clearYMD_HMS_TZ(p);
12935      break;
12936    }
12937    default: {
12938      break;
12939    }
12940  }
12941  return rc;
12942}
12943
12944/*
12945** Process time function arguments.  argv[0] is a date-time stamp.
12946** argv[1] and following are modifiers.  Parse them all and write
12947** the resulting time into the DateTime structure p.  Return 0
12948** on success and 1 if there are any errors.
12949**
12950** If there are zero parameters (if even argv[0] is undefined)
12951** then assume a default value of "now" for argv[0].
12952*/
12953static int isDate(
12954  sqlite3_context *context,
12955  int argc,
12956  sqlite3_value **argv,
12957  DateTime *p
12958){
12959  int i;
12960  const unsigned char *z;
12961  int eType;
12962  memset(p, 0, sizeof(*p));
12963  if( argc==0 ){
12964    setDateTimeToCurrent(context, p);
12965  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12966                   || eType==SQLITE_INTEGER ){
12967    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12968    p->validJD = 1;
12969  }else{
12970    z = sqlite3_value_text(argv[0]);
12971    if( !z || parseDateOrTime(context, (char*)z, p) ){
12972      return 1;
12973    }
12974  }
12975  for(i=1; i<argc; i++){
12976    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12977      return 1;
12978    }
12979  }
12980  return 0;
12981}
12982
12983
12984/*
12985** The following routines implement the various date and time functions
12986** of SQLite.
12987*/
12988
12989/*
12990**    julianday( TIMESTRING, MOD, MOD, ...)
12991**
12992** Return the julian day number of the date specified in the arguments
12993*/
12994static void juliandayFunc(
12995  sqlite3_context *context,
12996  int argc,
12997  sqlite3_value **argv
12998){
12999  DateTime x;
13000  if( isDate(context, argc, argv, &x)==0 ){
13001    computeJD(&x);
13002    sqlite3_result_double(context, x.iJD/86400000.0);
13003  }
13004}
13005
13006/*
13007**    datetime( TIMESTRING, MOD, MOD, ...)
13008**
13009** Return YYYY-MM-DD HH:MM:SS
13010*/
13011static void datetimeFunc(
13012  sqlite3_context *context,
13013  int argc,
13014  sqlite3_value **argv
13015){
13016  DateTime x;
13017  if( isDate(context, argc, argv, &x)==0 ){
13018    char zBuf[100];
13019    computeYMD_HMS(&x);
13020    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13021                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13022    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13023  }
13024}
13025
13026/*
13027**    time( TIMESTRING, MOD, MOD, ...)
13028**
13029** Return HH:MM:SS
13030*/
13031static void timeFunc(
13032  sqlite3_context *context,
13033  int argc,
13034  sqlite3_value **argv
13035){
13036  DateTime x;
13037  if( isDate(context, argc, argv, &x)==0 ){
13038    char zBuf[100];
13039    computeHMS(&x);
13040    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13041    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13042  }
13043}
13044
13045/*
13046**    date( TIMESTRING, MOD, MOD, ...)
13047**
13048** Return YYYY-MM-DD
13049*/
13050static void dateFunc(
13051  sqlite3_context *context,
13052  int argc,
13053  sqlite3_value **argv
13054){
13055  DateTime x;
13056  if( isDate(context, argc, argv, &x)==0 ){
13057    char zBuf[100];
13058    computeYMD(&x);
13059    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13060    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13061  }
13062}
13063
13064/*
13065**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13066**
13067** Return a string described by FORMAT.  Conversions as follows:
13068**
13069**   %d  day of month
13070**   %f  ** fractional seconds  SS.SSS
13071**   %H  hour 00-24
13072**   %j  day of year 000-366
13073**   %J  ** Julian day number
13074**   %m  month 01-12
13075**   %M  minute 00-59
13076**   %s  seconds since 1970-01-01
13077**   %S  seconds 00-59
13078**   %w  day of week 0-6  sunday==0
13079**   %W  week of year 00-53
13080**   %Y  year 0000-9999
13081**   %%  %
13082*/
13083static void strftimeFunc(
13084  sqlite3_context *context,
13085  int argc,
13086  sqlite3_value **argv
13087){
13088  DateTime x;
13089  u64 n;
13090  size_t i,j;
13091  char *z;
13092  sqlite3 *db;
13093  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13094  char zBuf[100];
13095  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13096  db = sqlite3_context_db_handle(context);
13097  for(i=0, n=1; zFmt[i]; i++, n++){
13098    if( zFmt[i]=='%' ){
13099      switch( zFmt[i+1] ){
13100        case 'd':
13101        case 'H':
13102        case 'm':
13103        case 'M':
13104        case 'S':
13105        case 'W':
13106          n++;
13107          /* fall thru */
13108        case 'w':
13109        case '%':
13110          break;
13111        case 'f':
13112          n += 8;
13113          break;
13114        case 'j':
13115          n += 3;
13116          break;
13117        case 'Y':
13118          n += 8;
13119          break;
13120        case 's':
13121        case 'J':
13122          n += 50;
13123          break;
13124        default:
13125          return;  /* ERROR.  return a NULL */
13126      }
13127      i++;
13128    }
13129  }
13130  testcase( n==sizeof(zBuf)-1 );
13131  testcase( n==sizeof(zBuf) );
13132  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13133  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13134  if( n<sizeof(zBuf) ){
13135    z = zBuf;
13136  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13137    sqlite3_result_error_toobig(context);
13138    return;
13139  }else{
13140    z = sqlite3DbMallocRaw(db, (int)n);
13141    if( z==0 ){
13142      sqlite3_result_error_nomem(context);
13143      return;
13144    }
13145  }
13146  computeJD(&x);
13147  computeYMD_HMS(&x);
13148  for(i=j=0; zFmt[i]; i++){
13149    if( zFmt[i]!='%' ){
13150      z[j++] = zFmt[i];
13151    }else{
13152      i++;
13153      switch( zFmt[i] ){
13154        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13155        case 'f': {
13156          double s = x.s;
13157          if( s>59.999 ) s = 59.999;
13158          sqlite3_snprintf(7, &z[j],"%06.3f", s);
13159          j += sqlite3Strlen30(&z[j]);
13160          break;
13161        }
13162        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13163        case 'W': /* Fall thru */
13164        case 'j': {
13165          int nDay;             /* Number of days since 1st day of year */
13166          DateTime y = x;
13167          y.validJD = 0;
13168          y.M = 1;
13169          y.D = 1;
13170          computeJD(&y);
13171          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13172          if( zFmt[i]=='W' ){
13173            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13174            wd = (int)(((x.iJD+43200000)/86400000)%7);
13175            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13176            j += 2;
13177          }else{
13178            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13179            j += 3;
13180          }
13181          break;
13182        }
13183        case 'J': {
13184          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13185          j+=sqlite3Strlen30(&z[j]);
13186          break;
13187        }
13188        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13189        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13190        case 's': {
13191          sqlite3_snprintf(30,&z[j],"%lld",
13192                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
13193          j += sqlite3Strlen30(&z[j]);
13194          break;
13195        }
13196        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13197        case 'w': {
13198          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13199          break;
13200        }
13201        case 'Y': {
13202          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13203          break;
13204        }
13205        default:   z[j++] = '%'; break;
13206      }
13207    }
13208  }
13209  z[j] = 0;
13210  sqlite3_result_text(context, z, -1,
13211                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13212}
13213
13214/*
13215** current_time()
13216**
13217** This function returns the same value as time('now').
13218*/
13219static void ctimeFunc(
13220  sqlite3_context *context,
13221  int NotUsed,
13222  sqlite3_value **NotUsed2
13223){
13224  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13225  timeFunc(context, 0, 0);
13226}
13227
13228/*
13229** current_date()
13230**
13231** This function returns the same value as date('now').
13232*/
13233static void cdateFunc(
13234  sqlite3_context *context,
13235  int NotUsed,
13236  sqlite3_value **NotUsed2
13237){
13238  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13239  dateFunc(context, 0, 0);
13240}
13241
13242/*
13243** current_timestamp()
13244**
13245** This function returns the same value as datetime('now').
13246*/
13247static void ctimestampFunc(
13248  sqlite3_context *context,
13249  int NotUsed,
13250  sqlite3_value **NotUsed2
13251){
13252  UNUSED_PARAMETER2(NotUsed, NotUsed2);
13253  datetimeFunc(context, 0, 0);
13254}
13255#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13256
13257#ifdef SQLITE_OMIT_DATETIME_FUNCS
13258/*
13259** If the library is compiled to omit the full-scale date and time
13260** handling (to get a smaller binary), the following minimal version
13261** of the functions current_time(), current_date() and current_timestamp()
13262** are included instead. This is to support column declarations that
13263** include "DEFAULT CURRENT_TIME" etc.
13264**
13265** This function uses the C-library functions time(), gmtime()
13266** and strftime(). The format string to pass to strftime() is supplied
13267** as the user-data for the function.
13268*/
13269static void currentTimeFunc(
13270  sqlite3_context *context,
13271  int argc,
13272  sqlite3_value **argv
13273){
13274  time_t t;
13275  char *zFormat = (char *)sqlite3_user_data(context);
13276  sqlite3 *db;
13277  sqlite3_int64 iT;
13278  char zBuf[20];
13279
13280  UNUSED_PARAMETER(argc);
13281  UNUSED_PARAMETER(argv);
13282
13283  db = sqlite3_context_db_handle(context);
13284  sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13285  t = iT/1000 - 10000*(sqlite3_int64)21086676;
13286#ifdef HAVE_GMTIME_R
13287  {
13288    struct tm sNow;
13289    gmtime_r(&t, &sNow);
13290    strftime(zBuf, 20, zFormat, &sNow);
13291  }
13292#else
13293  {
13294    struct tm *pTm;
13295    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13296    pTm = gmtime(&t);
13297    strftime(zBuf, 20, zFormat, pTm);
13298    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13299  }
13300#endif
13301
13302  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13303}
13304#endif
13305
13306/*
13307** This function registered all of the above C functions as SQL
13308** functions.  This should be the only routine in this file with
13309** external linkage.
13310*/
13311SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13312  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13313#ifndef SQLITE_OMIT_DATETIME_FUNCS
13314    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13315    FUNCTION(date,             -1, 0, 0, dateFunc      ),
13316    FUNCTION(time,             -1, 0, 0, timeFunc      ),
13317    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13318    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13319    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13320    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13321    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13322#else
13323    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13324    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13325    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13326#endif
13327  };
13328  int i;
13329  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13330  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13331
13332  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13333    sqlite3FuncDefInsert(pHash, &aFunc[i]);
13334  }
13335}
13336
13337/************** End of date.c ************************************************/
13338/************** Begin file os.c **********************************************/
13339/*
13340** 2005 November 29
13341**
13342** The author disclaims copyright to this source code.  In place of
13343** a legal notice, here is a blessing:
13344**
13345**    May you do good and not evil.
13346**    May you find forgiveness for yourself and forgive others.
13347**    May you share freely, never taking more than you give.
13348**
13349******************************************************************************
13350**
13351** This file contains OS interface code that is common to all
13352** architectures.
13353*/
13354#define _SQLITE_OS_C_ 1
13355#undef _SQLITE_OS_C_
13356
13357/*
13358** The default SQLite sqlite3_vfs implementations do not allocate
13359** memory (actually, os_unix.c allocates a small amount of memory
13360** from within OsOpen()), but some third-party implementations may.
13361** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13362** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13363**
13364** The following functions are instrumented for malloc() failure
13365** testing:
13366**
13367**     sqlite3OsOpen()
13368**     sqlite3OsRead()
13369**     sqlite3OsWrite()
13370**     sqlite3OsSync()
13371**     sqlite3OsLock()
13372**
13373*/
13374#if defined(SQLITE_TEST)
13375SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13376  #define DO_OS_MALLOC_TEST(x)                                       \
13377  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13378    void *pTstAlloc = sqlite3Malloc(10);                             \
13379    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13380    sqlite3_free(pTstAlloc);                                         \
13381  }
13382#else
13383  #define DO_OS_MALLOC_TEST(x)
13384#endif
13385
13386/*
13387** The following routines are convenience wrappers around methods
13388** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13389** of this would be completely automatic if SQLite were coded using
13390** C++ instead of plain old C.
13391*/
13392SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13393  int rc = SQLITE_OK;
13394  if( pId->pMethods ){
13395    rc = pId->pMethods->xClose(pId);
13396    pId->pMethods = 0;
13397  }
13398  return rc;
13399}
13400SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13401  DO_OS_MALLOC_TEST(id);
13402  return id->pMethods->xRead(id, pBuf, amt, offset);
13403}
13404SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13405  DO_OS_MALLOC_TEST(id);
13406  return id->pMethods->xWrite(id, pBuf, amt, offset);
13407}
13408SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13409  return id->pMethods->xTruncate(id, size);
13410}
13411SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13412  DO_OS_MALLOC_TEST(id);
13413  return id->pMethods->xSync(id, flags);
13414}
13415SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
13416  DO_OS_MALLOC_TEST(id);
13417  return id->pMethods->xFileSize(id, pSize);
13418}
13419SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
13420  DO_OS_MALLOC_TEST(id);
13421  return id->pMethods->xLock(id, lockType);
13422}
13423SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
13424  return id->pMethods->xUnlock(id, lockType);
13425}
13426SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
13427  DO_OS_MALLOC_TEST(id);
13428  return id->pMethods->xCheckReservedLock(id, pResOut);
13429}
13430SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
13431  return id->pMethods->xFileControl(id, op, pArg);
13432}
13433SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
13434  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
13435  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
13436}
13437SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
13438  return id->pMethods->xDeviceCharacteristics(id);
13439}
13440SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
13441  return id->pMethods->xShmLock(id, offset, n, flags);
13442}
13443SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
13444  id->pMethods->xShmBarrier(id);
13445}
13446SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
13447  return id->pMethods->xShmUnmap(id, deleteFlag);
13448}
13449SQLITE_PRIVATE int sqlite3OsShmMap(
13450  sqlite3_file *id,               /* Database file handle */
13451  int iPage,
13452  int pgsz,
13453  int bExtend,                    /* True to extend file if necessary */
13454  void volatile **pp              /* OUT: Pointer to mapping */
13455){
13456  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
13457}
13458
13459/*
13460** The next group of routines are convenience wrappers around the
13461** VFS methods.
13462*/
13463SQLITE_PRIVATE int sqlite3OsOpen(
13464  sqlite3_vfs *pVfs,
13465  const char *zPath,
13466  sqlite3_file *pFile,
13467  int flags,
13468  int *pFlagsOut
13469){
13470  int rc;
13471  DO_OS_MALLOC_TEST(0);
13472  /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
13473  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
13474  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
13475  ** reaching the VFS. */
13476  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
13477  assert( rc==SQLITE_OK || pFile->pMethods==0 );
13478  return rc;
13479}
13480SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
13481  return pVfs->xDelete(pVfs, zPath, dirSync);
13482}
13483SQLITE_PRIVATE int sqlite3OsAccess(
13484  sqlite3_vfs *pVfs,
13485  const char *zPath,
13486  int flags,
13487  int *pResOut
13488){
13489  DO_OS_MALLOC_TEST(0);
13490  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
13491}
13492SQLITE_PRIVATE int sqlite3OsFullPathname(
13493  sqlite3_vfs *pVfs,
13494  const char *zPath,
13495  int nPathOut,
13496  char *zPathOut
13497){
13498  zPathOut[0] = 0;
13499  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
13500}
13501#ifndef SQLITE_OMIT_LOAD_EXTENSION
13502SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
13503  return pVfs->xDlOpen(pVfs, zPath);
13504}
13505SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13506  pVfs->xDlError(pVfs, nByte, zBufOut);
13507}
13508SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
13509  return pVfs->xDlSym(pVfs, pHdle, zSym);
13510}
13511SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
13512  pVfs->xDlClose(pVfs, pHandle);
13513}
13514#endif /* SQLITE_OMIT_LOAD_EXTENSION */
13515SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13516  return pVfs->xRandomness(pVfs, nByte, zBufOut);
13517}
13518SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13519  return pVfs->xSleep(pVfs, nMicro);
13520}
13521SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13522  int rc;
13523  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13524    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13525  }else{
13526    double r;
13527    rc = pVfs->xCurrentTime(pVfs, &r);
13528    *pTimeOut = (sqlite3_int64)(r*86400000.0);
13529  }
13530  return rc;
13531}
13532
13533SQLITE_PRIVATE int sqlite3OsOpenMalloc(
13534  sqlite3_vfs *pVfs,
13535  const char *zFile,
13536  sqlite3_file **ppFile,
13537  int flags,
13538  int *pOutFlags
13539){
13540  int rc = SQLITE_NOMEM;
13541  sqlite3_file *pFile;
13542  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
13543  if( pFile ){
13544    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13545    if( rc!=SQLITE_OK ){
13546      sqlite3_free(pFile);
13547    }else{
13548      *ppFile = pFile;
13549    }
13550  }
13551  return rc;
13552}
13553SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13554  int rc = SQLITE_OK;
13555  assert( pFile );
13556  rc = sqlite3OsClose(pFile);
13557  sqlite3_free(pFile);
13558  return rc;
13559}
13560
13561/*
13562** This function is a wrapper around the OS specific implementation of
13563** sqlite3_os_init(). The purpose of the wrapper is to provide the
13564** ability to simulate a malloc failure, so that the handling of an
13565** error in sqlite3_os_init() by the upper layers can be tested.
13566*/
13567SQLITE_PRIVATE int sqlite3OsInit(void){
13568  void *p = sqlite3_malloc(10);
13569  if( p==0 ) return SQLITE_NOMEM;
13570  sqlite3_free(p);
13571  return sqlite3_os_init();
13572}
13573
13574/*
13575** The list of all registered VFS implementations.
13576*/
13577static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13578#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13579
13580/*
13581** Locate a VFS by name.  If no name is given, simply return the
13582** first VFS on the list.
13583*/
13584SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13585  sqlite3_vfs *pVfs = 0;
13586#if SQLITE_THREADSAFE
13587  sqlite3_mutex *mutex;
13588#endif
13589#ifndef SQLITE_OMIT_AUTOINIT
13590  int rc = sqlite3_initialize();
13591  if( rc ) return 0;
13592#endif
13593#if SQLITE_THREADSAFE
13594  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13595#endif
13596  sqlite3_mutex_enter(mutex);
13597  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13598    if( zVfs==0 ) break;
13599    if( strcmp(zVfs, pVfs->zName)==0 ) break;
13600  }
13601  sqlite3_mutex_leave(mutex);
13602  return pVfs;
13603}
13604
13605/*
13606** Unlink a VFS from the linked list
13607*/
13608static void vfsUnlink(sqlite3_vfs *pVfs){
13609  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13610  if( pVfs==0 ){
13611    /* No-op */
13612  }else if( vfsList==pVfs ){
13613    vfsList = pVfs->pNext;
13614  }else if( vfsList ){
13615    sqlite3_vfs *p = vfsList;
13616    while( p->pNext && p->pNext!=pVfs ){
13617      p = p->pNext;
13618    }
13619    if( p->pNext==pVfs ){
13620      p->pNext = pVfs->pNext;
13621    }
13622  }
13623}
13624
13625/*
13626** Register a VFS with the system.  It is harmless to register the same
13627** VFS multiple times.  The new VFS becomes the default if makeDflt is
13628** true.
13629*/
13630SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13631  sqlite3_mutex *mutex = 0;
13632#ifndef SQLITE_OMIT_AUTOINIT
13633  int rc = sqlite3_initialize();
13634  if( rc ) return rc;
13635#endif
13636  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13637  sqlite3_mutex_enter(mutex);
13638  vfsUnlink(pVfs);
13639  if( makeDflt || vfsList==0 ){
13640    pVfs->pNext = vfsList;
13641    vfsList = pVfs;
13642  }else{
13643    pVfs->pNext = vfsList->pNext;
13644    vfsList->pNext = pVfs;
13645  }
13646  assert(vfsList);
13647  sqlite3_mutex_leave(mutex);
13648  return SQLITE_OK;
13649}
13650
13651/*
13652** Unregister a VFS so that it is no longer accessible.
13653*/
13654SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
13655#if SQLITE_THREADSAFE
13656  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13657#endif
13658  sqlite3_mutex_enter(mutex);
13659  vfsUnlink(pVfs);
13660  sqlite3_mutex_leave(mutex);
13661  return SQLITE_OK;
13662}
13663
13664/************** End of os.c **************************************************/
13665/************** Begin file fault.c *******************************************/
13666/*
13667** 2008 Jan 22
13668**
13669** The author disclaims copyright to this source code.  In place of
13670** a legal notice, here is a blessing:
13671**
13672**    May you do good and not evil.
13673**    May you find forgiveness for yourself and forgive others.
13674**    May you share freely, never taking more than you give.
13675**
13676*************************************************************************
13677**
13678** This file contains code to support the concept of "benign"
13679** malloc failures (when the xMalloc() or xRealloc() method of the
13680** sqlite3_mem_methods structure fails to allocate a block of memory
13681** and returns 0).
13682**
13683** Most malloc failures are non-benign. After they occur, SQLite
13684** abandons the current operation and returns an error code (usually
13685** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
13686** fatal. For example, if a malloc fails while resizing a hash table, this
13687** is completely recoverable simply by not carrying out the resize. The
13688** hash table will continue to function normally.  So a malloc failure
13689** during a hash table resize is a benign fault.
13690*/
13691
13692
13693#ifndef SQLITE_OMIT_BUILTIN_TEST
13694
13695/*
13696** Global variables.
13697*/
13698typedef struct BenignMallocHooks BenignMallocHooks;
13699static SQLITE_WSD struct BenignMallocHooks {
13700  void (*xBenignBegin)(void);
13701  void (*xBenignEnd)(void);
13702} sqlite3Hooks = { 0, 0 };
13703
13704/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
13705** structure.  If writable static data is unsupported on the target,
13706** we have to locate the state vector at run-time.  In the more common
13707** case where writable static data is supported, wsdHooks can refer directly
13708** to the "sqlite3Hooks" state vector declared above.
13709*/
13710#ifdef SQLITE_OMIT_WSD
13711# define wsdHooksInit \
13712  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
13713# define wsdHooks x[0]
13714#else
13715# define wsdHooksInit
13716# define wsdHooks sqlite3Hooks
13717#endif
13718
13719
13720/*
13721** Register hooks to call when sqlite3BeginBenignMalloc() and
13722** sqlite3EndBenignMalloc() are called, respectively.
13723*/
13724SQLITE_PRIVATE void sqlite3BenignMallocHooks(
13725  void (*xBenignBegin)(void),
13726  void (*xBenignEnd)(void)
13727){
13728  wsdHooksInit;
13729  wsdHooks.xBenignBegin = xBenignBegin;
13730  wsdHooks.xBenignEnd = xBenignEnd;
13731}
13732
13733/*
13734** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
13735** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
13736** indicates that subsequent malloc failures are non-benign.
13737*/
13738SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
13739  wsdHooksInit;
13740  if( wsdHooks.xBenignBegin ){
13741    wsdHooks.xBenignBegin();
13742  }
13743}
13744SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
13745  wsdHooksInit;
13746  if( wsdHooks.xBenignEnd ){
13747    wsdHooks.xBenignEnd();
13748  }
13749}
13750
13751#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
13752
13753/************** End of fault.c ***********************************************/
13754/************** Begin file mem0.c ********************************************/
13755/*
13756** 2008 October 28
13757**
13758** The author disclaims copyright to this source code.  In place of
13759** a legal notice, here is a blessing:
13760**
13761**    May you do good and not evil.
13762**    May you find forgiveness for yourself and forgive others.
13763**    May you share freely, never taking more than you give.
13764**
13765*************************************************************************
13766**
13767** This file contains a no-op memory allocation drivers for use when
13768** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
13769** here always fail.  SQLite will not operate with these drivers.  These
13770** are merely placeholders.  Real drivers must be substituted using
13771** sqlite3_config() before SQLite will operate.
13772*/
13773
13774/*
13775** This version of the memory allocator is the default.  It is
13776** used when no other memory allocator is specified using compile-time
13777** macros.
13778*/
13779#ifdef SQLITE_ZERO_MALLOC
13780
13781/*
13782** No-op versions of all memory allocation routines
13783*/
13784static void *sqlite3MemMalloc(int nByte){ return 0; }
13785static void sqlite3MemFree(void *pPrior){ return; }
13786static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
13787static int sqlite3MemSize(void *pPrior){ return 0; }
13788static int sqlite3MemRoundup(int n){ return n; }
13789static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
13790static void sqlite3MemShutdown(void *NotUsed){ return; }
13791
13792/*
13793** This routine is the only routine in this file with external linkage.
13794**
13795** Populate the low-level memory allocation function pointers in
13796** sqlite3GlobalConfig.m with pointers to the routines in this file.
13797*/
13798SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13799  static const sqlite3_mem_methods defaultMethods = {
13800     sqlite3MemMalloc,
13801     sqlite3MemFree,
13802     sqlite3MemRealloc,
13803     sqlite3MemSize,
13804     sqlite3MemRoundup,
13805     sqlite3MemInit,
13806     sqlite3MemShutdown,
13807     0
13808  };
13809  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13810}
13811
13812#endif /* SQLITE_ZERO_MALLOC */
13813
13814/************** End of mem0.c ************************************************/
13815/************** Begin file mem1.c ********************************************/
13816/*
13817** 2007 August 14
13818**
13819** The author disclaims copyright to this source code.  In place of
13820** a legal notice, here is a blessing:
13821**
13822**    May you do good and not evil.
13823**    May you find forgiveness for yourself and forgive others.
13824**    May you share freely, never taking more than you give.
13825**
13826*************************************************************************
13827**
13828** This file contains low-level memory allocation drivers for when
13829** SQLite will use the standard C-library malloc/realloc/free interface
13830** to obtain the memory it needs.
13831**
13832** This file contains implementations of the low-level memory allocation
13833** routines specified in the sqlite3_mem_methods object.
13834*/
13835
13836/*
13837** This version of the memory allocator is the default.  It is
13838** used when no other memory allocator is specified using compile-time
13839** macros.
13840*/
13841#ifdef SQLITE_SYSTEM_MALLOC
13842
13843/*
13844** Like malloc(), but remember the size of the allocation
13845** so that we can find it later using sqlite3MemSize().
13846**
13847** For this low-level routine, we are guaranteed that nByte>0 because
13848** cases of nByte<=0 will be intercepted and dealt with by higher level
13849** routines.
13850*/
13851static void *sqlite3MemMalloc(int nByte){
13852  sqlite3_int64 *p;
13853  assert( nByte>0 );
13854  nByte = ROUND8(nByte);
13855  p = malloc( nByte+8 );
13856  if( p ){
13857    p[0] = nByte;
13858    p++;
13859  }else{
13860    testcase( sqlite3GlobalConfig.xLog!=0 );
13861    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
13862  }
13863  return (void *)p;
13864}
13865
13866/*
13867** Like free() but works for allocations obtained from sqlite3MemMalloc()
13868** or sqlite3MemRealloc().
13869**
13870** For this low-level routine, we already know that pPrior!=0 since
13871** cases where pPrior==0 will have been intecepted and dealt with
13872** by higher-level routines.
13873*/
13874static void sqlite3MemFree(void *pPrior){
13875  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13876  assert( pPrior!=0 );
13877  p--;
13878  free(p);
13879}
13880
13881/*
13882** Report the allocated size of a prior return from xMalloc()
13883** or xRealloc().
13884*/
13885static int sqlite3MemSize(void *pPrior){
13886  sqlite3_int64 *p;
13887  if( pPrior==0 ) return 0;
13888  p = (sqlite3_int64*)pPrior;
13889  p--;
13890  return (int)p[0];
13891}
13892
13893/*
13894** Like realloc().  Resize an allocation previously obtained from
13895** sqlite3MemMalloc().
13896**
13897** For this low-level interface, we know that pPrior!=0.  Cases where
13898** pPrior==0 while have been intercepted by higher-level routine and
13899** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13900** cases where nByte<=0 will have been intercepted by higher-level
13901** routines and redirected to xFree.
13902*/
13903static void *sqlite3MemRealloc(void *pPrior, int nByte){
13904  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13905  assert( pPrior!=0 && nByte>0 );
13906  nByte = ROUND8(nByte);
13907  p--;
13908  p = realloc(p, nByte+8 );
13909  if( p ){
13910    p[0] = nByte;
13911    p++;
13912  }else{
13913    testcase( sqlite3GlobalConfig.xLog!=0 );
13914    sqlite3_log(SQLITE_NOMEM,
13915      "failed memory resize %u to %u bytes",
13916      sqlite3MemSize(pPrior), nByte);
13917  }
13918  return (void*)p;
13919}
13920
13921/*
13922** Round up a request size to the next valid allocation size.
13923*/
13924static int sqlite3MemRoundup(int n){
13925  return ROUND8(n);
13926}
13927
13928/*
13929** Initialize this module.
13930*/
13931static int sqlite3MemInit(void *NotUsed){
13932  UNUSED_PARAMETER(NotUsed);
13933  return SQLITE_OK;
13934}
13935
13936/*
13937** Deinitialize this module.
13938*/
13939static void sqlite3MemShutdown(void *NotUsed){
13940  UNUSED_PARAMETER(NotUsed);
13941  return;
13942}
13943
13944/*
13945** This routine is the only routine in this file with external linkage.
13946**
13947** Populate the low-level memory allocation function pointers in
13948** sqlite3GlobalConfig.m with pointers to the routines in this file.
13949*/
13950SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13951  static const sqlite3_mem_methods defaultMethods = {
13952     sqlite3MemMalloc,
13953     sqlite3MemFree,
13954     sqlite3MemRealloc,
13955     sqlite3MemSize,
13956     sqlite3MemRoundup,
13957     sqlite3MemInit,
13958     sqlite3MemShutdown,
13959     0
13960  };
13961  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13962}
13963
13964#endif /* SQLITE_SYSTEM_MALLOC */
13965
13966/************** End of mem1.c ************************************************/
13967/************** Begin file mem2.c ********************************************/
13968/*
13969** 2007 August 15
13970**
13971** The author disclaims copyright to this source code.  In place of
13972** a legal notice, here is a blessing:
13973**
13974**    May you do good and not evil.
13975**    May you find forgiveness for yourself and forgive others.
13976**    May you share freely, never taking more than you give.
13977**
13978*************************************************************************
13979**
13980** This file contains low-level memory allocation drivers for when
13981** SQLite will use the standard C-library malloc/realloc/free interface
13982** to obtain the memory it needs while adding lots of additional debugging
13983** information to each allocation in order to help detect and fix memory
13984** leaks and memory usage errors.
13985**
13986** This file contains implementations of the low-level memory allocation
13987** routines specified in the sqlite3_mem_methods object.
13988*/
13989
13990/*
13991** This version of the memory allocator is used only if the
13992** SQLITE_MEMDEBUG macro is defined
13993*/
13994#ifdef SQLITE_MEMDEBUG
13995
13996/*
13997** The backtrace functionality is only available with GLIBC
13998*/
13999#ifdef __GLIBC__
14000  extern int backtrace(void**,int);
14001  extern void backtrace_symbols_fd(void*const*,int,int);
14002#else
14003# define backtrace(A,B) 1
14004# define backtrace_symbols_fd(A,B,C)
14005#endif
14006
14007/*
14008** Each memory allocation looks like this:
14009**
14010**  ------------------------------------------------------------------------
14011**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14012**  ------------------------------------------------------------------------
14013**
14014** The application code sees only a pointer to the allocation.  We have
14015** to back up from the allocation pointer to find the MemBlockHdr.  The
14016** MemBlockHdr tells us the size of the allocation and the number of
14017** backtrace pointers.  There is also a guard word at the end of the
14018** MemBlockHdr.
14019*/
14020struct MemBlockHdr {
14021  i64 iSize;                          /* Size of this allocation */
14022  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14023  char nBacktrace;                    /* Number of backtraces on this alloc */
14024  char nBacktraceSlots;               /* Available backtrace slots */
14025  u8 nTitle;                          /* Bytes of title; includes '\0' */
14026  u8 eType;                           /* Allocation type code */
14027  int iForeGuard;                     /* Guard word for sanity */
14028};
14029
14030/*
14031** Guard words
14032*/
14033#define FOREGUARD 0x80F5E153
14034#define REARGUARD 0xE4676B53
14035
14036/*
14037** Number of malloc size increments to track.
14038*/
14039#define NCSIZE  1000
14040
14041/*
14042** All of the static variables used by this module are collected
14043** into a single structure named "mem".  This is to keep the
14044** static variables organized and to reduce namespace pollution
14045** when this module is combined with other in the amalgamation.
14046*/
14047static struct {
14048
14049  /*
14050  ** Mutex to control access to the memory allocation subsystem.
14051  */
14052  sqlite3_mutex *mutex;
14053
14054  /*
14055  ** Head and tail of a linked list of all outstanding allocations
14056  */
14057  struct MemBlockHdr *pFirst;
14058  struct MemBlockHdr *pLast;
14059
14060  /*
14061  ** The number of levels of backtrace to save in new allocations.
14062  */
14063  int nBacktrace;
14064  void (*xBacktrace)(int, int, void **);
14065
14066  /*
14067  ** Title text to insert in front of each block
14068  */
14069  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14070  char zTitle[100];  /* The title text */
14071
14072  /*
14073  ** sqlite3MallocDisallow() increments the following counter.
14074  ** sqlite3MallocAllow() decrements it.
14075  */
14076  int disallow; /* Do not allow memory allocation */
14077
14078  /*
14079  ** Gather statistics on the sizes of memory allocations.
14080  ** nAlloc[i] is the number of allocation attempts of i*8
14081  ** bytes.  i==NCSIZE is the number of allocation attempts for
14082  ** sizes more than NCSIZE*8 bytes.
14083  */
14084  int nAlloc[NCSIZE];      /* Total number of allocations */
14085  int nCurrent[NCSIZE];    /* Current number of allocations */
14086  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14087
14088} mem;
14089
14090
14091/*
14092** Adjust memory usage statistics
14093*/
14094static void adjustStats(int iSize, int increment){
14095  int i = ROUND8(iSize)/8;
14096  if( i>NCSIZE-1 ){
14097    i = NCSIZE - 1;
14098  }
14099  if( increment>0 ){
14100    mem.nAlloc[i]++;
14101    mem.nCurrent[i]++;
14102    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14103      mem.mxCurrent[i] = mem.nCurrent[i];
14104    }
14105  }else{
14106    mem.nCurrent[i]--;
14107    assert( mem.nCurrent[i]>=0 );
14108  }
14109}
14110
14111/*
14112** Given an allocation, find the MemBlockHdr for that allocation.
14113**
14114** This routine checks the guards at either end of the allocation and
14115** if they are incorrect it asserts.
14116*/
14117static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14118  struct MemBlockHdr *p;
14119  int *pInt;
14120  u8 *pU8;
14121  int nReserve;
14122
14123  p = (struct MemBlockHdr*)pAllocation;
14124  p--;
14125  assert( p->iForeGuard==(int)FOREGUARD );
14126  nReserve = ROUND8(p->iSize);
14127  pInt = (int*)pAllocation;
14128  pU8 = (u8*)pAllocation;
14129  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14130  /* This checks any of the "extra" bytes allocated due
14131  ** to rounding up to an 8 byte boundary to ensure
14132  ** they haven't been overwritten.
14133  */
14134  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14135  return p;
14136}
14137
14138/*
14139** Return the number of bytes currently allocated at address p.
14140*/
14141static int sqlite3MemSize(void *p){
14142  struct MemBlockHdr *pHdr;
14143  if( !p ){
14144    return 0;
14145  }
14146  pHdr = sqlite3MemsysGetHeader(p);
14147  return pHdr->iSize;
14148}
14149
14150/*
14151** Initialize the memory allocation subsystem.
14152*/
14153static int sqlite3MemInit(void *NotUsed){
14154  UNUSED_PARAMETER(NotUsed);
14155  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14156  if( !sqlite3GlobalConfig.bMemstat ){
14157    /* If memory status is enabled, then the malloc.c wrapper will already
14158    ** hold the STATIC_MEM mutex when the routines here are invoked. */
14159    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14160  }
14161  return SQLITE_OK;
14162}
14163
14164/*
14165** Deinitialize the memory allocation subsystem.
14166*/
14167static void sqlite3MemShutdown(void *NotUsed){
14168  UNUSED_PARAMETER(NotUsed);
14169  mem.mutex = 0;
14170}
14171
14172/*
14173** Round up a request size to the next valid allocation size.
14174*/
14175static int sqlite3MemRoundup(int n){
14176  return ROUND8(n);
14177}
14178
14179/*
14180** Fill a buffer with pseudo-random bytes.  This is used to preset
14181** the content of a new memory allocation to unpredictable values and
14182** to clear the content of a freed allocation to unpredictable values.
14183*/
14184static void randomFill(char *pBuf, int nByte){
14185  unsigned int x, y, r;
14186  x = SQLITE_PTR_TO_INT(pBuf);
14187  y = nByte | 1;
14188  while( nByte >= 4 ){
14189    x = (x>>1) ^ (-(x&1) & 0xd0000001);
14190    y = y*1103515245 + 12345;
14191    r = x ^ y;
14192    *(int*)pBuf = r;
14193    pBuf += 4;
14194    nByte -= 4;
14195  }
14196  while( nByte-- > 0 ){
14197    x = (x>>1) ^ (-(x&1) & 0xd0000001);
14198    y = y*1103515245 + 12345;
14199    r = x ^ y;
14200    *(pBuf++) = r & 0xff;
14201  }
14202}
14203
14204/*
14205** Allocate nByte bytes of memory.
14206*/
14207static void *sqlite3MemMalloc(int nByte){
14208  struct MemBlockHdr *pHdr;
14209  void **pBt;
14210  char *z;
14211  int *pInt;
14212  void *p = 0;
14213  int totalSize;
14214  int nReserve;
14215  sqlite3_mutex_enter(mem.mutex);
14216  assert( mem.disallow==0 );
14217  nReserve = ROUND8(nByte);
14218  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14219               mem.nBacktrace*sizeof(void*) + mem.nTitle;
14220  p = malloc(totalSize);
14221  if( p ){
14222    z = p;
14223    pBt = (void**)&z[mem.nTitle];
14224    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14225    pHdr->pNext = 0;
14226    pHdr->pPrev = mem.pLast;
14227    if( mem.pLast ){
14228      mem.pLast->pNext = pHdr;
14229    }else{
14230      mem.pFirst = pHdr;
14231    }
14232    mem.pLast = pHdr;
14233    pHdr->iForeGuard = FOREGUARD;
14234    pHdr->eType = MEMTYPE_HEAP;
14235    pHdr->nBacktraceSlots = mem.nBacktrace;
14236    pHdr->nTitle = mem.nTitle;
14237    if( mem.nBacktrace ){
14238      void *aAddr[40];
14239      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14240      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14241      assert(pBt[0]);
14242      if( mem.xBacktrace ){
14243        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14244      }
14245    }else{
14246      pHdr->nBacktrace = 0;
14247    }
14248    if( mem.nTitle ){
14249      memcpy(z, mem.zTitle, mem.nTitle);
14250    }
14251    pHdr->iSize = nByte;
14252    adjustStats(nByte, +1);
14253    pInt = (int*)&pHdr[1];
14254    pInt[nReserve/sizeof(int)] = REARGUARD;
14255    randomFill((char*)pInt, nByte);
14256    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14257    p = (void*)pInt;
14258  }
14259  sqlite3_mutex_leave(mem.mutex);
14260  return p;
14261}
14262
14263/*
14264** Free memory.
14265*/
14266static void sqlite3MemFree(void *pPrior){
14267  struct MemBlockHdr *pHdr;
14268  void **pBt;
14269  char *z;
14270  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
14271       || mem.mutex!=0 );
14272  pHdr = sqlite3MemsysGetHeader(pPrior);
14273  pBt = (void**)pHdr;
14274  pBt -= pHdr->nBacktraceSlots;
14275  sqlite3_mutex_enter(mem.mutex);
14276  if( pHdr->pPrev ){
14277    assert( pHdr->pPrev->pNext==pHdr );
14278    pHdr->pPrev->pNext = pHdr->pNext;
14279  }else{
14280    assert( mem.pFirst==pHdr );
14281    mem.pFirst = pHdr->pNext;
14282  }
14283  if( pHdr->pNext ){
14284    assert( pHdr->pNext->pPrev==pHdr );
14285    pHdr->pNext->pPrev = pHdr->pPrev;
14286  }else{
14287    assert( mem.pLast==pHdr );
14288    mem.pLast = pHdr->pPrev;
14289  }
14290  z = (char*)pBt;
14291  z -= pHdr->nTitle;
14292  adjustStats(pHdr->iSize, -1);
14293  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14294                pHdr->iSize + sizeof(int) + pHdr->nTitle);
14295  free(z);
14296  sqlite3_mutex_leave(mem.mutex);
14297}
14298
14299/*
14300** Change the size of an existing memory allocation.
14301**
14302** For this debugging implementation, we *always* make a copy of the
14303** allocation into a new place in memory.  In this way, if the
14304** higher level code is using pointer to the old allocation, it is
14305** much more likely to break and we are much more liking to find
14306** the error.
14307*/
14308static void *sqlite3MemRealloc(void *pPrior, int nByte){
14309  struct MemBlockHdr *pOldHdr;
14310  void *pNew;
14311  assert( mem.disallow==0 );
14312  pOldHdr = sqlite3MemsysGetHeader(pPrior);
14313  pNew = sqlite3MemMalloc(nByte);
14314  if( pNew ){
14315    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14316    if( nByte>pOldHdr->iSize ){
14317      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14318    }
14319    sqlite3MemFree(pPrior);
14320  }
14321  return pNew;
14322}
14323
14324/*
14325** Populate the low-level memory allocation function pointers in
14326** sqlite3GlobalConfig.m with pointers to the routines in this file.
14327*/
14328SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14329  static const sqlite3_mem_methods defaultMethods = {
14330     sqlite3MemMalloc,
14331     sqlite3MemFree,
14332     sqlite3MemRealloc,
14333     sqlite3MemSize,
14334     sqlite3MemRoundup,
14335     sqlite3MemInit,
14336     sqlite3MemShutdown,
14337     0
14338  };
14339  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14340}
14341
14342/*
14343** Set the "type" of an allocation.
14344*/
14345SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14346  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14347    struct MemBlockHdr *pHdr;
14348    pHdr = sqlite3MemsysGetHeader(p);
14349    assert( pHdr->iForeGuard==FOREGUARD );
14350    pHdr->eType = eType;
14351  }
14352}
14353
14354/*
14355** Return TRUE if the mask of type in eType matches the type of the
14356** allocation p.  Also return true if p==NULL.
14357**
14358** This routine is designed for use within an assert() statement, to
14359** verify the type of an allocation.  For example:
14360**
14361**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14362*/
14363SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14364  int rc = 1;
14365  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14366    struct MemBlockHdr *pHdr;
14367    pHdr = sqlite3MemsysGetHeader(p);
14368    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14369    if( (pHdr->eType&eType)==0 ){
14370      rc = 0;
14371    }
14372  }
14373  return rc;
14374}
14375
14376/*
14377** Return TRUE if the mask of type in eType matches no bits of the type of the
14378** allocation p.  Also return true if p==NULL.
14379**
14380** This routine is designed for use within an assert() statement, to
14381** verify the type of an allocation.  For example:
14382**
14383**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14384*/
14385SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14386  int rc = 1;
14387  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14388    struct MemBlockHdr *pHdr;
14389    pHdr = sqlite3MemsysGetHeader(p);
14390    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14391    if( (pHdr->eType&eType)!=0 ){
14392      rc = 0;
14393    }
14394  }
14395  return rc;
14396}
14397
14398/*
14399** Set the number of backtrace levels kept for each allocation.
14400** A value of zero turns off backtracing.  The number is always rounded
14401** up to a multiple of 2.
14402*/
14403SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14404  if( depth<0 ){ depth = 0; }
14405  if( depth>20 ){ depth = 20; }
14406  depth = (depth+1)&0xfe;
14407  mem.nBacktrace = depth;
14408}
14409
14410SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
14411  mem.xBacktrace = xBacktrace;
14412}
14413
14414/*
14415** Set the title string for subsequent allocations.
14416*/
14417SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
14418  unsigned int n = sqlite3Strlen30(zTitle) + 1;
14419  sqlite3_mutex_enter(mem.mutex);
14420  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
14421  memcpy(mem.zTitle, zTitle, n);
14422  mem.zTitle[n] = 0;
14423  mem.nTitle = ROUND8(n);
14424  sqlite3_mutex_leave(mem.mutex);
14425}
14426
14427SQLITE_PRIVATE void sqlite3MemdebugSync(){
14428  struct MemBlockHdr *pHdr;
14429  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14430    void **pBt = (void**)pHdr;
14431    pBt -= pHdr->nBacktraceSlots;
14432    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
14433  }
14434}
14435
14436/*
14437** Open the file indicated and write a log of all unfreed memory
14438** allocations into that log.
14439*/
14440SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
14441  FILE *out;
14442  struct MemBlockHdr *pHdr;
14443  void **pBt;
14444  int i;
14445  out = fopen(zFilename, "w");
14446  if( out==0 ){
14447    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14448                    zFilename);
14449    return;
14450  }
14451  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14452    char *z = (char*)pHdr;
14453    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
14454    fprintf(out, "**** %lld bytes at %p from %s ****\n",
14455            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
14456    if( pHdr->nBacktrace ){
14457      fflush(out);
14458      pBt = (void**)pHdr;
14459      pBt -= pHdr->nBacktraceSlots;
14460      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
14461      fprintf(out, "\n");
14462    }
14463  }
14464  fprintf(out, "COUNTS:\n");
14465  for(i=0; i<NCSIZE-1; i++){
14466    if( mem.nAlloc[i] ){
14467      fprintf(out, "   %5d: %10d %10d %10d\n",
14468            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
14469    }
14470  }
14471  if( mem.nAlloc[NCSIZE-1] ){
14472    fprintf(out, "   %5d: %10d %10d %10d\n",
14473             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
14474             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
14475  }
14476  fclose(out);
14477}
14478
14479/*
14480** Return the number of times sqlite3MemMalloc() has been called.
14481*/
14482SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
14483  int i;
14484  int nTotal = 0;
14485  for(i=0; i<NCSIZE; i++){
14486    nTotal += mem.nAlloc[i];
14487  }
14488  return nTotal;
14489}
14490
14491
14492#endif /* SQLITE_MEMDEBUG */
14493
14494/************** End of mem2.c ************************************************/
14495/************** Begin file mem3.c ********************************************/
14496/*
14497** 2007 October 14
14498**
14499** The author disclaims copyright to this source code.  In place of
14500** a legal notice, here is a blessing:
14501**
14502**    May you do good and not evil.
14503**    May you find forgiveness for yourself and forgive others.
14504**    May you share freely, never taking more than you give.
14505**
14506*************************************************************************
14507** This file contains the C functions that implement a memory
14508** allocation subsystem for use by SQLite.
14509**
14510** This version of the memory allocation subsystem omits all
14511** use of malloc(). The SQLite user supplies a block of memory
14512** before calling sqlite3_initialize() from which allocations
14513** are made and returned by the xMalloc() and xRealloc()
14514** implementations. Once sqlite3_initialize() has been called,
14515** the amount of memory available to SQLite is fixed and cannot
14516** be changed.
14517**
14518** This version of the memory allocation subsystem is included
14519** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
14520*/
14521
14522/*
14523** This version of the memory allocator is only built into the library
14524** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
14525** mean that the library will use a memory-pool by default, just that
14526** it is available. The mempool allocator is activated by calling
14527** sqlite3_config().
14528*/
14529#ifdef SQLITE_ENABLE_MEMSYS3
14530
14531/*
14532** Maximum size (in Mem3Blocks) of a "small" chunk.
14533*/
14534#define MX_SMALL 10
14535
14536
14537/*
14538** Number of freelist hash slots
14539*/
14540#define N_HASH  61
14541
14542/*
14543** A memory allocation (also called a "chunk") consists of two or
14544** more blocks where each block is 8 bytes.  The first 8 bytes are
14545** a header that is not returned to the user.
14546**
14547** A chunk is two or more blocks that is either checked out or
14548** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
14549** size of the allocation in blocks if the allocation is free.
14550** The u.hdr.size4x&1 bit is true if the chunk is checked out and
14551** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
14552** is true if the previous chunk is checked out and false if the
14553** previous chunk is free.  The u.hdr.prevSize field is the size of
14554** the previous chunk in blocks if the previous chunk is on the
14555** freelist. If the previous chunk is checked out, then
14556** u.hdr.prevSize can be part of the data for that chunk and should
14557** not be read or written.
14558**
14559** We often identify a chunk by its index in mem3.aPool[].  When
14560** this is done, the chunk index refers to the second block of
14561** the chunk.  In this way, the first chunk has an index of 1.
14562** A chunk index of 0 means "no such chunk" and is the equivalent
14563** of a NULL pointer.
14564**
14565** The second block of free chunks is of the form u.list.  The
14566** two fields form a double-linked list of chunks of related sizes.
14567** Pointers to the head of the list are stored in mem3.aiSmall[]
14568** for smaller chunks and mem3.aiHash[] for larger chunks.
14569**
14570** The second block of a chunk is user data if the chunk is checked
14571** out.  If a chunk is checked out, the user data may extend into
14572** the u.hdr.prevSize value of the following chunk.
14573*/
14574typedef struct Mem3Block Mem3Block;
14575struct Mem3Block {
14576  union {
14577    struct {
14578      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
14579      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
14580    } hdr;
14581    struct {
14582      u32 next;       /* Index in mem3.aPool[] of next free chunk */
14583      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14584    } list;
14585  } u;
14586};
14587
14588/*
14589** All of the static variables used by this module are collected
14590** into a single structure named "mem3".  This is to keep the
14591** static variables organized and to reduce namespace pollution
14592** when this module is combined with other in the amalgamation.
14593*/
14594static SQLITE_WSD struct Mem3Global {
14595  /*
14596  ** Memory available for allocation. nPool is the size of the array
14597  ** (in Mem3Blocks) pointed to by aPool less 2.
14598  */
14599  u32 nPool;
14600  Mem3Block *aPool;
14601
14602  /*
14603  ** True if we are evaluating an out-of-memory callback.
14604  */
14605  int alarmBusy;
14606
14607  /*
14608  ** Mutex to control access to the memory allocation subsystem.
14609  */
14610  sqlite3_mutex *mutex;
14611
14612  /*
14613  ** The minimum amount of free space that we have seen.
14614  */
14615  u32 mnMaster;
14616
14617  /*
14618  ** iMaster is the index of the master chunk.  Most new allocations
14619  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14620  ** of the current master.  iMaster is 0 if there is not master chunk.
14621  ** The master chunk is not in either the aiHash[] or aiSmall[].
14622  */
14623  u32 iMaster;
14624  u32 szMaster;
14625
14626  /*
14627  ** Array of lists of free blocks according to the block size
14628  ** for smaller chunks, or a hash on the block size for larger
14629  ** chunks.
14630  */
14631  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14632  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
14633} mem3 = { 97535575 };
14634
14635#define mem3 GLOBAL(struct Mem3Global, mem3)
14636
14637/*
14638** Unlink the chunk at mem3.aPool[i] from list it is currently
14639** on.  *pRoot is the list that i is a member of.
14640*/
14641static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
14642  u32 next = mem3.aPool[i].u.list.next;
14643  u32 prev = mem3.aPool[i].u.list.prev;
14644  assert( sqlite3_mutex_held(mem3.mutex) );
14645  if( prev==0 ){
14646    *pRoot = next;
14647  }else{
14648    mem3.aPool[prev].u.list.next = next;
14649  }
14650  if( next ){
14651    mem3.aPool[next].u.list.prev = prev;
14652  }
14653  mem3.aPool[i].u.list.next = 0;
14654  mem3.aPool[i].u.list.prev = 0;
14655}
14656
14657/*
14658** Unlink the chunk at index i from
14659** whatever list is currently a member of.
14660*/
14661static void memsys3Unlink(u32 i){
14662  u32 size, hash;
14663  assert( sqlite3_mutex_held(mem3.mutex) );
14664  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14665  assert( i>=1 );
14666  size = mem3.aPool[i-1].u.hdr.size4x/4;
14667  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14668  assert( size>=2 );
14669  if( size <= MX_SMALL ){
14670    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
14671  }else{
14672    hash = size % N_HASH;
14673    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14674  }
14675}
14676
14677/*
14678** Link the chunk at mem3.aPool[i] so that is on the list rooted
14679** at *pRoot.
14680*/
14681static void memsys3LinkIntoList(u32 i, u32 *pRoot){
14682  assert( sqlite3_mutex_held(mem3.mutex) );
14683  mem3.aPool[i].u.list.next = *pRoot;
14684  mem3.aPool[i].u.list.prev = 0;
14685  if( *pRoot ){
14686    mem3.aPool[*pRoot].u.list.prev = i;
14687  }
14688  *pRoot = i;
14689}
14690
14691/*
14692** Link the chunk at index i into either the appropriate
14693** small chunk list, or into the large chunk hash table.
14694*/
14695static void memsys3Link(u32 i){
14696  u32 size, hash;
14697  assert( sqlite3_mutex_held(mem3.mutex) );
14698  assert( i>=1 );
14699  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
14700  size = mem3.aPool[i-1].u.hdr.size4x/4;
14701  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
14702  assert( size>=2 );
14703  if( size <= MX_SMALL ){
14704    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
14705  }else{
14706    hash = size % N_HASH;
14707    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
14708  }
14709}
14710
14711/*
14712** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14713** will already be held (obtained by code in malloc.c) if
14714** sqlite3GlobalConfig.bMemStat is true.
14715*/
14716static void memsys3Enter(void){
14717  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
14718    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14719  }
14720  sqlite3_mutex_enter(mem3.mutex);
14721}
14722static void memsys3Leave(void){
14723  sqlite3_mutex_leave(mem3.mutex);
14724}
14725
14726/*
14727** Called when we are unable to satisfy an allocation of nBytes.
14728*/
14729static void memsys3OutOfMemory(int nByte){
14730  if( !mem3.alarmBusy ){
14731    mem3.alarmBusy = 1;
14732    assert( sqlite3_mutex_held(mem3.mutex) );
14733    sqlite3_mutex_leave(mem3.mutex);
14734    sqlite3_release_memory(nByte);
14735    sqlite3_mutex_enter(mem3.mutex);
14736    mem3.alarmBusy = 0;
14737  }
14738}
14739
14740
14741/*
14742** Chunk i is a free chunk that has been unlinked.  Adjust its
14743** size parameters for check-out and return a pointer to the
14744** user portion of the chunk.
14745*/
14746static void *memsys3Checkout(u32 i, u32 nBlock){
14747  u32 x;
14748  assert( sqlite3_mutex_held(mem3.mutex) );
14749  assert( i>=1 );
14750  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
14751  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
14752  x = mem3.aPool[i-1].u.hdr.size4x;
14753  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
14754  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
14755  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
14756  return &mem3.aPool[i];
14757}
14758
14759/*
14760** Carve a piece off of the end of the mem3.iMaster free chunk.
14761** Return a pointer to the new allocation.  Or, if the master chunk
14762** is not large enough, return 0.
14763*/
14764static void *memsys3FromMaster(u32 nBlock){
14765  assert( sqlite3_mutex_held(mem3.mutex) );
14766  assert( mem3.szMaster>=nBlock );
14767  if( nBlock>=mem3.szMaster-1 ){
14768    /* Use the entire master */
14769    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
14770    mem3.iMaster = 0;
14771    mem3.szMaster = 0;
14772    mem3.mnMaster = 0;
14773    return p;
14774  }else{
14775    /* Split the master block.  Return the tail. */
14776    u32 newi, x;
14777    newi = mem3.iMaster + mem3.szMaster - nBlock;
14778    assert( newi > mem3.iMaster+1 );
14779    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
14780    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
14781    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
14782    mem3.szMaster -= nBlock;
14783    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
14784    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14785    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14786    if( mem3.szMaster < mem3.mnMaster ){
14787      mem3.mnMaster = mem3.szMaster;
14788    }
14789    return (void*)&mem3.aPool[newi];
14790  }
14791}
14792
14793/*
14794** *pRoot is the head of a list of free chunks of the same size
14795** or same size hash.  In other words, *pRoot is an entry in either
14796** mem3.aiSmall[] or mem3.aiHash[].
14797**
14798** This routine examines all entries on the given list and tries
14799** to coalesce each entries with adjacent free chunks.
14800**
14801** If it sees a chunk that is larger than mem3.iMaster, it replaces
14802** the current mem3.iMaster with the new larger chunk.  In order for
14803** this mem3.iMaster replacement to work, the master chunk must be
14804** linked into the hash tables.  That is not the normal state of
14805** affairs, of course.  The calling routine must link the master
14806** chunk before invoking this routine, then must unlink the (possibly
14807** changed) master chunk once this routine has finished.
14808*/
14809static void memsys3Merge(u32 *pRoot){
14810  u32 iNext, prev, size, i, x;
14811
14812  assert( sqlite3_mutex_held(mem3.mutex) );
14813  for(i=*pRoot; i>0; i=iNext){
14814    iNext = mem3.aPool[i].u.list.next;
14815    size = mem3.aPool[i-1].u.hdr.size4x;
14816    assert( (size&1)==0 );
14817    if( (size&2)==0 ){
14818      memsys3UnlinkFromList(i, pRoot);
14819      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
14820      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
14821      if( prev==iNext ){
14822        iNext = mem3.aPool[prev].u.list.next;
14823      }
14824      memsys3Unlink(prev);
14825      size = i + size/4 - prev;
14826      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
14827      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
14828      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
14829      memsys3Link(prev);
14830      i = prev;
14831    }else{
14832      size /= 4;
14833    }
14834    if( size>mem3.szMaster ){
14835      mem3.iMaster = i;
14836      mem3.szMaster = size;
14837    }
14838  }
14839}
14840
14841/*
14842** Return a block of memory of at least nBytes in size.
14843** Return NULL if unable.
14844**
14845** This function assumes that the necessary mutexes, if any, are
14846** already held by the caller. Hence "Unsafe".
14847*/
14848static void *memsys3MallocUnsafe(int nByte){
14849  u32 i;
14850  u32 nBlock;
14851  u32 toFree;
14852
14853  assert( sqlite3_mutex_held(mem3.mutex) );
14854  assert( sizeof(Mem3Block)==8 );
14855  if( nByte<=12 ){
14856    nBlock = 2;
14857  }else{
14858    nBlock = (nByte + 11)/8;
14859  }
14860  assert( nBlock>=2 );
14861
14862  /* STEP 1:
14863  ** Look for an entry of the correct size in either the small
14864  ** chunk table or in the large chunk hash table.  This is
14865  ** successful most of the time (about 9 times out of 10).
14866  */
14867  if( nBlock <= MX_SMALL ){
14868    i = mem3.aiSmall[nBlock-2];
14869    if( i>0 ){
14870      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
14871      return memsys3Checkout(i, nBlock);
14872    }
14873  }else{
14874    int hash = nBlock % N_HASH;
14875    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
14876      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
14877        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
14878        return memsys3Checkout(i, nBlock);
14879      }
14880    }
14881  }
14882
14883  /* STEP 2:
14884  ** Try to satisfy the allocation by carving a piece off of the end
14885  ** of the master chunk.  This step usually works if step 1 fails.
14886  */
14887  if( mem3.szMaster>=nBlock ){
14888    return memsys3FromMaster(nBlock);
14889  }
14890
14891
14892  /* STEP 3:
14893  ** Loop through the entire memory pool.  Coalesce adjacent free
14894  ** chunks.  Recompute the master chunk as the largest free chunk.
14895  ** Then try again to satisfy the allocation by carving a piece off
14896  ** of the end of the master chunk.  This step happens very
14897  ** rarely (we hope!)
14898  */
14899  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
14900    memsys3OutOfMemory(toFree);
14901    if( mem3.iMaster ){
14902      memsys3Link(mem3.iMaster);
14903      mem3.iMaster = 0;
14904      mem3.szMaster = 0;
14905    }
14906    for(i=0; i<N_HASH; i++){
14907      memsys3Merge(&mem3.aiHash[i]);
14908    }
14909    for(i=0; i<MX_SMALL-1; i++){
14910      memsys3Merge(&mem3.aiSmall[i]);
14911    }
14912    if( mem3.szMaster ){
14913      memsys3Unlink(mem3.iMaster);
14914      if( mem3.szMaster>=nBlock ){
14915        return memsys3FromMaster(nBlock);
14916      }
14917    }
14918  }
14919
14920  /* If none of the above worked, then we fail. */
14921  return 0;
14922}
14923
14924/*
14925** Free an outstanding memory allocation.
14926**
14927** This function assumes that the necessary mutexes, if any, are
14928** already held by the caller. Hence "Unsafe".
14929*/
14930void memsys3FreeUnsafe(void *pOld){
14931  Mem3Block *p = (Mem3Block*)pOld;
14932  int i;
14933  u32 size, x;
14934  assert( sqlite3_mutex_held(mem3.mutex) );
14935  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
14936  i = p - mem3.aPool;
14937  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14938  size = mem3.aPool[i-1].u.hdr.size4x/4;
14939  assert( i+size<=mem3.nPool+1 );
14940  mem3.aPool[i-1].u.hdr.size4x &= ~1;
14941  mem3.aPool[i+size-1].u.hdr.prevSize = size;
14942  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14943  memsys3Link(i);
14944
14945  /* Try to expand the master using the newly freed chunk */
14946  if( mem3.iMaster ){
14947    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14948      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14949      mem3.iMaster -= size;
14950      mem3.szMaster += size;
14951      memsys3Unlink(mem3.iMaster);
14952      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14953      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14954      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14955    }
14956    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14957    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14958      memsys3Unlink(mem3.iMaster+mem3.szMaster);
14959      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14960      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14961      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14962    }
14963  }
14964}
14965
14966/*
14967** Return the size of an outstanding allocation, in bytes.  The
14968** size returned omits the 8-byte header overhead.  This only
14969** works for chunks that are currently checked out.
14970*/
14971static int memsys3Size(void *p){
14972  Mem3Block *pBlock;
14973  if( p==0 ) return 0;
14974  pBlock = (Mem3Block*)p;
14975  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14976  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14977}
14978
14979/*
14980** Round up a request size to the next valid allocation size.
14981*/
14982static int memsys3Roundup(int n){
14983  if( n<=12 ){
14984    return 12;
14985  }else{
14986    return ((n+11)&~7) - 4;
14987  }
14988}
14989
14990/*
14991** Allocate nBytes of memory.
14992*/
14993static void *memsys3Malloc(int nBytes){
14994  sqlite3_int64 *p;
14995  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14996  memsys3Enter();
14997  p = memsys3MallocUnsafe(nBytes);
14998  memsys3Leave();
14999  return (void*)p;
15000}
15001
15002/*
15003** Free memory.
15004*/
15005void memsys3Free(void *pPrior){
15006  assert( pPrior );
15007  memsys3Enter();
15008  memsys3FreeUnsafe(pPrior);
15009  memsys3Leave();
15010}
15011
15012/*
15013** Change the size of an existing memory allocation
15014*/
15015void *memsys3Realloc(void *pPrior, int nBytes){
15016  int nOld;
15017  void *p;
15018  if( pPrior==0 ){
15019    return sqlite3_malloc(nBytes);
15020  }
15021  if( nBytes<=0 ){
15022    sqlite3_free(pPrior);
15023    return 0;
15024  }
15025  nOld = memsys3Size(pPrior);
15026  if( nBytes<=nOld && nBytes>=nOld-128 ){
15027    return pPrior;
15028  }
15029  memsys3Enter();
15030  p = memsys3MallocUnsafe(nBytes);
15031  if( p ){
15032    if( nOld<nBytes ){
15033      memcpy(p, pPrior, nOld);
15034    }else{
15035      memcpy(p, pPrior, nBytes);
15036    }
15037    memsys3FreeUnsafe(pPrior);
15038  }
15039  memsys3Leave();
15040  return p;
15041}
15042
15043/*
15044** Initialize this module.
15045*/
15046static int memsys3Init(void *NotUsed){
15047  UNUSED_PARAMETER(NotUsed);
15048  if( !sqlite3GlobalConfig.pHeap ){
15049    return SQLITE_ERROR;
15050  }
15051
15052  /* Store a pointer to the memory block in global structure mem3. */
15053  assert( sizeof(Mem3Block)==8 );
15054  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15055  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15056
15057  /* Initialize the master block. */
15058  mem3.szMaster = mem3.nPool;
15059  mem3.mnMaster = mem3.szMaster;
15060  mem3.iMaster = 1;
15061  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15062  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15063  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15064
15065  return SQLITE_OK;
15066}
15067
15068/*
15069** Deinitialize this module.
15070*/
15071static void memsys3Shutdown(void *NotUsed){
15072  UNUSED_PARAMETER(NotUsed);
15073  mem3.mutex = 0;
15074  return;
15075}
15076
15077
15078
15079/*
15080** Open the file indicated and write a log of all unfreed memory
15081** allocations into that log.
15082*/
15083SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15084#ifdef SQLITE_DEBUG
15085  FILE *out;
15086  u32 i, j;
15087  u32 size;
15088  if( zFilename==0 || zFilename[0]==0 ){
15089    out = stdout;
15090  }else{
15091    out = fopen(zFilename, "w");
15092    if( out==0 ){
15093      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15094                      zFilename);
15095      return;
15096    }
15097  }
15098  memsys3Enter();
15099  fprintf(out, "CHUNKS:\n");
15100  for(i=1; i<=mem3.nPool; i+=size/4){
15101    size = mem3.aPool[i-1].u.hdr.size4x;
15102    if( size/4<=1 ){
15103      fprintf(out, "%p size error\n", &mem3.aPool[i]);
15104      assert( 0 );
15105      break;
15106    }
15107    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15108      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15109      assert( 0 );
15110      break;
15111    }
15112    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15113      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15114      assert( 0 );
15115      break;
15116    }
15117    if( size&1 ){
15118      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15119    }else{
15120      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15121                  i==mem3.iMaster ? " **master**" : "");
15122    }
15123  }
15124  for(i=0; i<MX_SMALL-1; i++){
15125    if( mem3.aiSmall[i]==0 ) continue;
15126    fprintf(out, "small(%2d):", i);
15127    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15128      fprintf(out, " %p(%d)", &mem3.aPool[j],
15129              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15130    }
15131    fprintf(out, "\n");
15132  }
15133  for(i=0; i<N_HASH; i++){
15134    if( mem3.aiHash[i]==0 ) continue;
15135    fprintf(out, "hash(%2d):", i);
15136    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15137      fprintf(out, " %p(%d)", &mem3.aPool[j],
15138              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15139    }
15140    fprintf(out, "\n");
15141  }
15142  fprintf(out, "master=%d\n", mem3.iMaster);
15143  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15144  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15145  sqlite3_mutex_leave(mem3.mutex);
15146  if( out==stdout ){
15147    fflush(stdout);
15148  }else{
15149    fclose(out);
15150  }
15151#else
15152  UNUSED_PARAMETER(zFilename);
15153#endif
15154}
15155
15156/*
15157** This routine is the only routine in this file with external
15158** linkage.
15159**
15160** Populate the low-level memory allocation function pointers in
15161** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15162** arguments specify the block of memory to manage.
15163**
15164** This routine is only called by sqlite3_config(), and therefore
15165** is not required to be threadsafe (it is not).
15166*/
15167SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15168  static const sqlite3_mem_methods mempoolMethods = {
15169     memsys3Malloc,
15170     memsys3Free,
15171     memsys3Realloc,
15172     memsys3Size,
15173     memsys3Roundup,
15174     memsys3Init,
15175     memsys3Shutdown,
15176     0
15177  };
15178  return &mempoolMethods;
15179}
15180
15181#endif /* SQLITE_ENABLE_MEMSYS3 */
15182
15183/************** End of mem3.c ************************************************/
15184/************** Begin file mem5.c ********************************************/
15185/*
15186** 2007 October 14
15187**
15188** The author disclaims copyright to this source code.  In place of
15189** a legal notice, here is a blessing:
15190**
15191**    May you do good and not evil.
15192**    May you find forgiveness for yourself and forgive others.
15193**    May you share freely, never taking more than you give.
15194**
15195*************************************************************************
15196** This file contains the C functions that implement a memory
15197** allocation subsystem for use by SQLite.
15198**
15199** This version of the memory allocation subsystem omits all
15200** use of malloc(). The application gives SQLite a block of memory
15201** before calling sqlite3_initialize() from which allocations
15202** are made and returned by the xMalloc() and xRealloc()
15203** implementations. Once sqlite3_initialize() has been called,
15204** the amount of memory available to SQLite is fixed and cannot
15205** be changed.
15206**
15207** This version of the memory allocation subsystem is included
15208** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15209**
15210** This memory allocator uses the following algorithm:
15211**
15212**   1.  All memory allocations sizes are rounded up to a power of 2.
15213**
15214**   2.  If two adjacent free blocks are the halves of a larger block,
15215**       then the two blocks are coalesed into the single larger block.
15216**
15217**   3.  New memory is allocated from the first available free block.
15218**
15219** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15220** Concerning Dynamic Storage Allocation". Journal of the Association for
15221** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15222**
15223** Let n be the size of the largest allocation divided by the minimum
15224** allocation size (after rounding all sizes up to a power of 2.)  Let M
15225** be the maximum amount of memory ever outstanding at one time.  Let
15226** N be the total amount of memory available for allocation.  Robson
15227** proved that this memory allocator will never breakdown due to
15228** fragmentation as long as the following constraint holds:
15229**
15230**      N >=  M*(1 + log2(n)/2) - n + 1
15231**
15232** The sqlite3_status() logic tracks the maximum values of n and M so
15233** that an application can, at any time, verify this constraint.
15234*/
15235
15236/*
15237** This version of the memory allocator is used only when
15238** SQLITE_ENABLE_MEMSYS5 is defined.
15239*/
15240#ifdef SQLITE_ENABLE_MEMSYS5
15241
15242/*
15243** A minimum allocation is an instance of the following structure.
15244** Larger allocations are an array of these structures where the
15245** size of the array is a power of 2.
15246**
15247** The size of this object must be a power of two.  That fact is
15248** verified in memsys5Init().
15249*/
15250typedef struct Mem5Link Mem5Link;
15251struct Mem5Link {
15252  int next;       /* Index of next free chunk */
15253  int prev;       /* Index of previous free chunk */
15254};
15255
15256/*
15257** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15258** mem5.szAtom is always at least 8 and 32-bit integers are used,
15259** it is not actually possible to reach this limit.
15260*/
15261#define LOGMAX 30
15262
15263/*
15264** Masks used for mem5.aCtrl[] elements.
15265*/
15266#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15267#define CTRL_FREE     0x20    /* True if not checked out */
15268
15269/*
15270** All of the static variables used by this module are collected
15271** into a single structure named "mem5".  This is to keep the
15272** static variables organized and to reduce namespace pollution
15273** when this module is combined with other in the amalgamation.
15274*/
15275static SQLITE_WSD struct Mem5Global {
15276  /*
15277  ** Memory available for allocation
15278  */
15279  int szAtom;      /* Smallest possible allocation in bytes */
15280  int nBlock;      /* Number of szAtom sized blocks in zPool */
15281  u8 *zPool;       /* Memory available to be allocated */
15282
15283  /*
15284  ** Mutex to control access to the memory allocation subsystem.
15285  */
15286  sqlite3_mutex *mutex;
15287
15288  /*
15289  ** Performance statistics
15290  */
15291  u64 nAlloc;         /* Total number of calls to malloc */
15292  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15293  u64 totalExcess;    /* Total internal fragmentation */
15294  u32 currentOut;     /* Current checkout, including internal fragmentation */
15295  u32 currentCount;   /* Current number of distinct checkouts */
15296  u32 maxOut;         /* Maximum instantaneous currentOut */
15297  u32 maxCount;       /* Maximum instantaneous currentCount */
15298  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15299
15300  /*
15301  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15302  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15303  ** and so forth.
15304  */
15305  int aiFreelist[LOGMAX+1];
15306
15307  /*
15308  ** Space for tracking which blocks are checked out and the size
15309  ** of each block.  One byte per block.
15310  */
15311  u8 *aCtrl;
15312
15313} mem5 = { 0 };
15314
15315/*
15316** Access the static variable through a macro for SQLITE_OMIT_WSD
15317*/
15318#define mem5 GLOBAL(struct Mem5Global, mem5)
15319
15320/*
15321** Assuming mem5.zPool is divided up into an array of Mem5Link
15322** structures, return a pointer to the idx-th such lik.
15323*/
15324#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15325
15326/*
15327** Unlink the chunk at mem5.aPool[i] from list it is currently
15328** on.  It should be found on mem5.aiFreelist[iLogsize].
15329*/
15330static void memsys5Unlink(int i, int iLogsize){
15331  int next, prev;
15332  assert( i>=0 && i<mem5.nBlock );
15333  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15334  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15335
15336  next = MEM5LINK(i)->next;
15337  prev = MEM5LINK(i)->prev;
15338  if( prev<0 ){
15339    mem5.aiFreelist[iLogsize] = next;
15340  }else{
15341    MEM5LINK(prev)->next = next;
15342  }
15343  if( next>=0 ){
15344    MEM5LINK(next)->prev = prev;
15345  }
15346}
15347
15348/*
15349** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15350** free list.
15351*/
15352static void memsys5Link(int i, int iLogsize){
15353  int x;
15354  assert( sqlite3_mutex_held(mem5.mutex) );
15355  assert( i>=0 && i<mem5.nBlock );
15356  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15357  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15358
15359  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15360  MEM5LINK(i)->prev = -1;
15361  if( x>=0 ){
15362    assert( x<mem5.nBlock );
15363    MEM5LINK(x)->prev = i;
15364  }
15365  mem5.aiFreelist[iLogsize] = i;
15366}
15367
15368/*
15369** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15370** will already be held (obtained by code in malloc.c) if
15371** sqlite3GlobalConfig.bMemStat is true.
15372*/
15373static void memsys5Enter(void){
15374  sqlite3_mutex_enter(mem5.mutex);
15375}
15376static void memsys5Leave(void){
15377  sqlite3_mutex_leave(mem5.mutex);
15378}
15379
15380/*
15381** Return the size of an outstanding allocation, in bytes.  The
15382** size returned omits the 8-byte header overhead.  This only
15383** works for chunks that are currently checked out.
15384*/
15385static int memsys5Size(void *p){
15386  int iSize = 0;
15387  if( p ){
15388    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15389    assert( i>=0 && i<mem5.nBlock );
15390    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15391  }
15392  return iSize;
15393}
15394
15395/*
15396** Find the first entry on the freelist iLogsize.  Unlink that
15397** entry and return its index.
15398*/
15399static int memsys5UnlinkFirst(int iLogsize){
15400  int i;
15401  int iFirst;
15402
15403  assert( iLogsize>=0 && iLogsize<=LOGMAX );
15404  i = iFirst = mem5.aiFreelist[iLogsize];
15405  assert( iFirst>=0 );
15406  while( i>0 ){
15407    if( i<iFirst ) iFirst = i;
15408    i = MEM5LINK(i)->next;
15409  }
15410  memsys5Unlink(iFirst, iLogsize);
15411  return iFirst;
15412}
15413
15414/*
15415** Return a block of memory of at least nBytes in size.
15416** Return NULL if unable.  Return NULL if nBytes==0.
15417**
15418** The caller guarantees that nByte positive.
15419**
15420** The caller has obtained a mutex prior to invoking this
15421** routine so there is never any chance that two or more
15422** threads can be in this routine at the same time.
15423*/
15424static void *memsys5MallocUnsafe(int nByte){
15425  int i;           /* Index of a mem5.aPool[] slot */
15426  int iBin;        /* Index into mem5.aiFreelist[] */
15427  int iFullSz;     /* Size of allocation rounded up to power of 2 */
15428  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
15429
15430  /* nByte must be a positive */
15431  assert( nByte>0 );
15432
15433  /* Keep track of the maximum allocation request.  Even unfulfilled
15434  ** requests are counted */
15435  if( (u32)nByte>mem5.maxRequest ){
15436    mem5.maxRequest = nByte;
15437  }
15438
15439  /* Abort if the requested allocation size is larger than the largest
15440  ** power of two that we can represent using 32-bit signed integers.
15441  */
15442  if( nByte > 0x40000000 ){
15443    return 0;
15444  }
15445
15446  /* Round nByte up to the next valid power of two */
15447  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
15448
15449  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
15450  ** block.  If not, then split a block of the next larger power of
15451  ** two in order to create a new free block of size iLogsize.
15452  */
15453  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
15454  if( iBin>LOGMAX ){
15455    testcase( sqlite3GlobalConfig.xLog!=0 );
15456    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
15457    return 0;
15458  }
15459  i = memsys5UnlinkFirst(iBin);
15460  while( iBin>iLogsize ){
15461    int newSize;
15462
15463    iBin--;
15464    newSize = 1 << iBin;
15465    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
15466    memsys5Link(i+newSize, iBin);
15467  }
15468  mem5.aCtrl[i] = iLogsize;
15469
15470  /* Update allocator performance statistics. */
15471  mem5.nAlloc++;
15472  mem5.totalAlloc += iFullSz;
15473  mem5.totalExcess += iFullSz - nByte;
15474  mem5.currentCount++;
15475  mem5.currentOut += iFullSz;
15476  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
15477  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
15478
15479  /* Return a pointer to the allocated memory. */
15480  return (void*)&mem5.zPool[i*mem5.szAtom];
15481}
15482
15483/*
15484** Free an outstanding memory allocation.
15485*/
15486static void memsys5FreeUnsafe(void *pOld){
15487  u32 size, iLogsize;
15488  int iBlock;
15489
15490  /* Set iBlock to the index of the block pointed to by pOld in
15491  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
15492  */
15493  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
15494
15495  /* Check that the pointer pOld points to a valid, non-free block. */
15496  assert( iBlock>=0 && iBlock<mem5.nBlock );
15497  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
15498  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
15499
15500  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
15501  size = 1<<iLogsize;
15502  assert( iBlock+size-1<(u32)mem5.nBlock );
15503
15504  mem5.aCtrl[iBlock] |= CTRL_FREE;
15505  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
15506  assert( mem5.currentCount>0 );
15507  assert( mem5.currentOut>=(size*mem5.szAtom) );
15508  mem5.currentCount--;
15509  mem5.currentOut -= size*mem5.szAtom;
15510  assert( mem5.currentOut>0 || mem5.currentCount==0 );
15511  assert( mem5.currentCount>0 || mem5.currentOut==0 );
15512
15513  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15514  while( ALWAYS(iLogsize<LOGMAX) ){
15515    int iBuddy;
15516    if( (iBlock>>iLogsize) & 1 ){
15517      iBuddy = iBlock - size;
15518    }else{
15519      iBuddy = iBlock + size;
15520    }
15521    assert( iBuddy>=0 );
15522    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
15523    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
15524    memsys5Unlink(iBuddy, iLogsize);
15525    iLogsize++;
15526    if( iBuddy<iBlock ){
15527      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
15528      mem5.aCtrl[iBlock] = 0;
15529      iBlock = iBuddy;
15530    }else{
15531      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15532      mem5.aCtrl[iBuddy] = 0;
15533    }
15534    size *= 2;
15535  }
15536  memsys5Link(iBlock, iLogsize);
15537}
15538
15539/*
15540** Allocate nBytes of memory
15541*/
15542static void *memsys5Malloc(int nBytes){
15543  sqlite3_int64 *p = 0;
15544  if( nBytes>0 ){
15545    memsys5Enter();
15546    p = memsys5MallocUnsafe(nBytes);
15547    memsys5Leave();
15548  }
15549  return (void*)p;
15550}
15551
15552/*
15553** Free memory.
15554**
15555** The outer layer memory allocator prevents this routine from
15556** being called with pPrior==0.
15557*/
15558static void memsys5Free(void *pPrior){
15559  assert( pPrior!=0 );
15560  memsys5Enter();
15561  memsys5FreeUnsafe(pPrior);
15562  memsys5Leave();
15563}
15564
15565/*
15566** Change the size of an existing memory allocation.
15567**
15568** The outer layer memory allocator prevents this routine from
15569** being called with pPrior==0.
15570**
15571** nBytes is always a value obtained from a prior call to
15572** memsys5Round().  Hence nBytes is always a non-negative power
15573** of two.  If nBytes==0 that means that an oversize allocation
15574** (an allocation larger than 0x40000000) was requested and this
15575** routine should return 0 without freeing pPrior.
15576*/
15577static void *memsys5Realloc(void *pPrior, int nBytes){
15578  int nOld;
15579  void *p;
15580  assert( pPrior!=0 );
15581  assert( (nBytes&(nBytes-1))==0 );
15582  assert( nBytes>=0 );
15583  if( nBytes==0 ){
15584    return 0;
15585  }
15586  nOld = memsys5Size(pPrior);
15587  if( nBytes<=nOld ){
15588    return pPrior;
15589  }
15590  memsys5Enter();
15591  p = memsys5MallocUnsafe(nBytes);
15592  if( p ){
15593    memcpy(p, pPrior, nOld);
15594    memsys5FreeUnsafe(pPrior);
15595  }
15596  memsys5Leave();
15597  return p;
15598}
15599
15600/*
15601** Round up a request size to the next valid allocation size.  If
15602** the allocation is too large to be handled by this allocation system,
15603** return 0.
15604**
15605** All allocations must be a power of two and must be expressed by a
15606** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15607** or 1073741824 bytes.
15608*/
15609static int memsys5Roundup(int n){
15610  int iFullSz;
15611  if( n > 0x40000000 ) return 0;
15612  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15613  return iFullSz;
15614}
15615
15616/*
15617** Return the ceiling of the logarithm base 2 of iValue.
15618**
15619** Examples:   memsys5Log(1) -> 0
15620**             memsys5Log(2) -> 1
15621**             memsys5Log(4) -> 2
15622**             memsys5Log(5) -> 3
15623**             memsys5Log(8) -> 3
15624**             memsys5Log(9) -> 4
15625*/
15626static int memsys5Log(int iValue){
15627  int iLog;
15628  for(iLog=0; (1<<iLog)<iValue; iLog++);
15629  return iLog;
15630}
15631
15632/*
15633** Initialize the memory allocator.
15634**
15635** This routine is not threadsafe.  The caller must be holding a mutex
15636** to prevent multiple threads from entering at the same time.
15637*/
15638static int memsys5Init(void *NotUsed){
15639  int ii;            /* Loop counter */
15640  int nByte;         /* Number of bytes of memory available to this allocator */
15641  u8 *zByte;         /* Memory usable by this allocator */
15642  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
15643  int iOffset;       /* An offset into mem5.aCtrl[] */
15644
15645  UNUSED_PARAMETER(NotUsed);
15646
15647  /* For the purposes of this routine, disable the mutex */
15648  mem5.mutex = 0;
15649
15650  /* The size of a Mem5Link object must be a power of two.  Verify that
15651  ** this is case.
15652  */
15653  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
15654
15655  nByte = sqlite3GlobalConfig.nHeap;
15656  zByte = (u8*)sqlite3GlobalConfig.pHeap;
15657  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
15658
15659  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
15660  mem5.szAtom = (1<<nMinLog);
15661  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
15662    mem5.szAtom = mem5.szAtom << 1;
15663  }
15664
15665  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
15666  mem5.zPool = zByte;
15667  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
15668
15669  for(ii=0; ii<=LOGMAX; ii++){
15670    mem5.aiFreelist[ii] = -1;
15671  }
15672
15673  iOffset = 0;
15674  for(ii=LOGMAX; ii>=0; ii--){
15675    int nAlloc = (1<<ii);
15676    if( (iOffset+nAlloc)<=mem5.nBlock ){
15677      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
15678      memsys5Link(iOffset, ii);
15679      iOffset += nAlloc;
15680    }
15681    assert((iOffset+nAlloc)>mem5.nBlock);
15682  }
15683
15684  /* If a mutex is required for normal operation, allocate one */
15685  if( sqlite3GlobalConfig.bMemstat==0 ){
15686    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15687  }
15688
15689  return SQLITE_OK;
15690}
15691
15692/*
15693** Deinitialize this module.
15694*/
15695static void memsys5Shutdown(void *NotUsed){
15696  UNUSED_PARAMETER(NotUsed);
15697  mem5.mutex = 0;
15698  return;
15699}
15700
15701#ifdef SQLITE_TEST
15702/*
15703** Open the file indicated and write a log of all unfreed memory
15704** allocations into that log.
15705*/
15706SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
15707  FILE *out;
15708  int i, j, n;
15709  int nMinLog;
15710
15711  if( zFilename==0 || zFilename[0]==0 ){
15712    out = stdout;
15713  }else{
15714    out = fopen(zFilename, "w");
15715    if( out==0 ){
15716      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15717                      zFilename);
15718      return;
15719    }
15720  }
15721  memsys5Enter();
15722  nMinLog = memsys5Log(mem5.szAtom);
15723  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
15724    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
15725    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
15726  }
15727  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
15728  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
15729  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
15730  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
15731  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
15732  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
15733  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
15734  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
15735  memsys5Leave();
15736  if( out==stdout ){
15737    fflush(stdout);
15738  }else{
15739    fclose(out);
15740  }
15741}
15742#endif
15743
15744/*
15745** This routine is the only routine in this file with external
15746** linkage. It returns a pointer to a static sqlite3_mem_methods
15747** struct populated with the memsys5 methods.
15748*/
15749SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
15750  static const sqlite3_mem_methods memsys5Methods = {
15751     memsys5Malloc,
15752     memsys5Free,
15753     memsys5Realloc,
15754     memsys5Size,
15755     memsys5Roundup,
15756     memsys5Init,
15757     memsys5Shutdown,
15758     0
15759  };
15760  return &memsys5Methods;
15761}
15762
15763#endif /* SQLITE_ENABLE_MEMSYS5 */
15764
15765/************** End of mem5.c ************************************************/
15766/************** Begin file mutex.c *******************************************/
15767/*
15768** 2007 August 14
15769**
15770** The author disclaims copyright to this source code.  In place of
15771** a legal notice, here is a blessing:
15772**
15773**    May you do good and not evil.
15774**    May you find forgiveness for yourself and forgive others.
15775**    May you share freely, never taking more than you give.
15776**
15777*************************************************************************
15778** This file contains the C functions that implement mutexes.
15779**
15780** This file contains code that is common across all mutex implementations.
15781*/
15782
15783#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
15784/*
15785** For debugging purposes, record when the mutex subsystem is initialized
15786** and uninitialized so that we can assert() if there is an attempt to
15787** allocate a mutex while the system is uninitialized.
15788*/
15789static SQLITE_WSD int mutexIsInit = 0;
15790#endif /* SQLITE_DEBUG */
15791
15792
15793#ifndef SQLITE_MUTEX_OMIT
15794/*
15795** Initialize the mutex system.
15796*/
15797SQLITE_PRIVATE int sqlite3MutexInit(void){
15798  int rc = SQLITE_OK;
15799  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
15800    /* If the xMutexAlloc method has not been set, then the user did not
15801    ** install a mutex implementation via sqlite3_config() prior to
15802    ** sqlite3_initialize() being called. This block copies pointers to
15803    ** the default implementation into the sqlite3GlobalConfig structure.
15804    */
15805    sqlite3_mutex_methods const *pFrom;
15806    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
15807
15808    if( sqlite3GlobalConfig.bCoreMutex ){
15809      pFrom = sqlite3DefaultMutex();
15810    }else{
15811      pFrom = sqlite3NoopMutex();
15812    }
15813    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
15814    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
15815           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
15816    pTo->xMutexAlloc = pFrom->xMutexAlloc;
15817  }
15818  rc = sqlite3GlobalConfig.mutex.xMutexInit();
15819
15820#ifdef SQLITE_DEBUG
15821  GLOBAL(int, mutexIsInit) = 1;
15822#endif
15823
15824  return rc;
15825}
15826
15827/*
15828** Shutdown the mutex system. This call frees resources allocated by
15829** sqlite3MutexInit().
15830*/
15831SQLITE_PRIVATE int sqlite3MutexEnd(void){
15832  int rc = SQLITE_OK;
15833  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
15834    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
15835  }
15836
15837#ifdef SQLITE_DEBUG
15838  GLOBAL(int, mutexIsInit) = 0;
15839#endif
15840
15841  return rc;
15842}
15843
15844/*
15845** Retrieve a pointer to a static mutex or allocate a new dynamic one.
15846*/
15847SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
15848#ifndef SQLITE_OMIT_AUTOINIT
15849  if( sqlite3_initialize() ) return 0;
15850#endif
15851  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15852}
15853
15854SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
15855  if( !sqlite3GlobalConfig.bCoreMutex ){
15856    return 0;
15857  }
15858  assert( GLOBAL(int, mutexIsInit) );
15859  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
15860}
15861
15862/*
15863** Free a dynamic mutex.
15864*/
15865SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
15866  if( p ){
15867    sqlite3GlobalConfig.mutex.xMutexFree(p);
15868  }
15869}
15870
15871/*
15872** Obtain the mutex p. If some other thread already has the mutex, block
15873** until it can be obtained.
15874*/
15875SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
15876  if( p ){
15877    sqlite3GlobalConfig.mutex.xMutexEnter(p);
15878  }
15879}
15880
15881/*
15882** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
15883** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
15884*/
15885SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
15886  int rc = SQLITE_OK;
15887  if( p ){
15888    return sqlite3GlobalConfig.mutex.xMutexTry(p);
15889  }
15890  return rc;
15891}
15892
15893/*
15894** The sqlite3_mutex_leave() routine exits a mutex that was previously
15895** entered by the same thread.  The behavior is undefined if the mutex
15896** is not currently entered. If a NULL pointer is passed as an argument
15897** this function is a no-op.
15898*/
15899SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
15900  if( p ){
15901    sqlite3GlobalConfig.mutex.xMutexLeave(p);
15902  }
15903}
15904
15905#ifndef NDEBUG
15906/*
15907** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15908** intended for use inside assert() statements.
15909*/
15910SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
15911  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
15912}
15913SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
15914  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
15915}
15916#endif
15917
15918#endif /* SQLITE_MUTEX_OMIT */
15919
15920/************** End of mutex.c ***********************************************/
15921/************** Begin file mutex_noop.c **************************************/
15922/*
15923** 2008 October 07
15924**
15925** The author disclaims copyright to this source code.  In place of
15926** a legal notice, here is a blessing:
15927**
15928**    May you do good and not evil.
15929**    May you find forgiveness for yourself and forgive others.
15930**    May you share freely, never taking more than you give.
15931**
15932*************************************************************************
15933** This file contains the C functions that implement mutexes.
15934**
15935** This implementation in this file does not provide any mutual
15936** exclusion and is thus suitable for use only in applications
15937** that use SQLite in a single thread.  The routines defined
15938** here are place-holders.  Applications can substitute working
15939** mutex routines at start-time using the
15940**
15941**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15942**
15943** interface.
15944**
15945** If compiled with SQLITE_DEBUG, then additional logic is inserted
15946** that does error checking on mutexes to make sure they are being
15947** called correctly.
15948*/
15949
15950#ifndef SQLITE_MUTEX_OMIT
15951
15952#ifndef SQLITE_DEBUG
15953/*
15954** Stub routines for all mutex methods.
15955**
15956** This routines provide no mutual exclusion or error checking.
15957*/
15958static int noopMutexInit(void){ return SQLITE_OK; }
15959static int noopMutexEnd(void){ return SQLITE_OK; }
15960static sqlite3_mutex *noopMutexAlloc(int id){
15961  UNUSED_PARAMETER(id);
15962  return (sqlite3_mutex*)8;
15963}
15964static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15965static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15966static int noopMutexTry(sqlite3_mutex *p){
15967  UNUSED_PARAMETER(p);
15968  return SQLITE_OK;
15969}
15970static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
15971
15972SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
15973  static const sqlite3_mutex_methods sMutex = {
15974    noopMutexInit,
15975    noopMutexEnd,
15976    noopMutexAlloc,
15977    noopMutexFree,
15978    noopMutexEnter,
15979    noopMutexTry,
15980    noopMutexLeave,
15981
15982    0,
15983    0,
15984  };
15985
15986  return &sMutex;
15987}
15988#endif /* !SQLITE_DEBUG */
15989
15990#ifdef SQLITE_DEBUG
15991/*
15992** In this implementation, error checking is provided for testing
15993** and debugging purposes.  The mutexes still do not provide any
15994** mutual exclusion.
15995*/
15996
15997/*
15998** The mutex object
15999*/
16000typedef struct sqlite3_debug_mutex {
16001  int id;     /* The mutex type */
16002  int cnt;    /* Number of entries without a matching leave */
16003} sqlite3_debug_mutex;
16004
16005/*
16006** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16007** intended for use inside assert() statements.
16008*/
16009static int debugMutexHeld(sqlite3_mutex *pX){
16010  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16011  return p==0 || p->cnt>0;
16012}
16013static int debugMutexNotheld(sqlite3_mutex *pX){
16014  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16015  return p==0 || p->cnt==0;
16016}
16017
16018/*
16019** Initialize and deinitialize the mutex subsystem.
16020*/
16021static int debugMutexInit(void){ return SQLITE_OK; }
16022static int debugMutexEnd(void){ return SQLITE_OK; }
16023
16024/*
16025** The sqlite3_mutex_alloc() routine allocates a new
16026** mutex and returns a pointer to it.  If it returns NULL
16027** that means that a mutex could not be allocated.
16028*/
16029static sqlite3_mutex *debugMutexAlloc(int id){
16030  static sqlite3_debug_mutex aStatic[6];
16031  sqlite3_debug_mutex *pNew = 0;
16032  switch( id ){
16033    case SQLITE_MUTEX_FAST:
16034    case SQLITE_MUTEX_RECURSIVE: {
16035      pNew = sqlite3Malloc(sizeof(*pNew));
16036      if( pNew ){
16037        pNew->id = id;
16038        pNew->cnt = 0;
16039      }
16040      break;
16041    }
16042    default: {
16043      assert( id-2 >= 0 );
16044      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16045      pNew = &aStatic[id-2];
16046      pNew->id = id;
16047      break;
16048    }
16049  }
16050  return (sqlite3_mutex*)pNew;
16051}
16052
16053/*
16054** This routine deallocates a previously allocated mutex.
16055*/
16056static void debugMutexFree(sqlite3_mutex *pX){
16057  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16058  assert( p->cnt==0 );
16059  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16060  sqlite3_free(p);
16061}
16062
16063/*
16064** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16065** to enter a mutex.  If another thread is already within the mutex,
16066** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16067** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16068** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16069** be entered multiple times by the same thread.  In such cases the,
16070** mutex must be exited an equal number of times before another thread
16071** can enter.  If the same thread tries to enter any other kind of mutex
16072** more than once, the behavior is undefined.
16073*/
16074static void debugMutexEnter(sqlite3_mutex *pX){
16075  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16076  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16077  p->cnt++;
16078}
16079static int debugMutexTry(sqlite3_mutex *pX){
16080  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16081  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16082  p->cnt++;
16083  return SQLITE_OK;
16084}
16085
16086/*
16087** The sqlite3_mutex_leave() routine exits a mutex that was
16088** previously entered by the same thread.  The behavior
16089** is undefined if the mutex is not currently entered or
16090** is not currently allocated.  SQLite will never do either.
16091*/
16092static void debugMutexLeave(sqlite3_mutex *pX){
16093  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16094  assert( debugMutexHeld(pX) );
16095  p->cnt--;
16096  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16097}
16098
16099SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16100  static const sqlite3_mutex_methods sMutex = {
16101    debugMutexInit,
16102    debugMutexEnd,
16103    debugMutexAlloc,
16104    debugMutexFree,
16105    debugMutexEnter,
16106    debugMutexTry,
16107    debugMutexLeave,
16108
16109    debugMutexHeld,
16110    debugMutexNotheld
16111  };
16112
16113  return &sMutex;
16114}
16115#endif /* SQLITE_DEBUG */
16116
16117/*
16118** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16119** is used regardless of the run-time threadsafety setting.
16120*/
16121#ifdef SQLITE_MUTEX_NOOP
16122SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16123  return sqlite3NoopMutex();
16124}
16125#endif /* SQLITE_MUTEX_NOOP */
16126#endif /* SQLITE_MUTEX_OMIT */
16127
16128/************** End of mutex_noop.c ******************************************/
16129/************** Begin file mutex_os2.c ***************************************/
16130/*
16131** 2007 August 28
16132**
16133** The author disclaims copyright to this source code.  In place of
16134** a legal notice, here is a blessing:
16135**
16136**    May you do good and not evil.
16137**    May you find forgiveness for yourself and forgive others.
16138**    May you share freely, never taking more than you give.
16139**
16140*************************************************************************
16141** This file contains the C functions that implement mutexes for OS/2
16142*/
16143
16144/*
16145** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16146** See the mutex.h file for details.
16147*/
16148#ifdef SQLITE_MUTEX_OS2
16149
16150/********************** OS/2 Mutex Implementation **********************
16151**
16152** This implementation of mutexes is built using the OS/2 API.
16153*/
16154
16155/*
16156** The mutex object
16157** Each recursive mutex is an instance of the following structure.
16158*/
16159struct sqlite3_mutex {
16160  HMTX mutex;       /* Mutex controlling the lock */
16161  int  id;          /* Mutex type */
16162  int  nRef;        /* Number of references */
16163  TID  owner;       /* Thread holding this mutex */
16164};
16165
16166#define OS2_MUTEX_INITIALIZER   0,0,0,0
16167
16168/*
16169** Initialize and deinitialize the mutex subsystem.
16170*/
16171static int os2MutexInit(void){ return SQLITE_OK; }
16172static int os2MutexEnd(void){ return SQLITE_OK; }
16173
16174/*
16175** The sqlite3_mutex_alloc() routine allocates a new
16176** mutex and returns a pointer to it.  If it returns NULL
16177** that means that a mutex could not be allocated.
16178** SQLite will unwind its stack and return an error.  The argument
16179** to sqlite3_mutex_alloc() is one of these integer constants:
16180**
16181** <ul>
16182** <li>  SQLITE_MUTEX_FAST               0
16183** <li>  SQLITE_MUTEX_RECURSIVE          1
16184** <li>  SQLITE_MUTEX_STATIC_MASTER      2
16185** <li>  SQLITE_MUTEX_STATIC_MEM         3
16186** <li>  SQLITE_MUTEX_STATIC_PRNG        4
16187** </ul>
16188**
16189** The first two constants cause sqlite3_mutex_alloc() to create
16190** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16191** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16192** The mutex implementation does not need to make a distinction
16193** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16194** not want to.  But SQLite will only request a recursive mutex in
16195** cases where it really needs one.  If a faster non-recursive mutex
16196** implementation is available on the host platform, the mutex subsystem
16197** might return such a mutex in response to SQLITE_MUTEX_FAST.
16198**
16199** The other allowed parameters to sqlite3_mutex_alloc() each return
16200** a pointer to a static preexisting mutex.  Three static mutexes are
16201** used by the current version of SQLite.  Future versions of SQLite
16202** may add additional static mutexes.  Static mutexes are for internal
16203** use by SQLite only.  Applications that use SQLite mutexes should
16204** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16205** SQLITE_MUTEX_RECURSIVE.
16206**
16207** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16208** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16209** returns a different mutex on every call.  But for the static
16210** mutex types, the same mutex is returned on every call that has
16211** the same type number.
16212*/
16213static sqlite3_mutex *os2MutexAlloc(int iType){
16214  sqlite3_mutex *p = NULL;
16215  switch( iType ){
16216    case SQLITE_MUTEX_FAST:
16217    case SQLITE_MUTEX_RECURSIVE: {
16218      p = sqlite3MallocZero( sizeof(*p) );
16219      if( p ){
16220        p->id = iType;
16221        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16222          sqlite3_free( p );
16223          p = NULL;
16224        }
16225      }
16226      break;
16227    }
16228    default: {
16229      static volatile int isInit = 0;
16230      static sqlite3_mutex staticMutexes[] = {
16231        { OS2_MUTEX_INITIALIZER, },
16232        { OS2_MUTEX_INITIALIZER, },
16233        { OS2_MUTEX_INITIALIZER, },
16234        { OS2_MUTEX_INITIALIZER, },
16235        { OS2_MUTEX_INITIALIZER, },
16236        { OS2_MUTEX_INITIALIZER, },
16237      };
16238      if ( !isInit ){
16239        APIRET rc;
16240        PTIB ptib;
16241        PPIB ppib;
16242        HMTX mutex;
16243        char name[32];
16244        DosGetInfoBlocks( &ptib, &ppib );
16245        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16246                          ppib->pib_ulpid );
16247        while( !isInit ){
16248          mutex = 0;
16249          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16250          if( rc == NO_ERROR ){
16251            unsigned int i;
16252            if( !isInit ){
16253              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16254                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16255              }
16256              isInit = 1;
16257            }
16258            DosCloseMutexSem( mutex );
16259          }else if( rc == ERROR_DUPLICATE_NAME ){
16260            DosSleep( 1 );
16261          }else{
16262            return p;
16263          }
16264        }
16265      }
16266      assert( iType-2 >= 0 );
16267      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16268      p = &staticMutexes[iType-2];
16269      p->id = iType;
16270      break;
16271    }
16272  }
16273  return p;
16274}
16275
16276
16277/*
16278** This routine deallocates a previously allocated mutex.
16279** SQLite is careful to deallocate every mutex that it allocates.
16280*/
16281static void os2MutexFree(sqlite3_mutex *p){
16282  if( p==0 ) return;
16283  assert( p->nRef==0 );
16284  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16285  DosCloseMutexSem( p->mutex );
16286  sqlite3_free( p );
16287}
16288
16289#ifdef SQLITE_DEBUG
16290/*
16291** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16292** intended for use inside assert() statements.
16293*/
16294static int os2MutexHeld(sqlite3_mutex *p){
16295  TID tid;
16296  PID pid;
16297  ULONG ulCount;
16298  PTIB ptib;
16299  if( p!=0 ) {
16300    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16301  } else {
16302    DosGetInfoBlocks(&ptib, NULL);
16303    tid = ptib->tib_ptib2->tib2_ultid;
16304  }
16305  return p==0 || (p->nRef!=0 && p->owner==tid);
16306}
16307static int os2MutexNotheld(sqlite3_mutex *p){
16308  TID tid;
16309  PID pid;
16310  ULONG ulCount;
16311  PTIB ptib;
16312  if( p!= 0 ) {
16313    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16314  } else {
16315    DosGetInfoBlocks(&ptib, NULL);
16316    tid = ptib->tib_ptib2->tib2_ultid;
16317  }
16318  return p==0 || p->nRef==0 || p->owner!=tid;
16319}
16320#endif
16321
16322/*
16323** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16324** to enter a mutex.  If another thread is already within the mutex,
16325** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16326** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16327** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16328** be entered multiple times by the same thread.  In such cases the,
16329** mutex must be exited an equal number of times before another thread
16330** can enter.  If the same thread tries to enter any other kind of mutex
16331** more than once, the behavior is undefined.
16332*/
16333static void os2MutexEnter(sqlite3_mutex *p){
16334  TID tid;
16335  PID holder1;
16336  ULONG holder2;
16337  if( p==0 ) return;
16338  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16339  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16340  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16341  p->owner = tid;
16342  p->nRef++;
16343}
16344static int os2MutexTry(sqlite3_mutex *p){
16345  int rc;
16346  TID tid;
16347  PID holder1;
16348  ULONG holder2;
16349  if( p==0 ) return SQLITE_OK;
16350  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16351  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
16352    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16353    p->owner = tid;
16354    p->nRef++;
16355    rc = SQLITE_OK;
16356  } else {
16357    rc = SQLITE_BUSY;
16358  }
16359
16360  return rc;
16361}
16362
16363/*
16364** The sqlite3_mutex_leave() routine exits a mutex that was
16365** previously entered by the same thread.  The behavior
16366** is undefined if the mutex is not currently entered or
16367** is not currently allocated.  SQLite will never do either.
16368*/
16369static void os2MutexLeave(sqlite3_mutex *p){
16370  TID tid;
16371  PID holder1;
16372  ULONG holder2;
16373  if( p==0 ) return;
16374  assert( p->nRef>0 );
16375  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16376  assert( p->owner==tid );
16377  p->nRef--;
16378  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16379  DosReleaseMutexSem(p->mutex);
16380}
16381
16382SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16383  static const sqlite3_mutex_methods sMutex = {
16384    os2MutexInit,
16385    os2MutexEnd,
16386    os2MutexAlloc,
16387    os2MutexFree,
16388    os2MutexEnter,
16389    os2MutexTry,
16390    os2MutexLeave,
16391#ifdef SQLITE_DEBUG
16392    os2MutexHeld,
16393    os2MutexNotheld
16394#endif
16395  };
16396
16397  return &sMutex;
16398}
16399#endif /* SQLITE_MUTEX_OS2 */
16400
16401/************** End of mutex_os2.c *******************************************/
16402/************** Begin file mutex_unix.c **************************************/
16403/*
16404** 2007 August 28
16405**
16406** The author disclaims copyright to this source code.  In place of
16407** a legal notice, here is a blessing:
16408**
16409**    May you do good and not evil.
16410**    May you find forgiveness for yourself and forgive others.
16411**    May you share freely, never taking more than you give.
16412**
16413*************************************************************************
16414** This file contains the C functions that implement mutexes for pthreads
16415*/
16416
16417/*
16418** The code in this file is only used if we are compiling threadsafe
16419** under unix with pthreads.
16420**
16421** Note that this implementation requires a version of pthreads that
16422** supports recursive mutexes.
16423*/
16424#ifdef SQLITE_MUTEX_PTHREADS
16425
16426#include <pthread.h>
16427
16428/*
16429** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
16430** are necessary under two condidtions:  (1) Debug builds and (2) using
16431** home-grown mutexes.  Encapsulate these conditions into a single #define.
16432*/
16433#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
16434# define SQLITE_MUTEX_NREF 1
16435#else
16436# define SQLITE_MUTEX_NREF 0
16437#endif
16438
16439/*
16440** Each recursive mutex is an instance of the following structure.
16441*/
16442struct sqlite3_mutex {
16443  pthread_mutex_t mutex;     /* Mutex controlling the lock */
16444#if SQLITE_MUTEX_NREF
16445  int id;                    /* Mutex type */
16446  volatile int nRef;         /* Number of entrances */
16447  volatile pthread_t owner;  /* Thread that is within this mutex */
16448  int trace;                 /* True to trace changes */
16449#endif
16450};
16451#if SQLITE_MUTEX_NREF
16452#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
16453#else
16454#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
16455#endif
16456
16457/*
16458** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16459** intended for use only inside assert() statements.  On some platforms,
16460** there might be race conditions that can cause these routines to
16461** deliver incorrect results.  In particular, if pthread_equal() is
16462** not an atomic operation, then these routines might delivery
16463** incorrect results.  On most platforms, pthread_equal() is a
16464** comparison of two integers and is therefore atomic.  But we are
16465** told that HPUX is not such a platform.  If so, then these routines
16466** will not always work correctly on HPUX.
16467**
16468** On those platforms where pthread_equal() is not atomic, SQLite
16469** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
16470** make sure no assert() statements are evaluated and hence these
16471** routines are never called.
16472*/
16473#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
16474static int pthreadMutexHeld(sqlite3_mutex *p){
16475  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
16476}
16477static int pthreadMutexNotheld(sqlite3_mutex *p){
16478  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
16479}
16480#endif
16481
16482/*
16483** Initialize and deinitialize the mutex subsystem.
16484*/
16485static int pthreadMutexInit(void){ return SQLITE_OK; }
16486static int pthreadMutexEnd(void){ return SQLITE_OK; }
16487
16488/*
16489** The sqlite3_mutex_alloc() routine allocates a new
16490** mutex and returns a pointer to it.  If it returns NULL
16491** that means that a mutex could not be allocated.  SQLite
16492** will unwind its stack and return an error.  The argument
16493** to sqlite3_mutex_alloc() is one of these integer constants:
16494**
16495** <ul>
16496** <li>  SQLITE_MUTEX_FAST
16497** <li>  SQLITE_MUTEX_RECURSIVE
16498** <li>  SQLITE_MUTEX_STATIC_MASTER
16499** <li>  SQLITE_MUTEX_STATIC_MEM
16500** <li>  SQLITE_MUTEX_STATIC_MEM2
16501** <li>  SQLITE_MUTEX_STATIC_PRNG
16502** <li>  SQLITE_MUTEX_STATIC_LRU
16503** <li>  SQLITE_MUTEX_STATIC_LRU2
16504** </ul>
16505**
16506** The first two constants cause sqlite3_mutex_alloc() to create
16507** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16508** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16509** The mutex implementation does not need to make a distinction
16510** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16511** not want to.  But SQLite will only request a recursive mutex in
16512** cases where it really needs one.  If a faster non-recursive mutex
16513** implementation is available on the host platform, the mutex subsystem
16514** might return such a mutex in response to SQLITE_MUTEX_FAST.
16515**
16516** The other allowed parameters to sqlite3_mutex_alloc() each return
16517** a pointer to a static preexisting mutex.  Six static mutexes are
16518** used by the current version of SQLite.  Future versions of SQLite
16519** may add additional static mutexes.  Static mutexes are for internal
16520** use by SQLite only.  Applications that use SQLite mutexes should
16521** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16522** SQLITE_MUTEX_RECURSIVE.
16523**
16524** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16525** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16526** returns a different mutex on every call.  But for the static
16527** mutex types, the same mutex is returned on every call that has
16528** the same type number.
16529*/
16530static sqlite3_mutex *pthreadMutexAlloc(int iType){
16531  static sqlite3_mutex staticMutexes[] = {
16532    SQLITE3_MUTEX_INITIALIZER,
16533    SQLITE3_MUTEX_INITIALIZER,
16534    SQLITE3_MUTEX_INITIALIZER,
16535    SQLITE3_MUTEX_INITIALIZER,
16536    SQLITE3_MUTEX_INITIALIZER,
16537    SQLITE3_MUTEX_INITIALIZER
16538  };
16539  sqlite3_mutex *p;
16540  switch( iType ){
16541    case SQLITE_MUTEX_RECURSIVE: {
16542      p = sqlite3MallocZero( sizeof(*p) );
16543      if( p ){
16544#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16545        /* If recursive mutexes are not available, we will have to
16546        ** build our own.  See below. */
16547        pthread_mutex_init(&p->mutex, 0);
16548#else
16549        /* Use a recursive mutex if it is available */
16550        pthread_mutexattr_t recursiveAttr;
16551        pthread_mutexattr_init(&recursiveAttr);
16552        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
16553        pthread_mutex_init(&p->mutex, &recursiveAttr);
16554        pthread_mutexattr_destroy(&recursiveAttr);
16555#endif
16556#if SQLITE_MUTEX_NREF
16557        p->id = iType;
16558#endif
16559      }
16560      break;
16561    }
16562    case SQLITE_MUTEX_FAST: {
16563      p = sqlite3MallocZero( sizeof(*p) );
16564      if( p ){
16565#if SQLITE_MUTEX_NREF
16566        p->id = iType;
16567#endif
16568        pthread_mutex_init(&p->mutex, 0);
16569      }
16570      break;
16571    }
16572    default: {
16573      assert( iType-2 >= 0 );
16574      assert( iType-2 < ArraySize(staticMutexes) );
16575      p = &staticMutexes[iType-2];
16576#if SQLITE_MUTEX_NREF
16577      p->id = iType;
16578#endif
16579      break;
16580    }
16581  }
16582  return p;
16583}
16584
16585
16586/*
16587** This routine deallocates a previously
16588** allocated mutex.  SQLite is careful to deallocate every
16589** mutex that it allocates.
16590*/
16591static void pthreadMutexFree(sqlite3_mutex *p){
16592  assert( p->nRef==0 );
16593  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16594  pthread_mutex_destroy(&p->mutex);
16595  sqlite3_free(p);
16596}
16597
16598/*
16599** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16600** to enter a mutex.  If another thread is already within the mutex,
16601** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16602** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16603** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16604** be entered multiple times by the same thread.  In such cases the,
16605** mutex must be exited an equal number of times before another thread
16606** can enter.  If the same thread tries to enter any other kind of mutex
16607** more than once, the behavior is undefined.
16608*/
16609static void pthreadMutexEnter(sqlite3_mutex *p){
16610  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16611
16612#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16613  /* If recursive mutexes are not available, then we have to grow
16614  ** our own.  This implementation assumes that pthread_equal()
16615  ** is atomic - that it cannot be deceived into thinking self
16616  ** and p->owner are equal if p->owner changes between two values
16617  ** that are not equal to self while the comparison is taking place.
16618  ** This implementation also assumes a coherent cache - that
16619  ** separate processes cannot read different values from the same
16620  ** address at the same time.  If either of these two conditions
16621  ** are not met, then the mutexes will fail and problems will result.
16622  */
16623  {
16624    pthread_t self = pthread_self();
16625    if( p->nRef>0 && pthread_equal(p->owner, self) ){
16626      p->nRef++;
16627    }else{
16628      pthread_mutex_lock(&p->mutex);
16629      assert( p->nRef==0 );
16630      p->owner = self;
16631      p->nRef = 1;
16632    }
16633  }
16634#else
16635  /* Use the built-in recursive mutexes if they are available.
16636  */
16637  pthread_mutex_lock(&p->mutex);
16638#if SQLITE_MUTEX_NREF
16639  assert( p->nRef>0 || p->owner==0 );
16640  p->owner = pthread_self();
16641  p->nRef++;
16642#endif
16643#endif
16644
16645#ifdef SQLITE_DEBUG
16646  if( p->trace ){
16647    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16648  }
16649#endif
16650}
16651static int pthreadMutexTry(sqlite3_mutex *p){
16652  int rc;
16653  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16654
16655#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16656  /* If recursive mutexes are not available, then we have to grow
16657  ** our own.  This implementation assumes that pthread_equal()
16658  ** is atomic - that it cannot be deceived into thinking self
16659  ** and p->owner are equal if p->owner changes between two values
16660  ** that are not equal to self while the comparison is taking place.
16661  ** This implementation also assumes a coherent cache - that
16662  ** separate processes cannot read different values from the same
16663  ** address at the same time.  If either of these two conditions
16664  ** are not met, then the mutexes will fail and problems will result.
16665  */
16666  {
16667    pthread_t self = pthread_self();
16668    if( p->nRef>0 && pthread_equal(p->owner, self) ){
16669      p->nRef++;
16670      rc = SQLITE_OK;
16671    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
16672      assert( p->nRef==0 );
16673      p->owner = self;
16674      p->nRef = 1;
16675      rc = SQLITE_OK;
16676    }else{
16677      rc = SQLITE_BUSY;
16678    }
16679  }
16680#else
16681  /* Use the built-in recursive mutexes if they are available.
16682  */
16683  if( pthread_mutex_trylock(&p->mutex)==0 ){
16684#if SQLITE_MUTEX_NREF
16685    p->owner = pthread_self();
16686    p->nRef++;
16687#endif
16688    rc = SQLITE_OK;
16689  }else{
16690    rc = SQLITE_BUSY;
16691  }
16692#endif
16693
16694#ifdef SQLITE_DEBUG
16695  if( rc==SQLITE_OK && p->trace ){
16696    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16697  }
16698#endif
16699  return rc;
16700}
16701
16702/*
16703** The sqlite3_mutex_leave() routine exits a mutex that was
16704** previously entered by the same thread.  The behavior
16705** is undefined if the mutex is not currently entered or
16706** is not currently allocated.  SQLite will never do either.
16707*/
16708static void pthreadMutexLeave(sqlite3_mutex *p){
16709  assert( pthreadMutexHeld(p) );
16710#if SQLITE_MUTEX_NREF
16711  p->nRef--;
16712  if( p->nRef==0 ) p->owner = 0;
16713#endif
16714  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16715
16716#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16717  if( p->nRef==0 ){
16718    pthread_mutex_unlock(&p->mutex);
16719  }
16720#else
16721  pthread_mutex_unlock(&p->mutex);
16722#endif
16723
16724#ifdef SQLITE_DEBUG
16725  if( p->trace ){
16726    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16727  }
16728#endif
16729}
16730
16731SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16732  static const sqlite3_mutex_methods sMutex = {
16733    pthreadMutexInit,
16734    pthreadMutexEnd,
16735    pthreadMutexAlloc,
16736    pthreadMutexFree,
16737    pthreadMutexEnter,
16738    pthreadMutexTry,
16739    pthreadMutexLeave,
16740#ifdef SQLITE_DEBUG
16741    pthreadMutexHeld,
16742    pthreadMutexNotheld
16743#else
16744    0,
16745    0
16746#endif
16747  };
16748
16749  return &sMutex;
16750}
16751
16752#endif /* SQLITE_MUTEX_PTHREAD */
16753
16754/************** End of mutex_unix.c ******************************************/
16755/************** Begin file mutex_w32.c ***************************************/
16756/*
16757** 2007 August 14
16758**
16759** The author disclaims copyright to this source code.  In place of
16760** a legal notice, here is a blessing:
16761**
16762**    May you do good and not evil.
16763**    May you find forgiveness for yourself and forgive others.
16764**    May you share freely, never taking more than you give.
16765**
16766*************************************************************************
16767** This file contains the C functions that implement mutexes for win32
16768*/
16769
16770/*
16771** The code in this file is only used if we are compiling multithreaded
16772** on a win32 system.
16773*/
16774#ifdef SQLITE_MUTEX_W32
16775
16776/*
16777** Each recursive mutex is an instance of the following structure.
16778*/
16779struct sqlite3_mutex {
16780  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
16781  int id;                    /* Mutex type */
16782#ifdef SQLITE_DEBUG
16783  volatile int nRef;         /* Number of enterances */
16784  volatile DWORD owner;      /* Thread holding this mutex */
16785  int trace;                 /* True to trace changes */
16786#endif
16787};
16788#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
16789#ifdef SQLITE_DEBUG
16790#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
16791#else
16792#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
16793#endif
16794
16795/*
16796** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
16797** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
16798**
16799** Here is an interesting observation:  Win95, Win98, and WinME lack
16800** the LockFileEx() API.  But we can still statically link against that
16801** API as long as we don't call it win running Win95/98/ME.  A call to
16802** this routine is used to determine if the host is Win95/98/ME or
16803** WinNT/2K/XP so that we will know whether or not we can safely call
16804** the LockFileEx() API.
16805**
16806** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
16807** which is only available if your application was compiled with
16808** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
16809** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
16810** this out as well.
16811*/
16812#if 0
16813#if SQLITE_OS_WINCE
16814# define mutexIsNT()  (1)
16815#else
16816  static int mutexIsNT(void){
16817    static int osType = 0;
16818    if( osType==0 ){
16819      OSVERSIONINFO sInfo;
16820      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
16821      GetVersionEx(&sInfo);
16822      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
16823    }
16824    return osType==2;
16825  }
16826#endif /* SQLITE_OS_WINCE */
16827#endif
16828
16829#ifdef SQLITE_DEBUG
16830/*
16831** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16832** intended for use only inside assert() statements.
16833*/
16834static int winMutexHeld(sqlite3_mutex *p){
16835  return p->nRef!=0 && p->owner==GetCurrentThreadId();
16836}
16837static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
16838  return p->nRef==0 || p->owner!=tid;
16839}
16840static int winMutexNotheld(sqlite3_mutex *p){
16841  DWORD tid = GetCurrentThreadId();
16842  return winMutexNotheld2(p, tid);
16843}
16844#endif
16845
16846
16847/*
16848** Initialize and deinitialize the mutex subsystem.
16849*/
16850static sqlite3_mutex winMutex_staticMutexes[6] = {
16851  SQLITE3_MUTEX_INITIALIZER,
16852  SQLITE3_MUTEX_INITIALIZER,
16853  SQLITE3_MUTEX_INITIALIZER,
16854  SQLITE3_MUTEX_INITIALIZER,
16855  SQLITE3_MUTEX_INITIALIZER,
16856  SQLITE3_MUTEX_INITIALIZER
16857};
16858static int winMutex_isInit = 0;
16859/* As winMutexInit() and winMutexEnd() are called as part
16860** of the sqlite3_initialize and sqlite3_shutdown()
16861** processing, the "interlocked" magic is probably not
16862** strictly necessary.
16863*/
16864static long winMutex_lock = 0;
16865
16866static int winMutexInit(void){
16867  /* The first to increment to 1 does actual initialization */
16868  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
16869    int i;
16870    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16871      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
16872    }
16873    winMutex_isInit = 1;
16874  }else{
16875    /* Someone else is in the process of initing the static mutexes */
16876    while( !winMutex_isInit ){
16877      Sleep(1);
16878    }
16879  }
16880  return SQLITE_OK;
16881}
16882
16883static int winMutexEnd(void){
16884  /* The first to decrement to 0 does actual shutdown
16885  ** (which should be the last to shutdown.) */
16886  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
16887    if( winMutex_isInit==1 ){
16888      int i;
16889      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
16890        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
16891      }
16892      winMutex_isInit = 0;
16893    }
16894  }
16895  return SQLITE_OK;
16896}
16897
16898/*
16899** The sqlite3_mutex_alloc() routine allocates a new
16900** mutex and returns a pointer to it.  If it returns NULL
16901** that means that a mutex could not be allocated.  SQLite
16902** will unwind its stack and return an error.  The argument
16903** to sqlite3_mutex_alloc() is one of these integer constants:
16904**
16905** <ul>
16906** <li>  SQLITE_MUTEX_FAST
16907** <li>  SQLITE_MUTEX_RECURSIVE
16908** <li>  SQLITE_MUTEX_STATIC_MASTER
16909** <li>  SQLITE_MUTEX_STATIC_MEM
16910** <li>  SQLITE_MUTEX_STATIC_MEM2
16911** <li>  SQLITE_MUTEX_STATIC_PRNG
16912** <li>  SQLITE_MUTEX_STATIC_LRU
16913** <li>  SQLITE_MUTEX_STATIC_LRU2
16914** </ul>
16915**
16916** The first two constants cause sqlite3_mutex_alloc() to create
16917** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16918** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16919** The mutex implementation does not need to make a distinction
16920** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16921** not want to.  But SQLite will only request a recursive mutex in
16922** cases where it really needs one.  If a faster non-recursive mutex
16923** implementation is available on the host platform, the mutex subsystem
16924** might return such a mutex in response to SQLITE_MUTEX_FAST.
16925**
16926** The other allowed parameters to sqlite3_mutex_alloc() each return
16927** a pointer to a static preexisting mutex.  Six static mutexes are
16928** used by the current version of SQLite.  Future versions of SQLite
16929** may add additional static mutexes.  Static mutexes are for internal
16930** use by SQLite only.  Applications that use SQLite mutexes should
16931** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16932** SQLITE_MUTEX_RECURSIVE.
16933**
16934** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16935** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16936** returns a different mutex on every call.  But for the static
16937** mutex types, the same mutex is returned on every call that has
16938** the same type number.
16939*/
16940static sqlite3_mutex *winMutexAlloc(int iType){
16941  sqlite3_mutex *p;
16942
16943  switch( iType ){
16944    case SQLITE_MUTEX_FAST:
16945    case SQLITE_MUTEX_RECURSIVE: {
16946      p = sqlite3MallocZero( sizeof(*p) );
16947      if( p ){
16948#ifdef SQLITE_DEBUG
16949        p->id = iType;
16950#endif
16951        InitializeCriticalSection(&p->mutex);
16952      }
16953      break;
16954    }
16955    default: {
16956      assert( winMutex_isInit==1 );
16957      assert( iType-2 >= 0 );
16958      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
16959      p = &winMutex_staticMutexes[iType-2];
16960#ifdef SQLITE_DEBUG
16961      p->id = iType;
16962#endif
16963      break;
16964    }
16965  }
16966  return p;
16967}
16968
16969
16970/*
16971** This routine deallocates a previously
16972** allocated mutex.  SQLite is careful to deallocate every
16973** mutex that it allocates.
16974*/
16975static void winMutexFree(sqlite3_mutex *p){
16976  assert( p );
16977  assert( p->nRef==0 && p->owner==0 );
16978  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16979  DeleteCriticalSection(&p->mutex);
16980  sqlite3_free(p);
16981}
16982
16983/*
16984** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16985** to enter a mutex.  If another thread is already within the mutex,
16986** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16987** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16988** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16989** be entered multiple times by the same thread.  In such cases the,
16990** mutex must be exited an equal number of times before another thread
16991** can enter.  If the same thread tries to enter any other kind of mutex
16992** more than once, the behavior is undefined.
16993*/
16994static void winMutexEnter(sqlite3_mutex *p){
16995#ifdef SQLITE_DEBUG
16996  DWORD tid = GetCurrentThreadId();
16997  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16998#endif
16999  EnterCriticalSection(&p->mutex);
17000#ifdef SQLITE_DEBUG
17001  assert( p->nRef>0 || p->owner==0 );
17002  p->owner = tid;
17003  p->nRef++;
17004  if( p->trace ){
17005    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17006  }
17007#endif
17008}
17009static int winMutexTry(sqlite3_mutex *p){
17010#ifndef NDEBUG
17011  DWORD tid = GetCurrentThreadId();
17012#endif
17013  int rc = SQLITE_BUSY;
17014  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17015  /*
17016  ** The sqlite3_mutex_try() routine is very rarely used, and when it
17017  ** is used it is merely an optimization.  So it is OK for it to always
17018  ** fail.
17019  **
17020  ** The TryEnterCriticalSection() interface is only available on WinNT.
17021  ** And some windows compilers complain if you try to use it without
17022  ** first doing some #defines that prevent SQLite from building on Win98.
17023  ** For that reason, we will omit this optimization for now.  See
17024  ** ticket #2685.
17025  */
17026#if 0
17027  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17028    p->owner = tid;
17029    p->nRef++;
17030    rc = SQLITE_OK;
17031  }
17032#else
17033  UNUSED_PARAMETER(p);
17034#endif
17035#ifdef SQLITE_DEBUG
17036  if( rc==SQLITE_OK && p->trace ){
17037    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17038  }
17039#endif
17040  return rc;
17041}
17042
17043/*
17044** The sqlite3_mutex_leave() routine exits a mutex that was
17045** previously entered by the same thread.  The behavior
17046** is undefined if the mutex is not currently entered or
17047** is not currently allocated.  SQLite will never do either.
17048*/
17049static void winMutexLeave(sqlite3_mutex *p){
17050#ifndef NDEBUG
17051  DWORD tid = GetCurrentThreadId();
17052  assert( p->nRef>0 );
17053  assert( p->owner==tid );
17054  p->nRef--;
17055  if( p->nRef==0 ) p->owner = 0;
17056  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17057#endif
17058  LeaveCriticalSection(&p->mutex);
17059#ifdef SQLITE_DEBUG
17060  if( p->trace ){
17061    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17062  }
17063#endif
17064}
17065
17066SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17067  static const sqlite3_mutex_methods sMutex = {
17068    winMutexInit,
17069    winMutexEnd,
17070    winMutexAlloc,
17071    winMutexFree,
17072    winMutexEnter,
17073    winMutexTry,
17074    winMutexLeave,
17075#ifdef SQLITE_DEBUG
17076    winMutexHeld,
17077    winMutexNotheld
17078#else
17079    0,
17080    0
17081#endif
17082  };
17083
17084  return &sMutex;
17085}
17086#endif /* SQLITE_MUTEX_W32 */
17087
17088/************** End of mutex_w32.c *******************************************/
17089/************** Begin file malloc.c ******************************************/
17090/*
17091** 2001 September 15
17092**
17093** The author disclaims copyright to this source code.  In place of
17094** a legal notice, here is a blessing:
17095**
17096**    May you do good and not evil.
17097**    May you find forgiveness for yourself and forgive others.
17098**    May you share freely, never taking more than you give.
17099**
17100*************************************************************************
17101**
17102** Memory allocation functions used throughout sqlite.
17103*/
17104
17105/*
17106** This routine runs when the memory allocator sees that the
17107** total memory allocation is about to exceed the soft heap
17108** limit.
17109*/
17110static void softHeapLimitEnforcer(
17111  void *NotUsed,
17112  sqlite3_int64 NotUsed2,
17113  int allocSize
17114){
17115  UNUSED_PARAMETER2(NotUsed, NotUsed2);
17116  sqlite3_release_memory(allocSize);
17117}
17118
17119/*
17120** Set the soft heap-size limit for the library. Passing a zero or
17121** negative value indicates no limit.
17122*/
17123SQLITE_API void sqlite3_soft_heap_limit(int n){
17124  sqlite3_uint64 iLimit;
17125  int overage;
17126  if( n<0 ){
17127    iLimit = 0;
17128  }else{
17129    iLimit = n;
17130  }
17131#ifndef SQLITE_OMIT_AUTOINIT
17132  sqlite3_initialize();
17133#endif
17134  if( iLimit>0 ){
17135    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
17136  }else{
17137    sqlite3MemoryAlarm(0, 0, 0);
17138  }
17139  overage = (int)(sqlite3_memory_used() - (i64)n);
17140  if( overage>0 ){
17141    sqlite3_release_memory(overage);
17142  }
17143}
17144
17145/*
17146** Attempt to release up to n bytes of non-essential memory currently
17147** held by SQLite. An example of non-essential memory is memory used to
17148** cache database pages that are not currently in use.
17149*/
17150SQLITE_API int sqlite3_release_memory(int n){
17151#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17152  int nRet = 0;
17153  nRet += sqlite3PcacheReleaseMemory(n-nRet);
17154  return nRet;
17155#else
17156  UNUSED_PARAMETER(n);
17157  return SQLITE_OK;
17158#endif
17159}
17160
17161/*
17162** State information local to the memory allocation subsystem.
17163*/
17164static SQLITE_WSD struct Mem0Global {
17165  /* Number of free pages for scratch and page-cache memory */
17166  u32 nScratchFree;
17167  u32 nPageFree;
17168
17169  sqlite3_mutex *mutex;         /* Mutex to serialize access */
17170
17171  /*
17172  ** The alarm callback and its arguments.  The mem0.mutex lock will
17173  ** be held while the callback is running.  Recursive calls into
17174  ** the memory subsystem are allowed, but no new callbacks will be
17175  ** issued.
17176  */
17177  sqlite3_int64 alarmThreshold;
17178  void (*alarmCallback)(void*, sqlite3_int64,int);
17179  void *alarmArg;
17180
17181  /*
17182  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
17183  ** sqlite3GlobalConfig.pPage to a block of memory that records
17184  ** which pages are available.
17185  */
17186  u32 *aScratchFree;
17187  u32 *aPageFree;
17188} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17189
17190#define mem0 GLOBAL(struct Mem0Global, mem0)
17191
17192/*
17193** Initialize the memory allocation subsystem.
17194*/
17195SQLITE_PRIVATE int sqlite3MallocInit(void){
17196  if( sqlite3GlobalConfig.m.xMalloc==0 ){
17197    sqlite3MemSetDefault();
17198  }
17199  memset(&mem0, 0, sizeof(mem0));
17200  if( sqlite3GlobalConfig.bCoreMutex ){
17201    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17202  }
17203  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17204      && sqlite3GlobalConfig.nScratch>=0 ){
17205    int i;
17206    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
17207    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
17208                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
17209    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
17210    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
17211  }else{
17212    sqlite3GlobalConfig.pScratch = 0;
17213    sqlite3GlobalConfig.szScratch = 0;
17214  }
17215  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
17216      && sqlite3GlobalConfig.nPage>=1 ){
17217    int i;
17218    int overhead;
17219    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
17220    int n = sqlite3GlobalConfig.nPage;
17221    overhead = (4*n + sz - 1)/sz;
17222    sqlite3GlobalConfig.nPage -= overhead;
17223    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
17224                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
17225    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
17226    mem0.nPageFree = sqlite3GlobalConfig.nPage;
17227  }else{
17228    sqlite3GlobalConfig.pPage = 0;
17229    sqlite3GlobalConfig.szPage = 0;
17230  }
17231  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17232}
17233
17234/*
17235** Deinitialize the memory allocation subsystem.
17236*/
17237SQLITE_PRIVATE void sqlite3MallocEnd(void){
17238  if( sqlite3GlobalConfig.m.xShutdown ){
17239    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17240  }
17241  memset(&mem0, 0, sizeof(mem0));
17242}
17243
17244/*
17245** Return the amount of memory currently checked out.
17246*/
17247SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17248  int n, mx;
17249  sqlite3_int64 res;
17250  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17251  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17252  return res;
17253}
17254
17255/*
17256** Return the maximum amount of memory that has ever been
17257** checked out since either the beginning of this process
17258** or since the most recent reset.
17259*/
17260SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17261  int n, mx;
17262  sqlite3_int64 res;
17263  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17264  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17265  return res;
17266}
17267
17268/*
17269** Change the alarm callback
17270*/
17271SQLITE_PRIVATE int sqlite3MemoryAlarm(
17272  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17273  void *pArg,
17274  sqlite3_int64 iThreshold
17275){
17276  sqlite3_mutex_enter(mem0.mutex);
17277  mem0.alarmCallback = xCallback;
17278  mem0.alarmArg = pArg;
17279  mem0.alarmThreshold = iThreshold;
17280  sqlite3_mutex_leave(mem0.mutex);
17281  return SQLITE_OK;
17282}
17283
17284#ifndef SQLITE_OMIT_DEPRECATED
17285/*
17286** Deprecated external interface.  Internal/core SQLite code
17287** should call sqlite3MemoryAlarm.
17288*/
17289SQLITE_API int sqlite3_memory_alarm(
17290  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17291  void *pArg,
17292  sqlite3_int64 iThreshold
17293){
17294  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17295}
17296#endif
17297
17298/*
17299** Trigger the alarm
17300*/
17301static void sqlite3MallocAlarm(int nByte){
17302  void (*xCallback)(void*,sqlite3_int64,int);
17303  sqlite3_int64 nowUsed;
17304  void *pArg;
17305  if( mem0.alarmCallback==0 ) return;
17306  xCallback = mem0.alarmCallback;
17307  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17308  pArg = mem0.alarmArg;
17309  mem0.alarmCallback = 0;
17310  sqlite3_mutex_leave(mem0.mutex);
17311  xCallback(pArg, nowUsed, nByte);
17312  sqlite3_mutex_enter(mem0.mutex);
17313  mem0.alarmCallback = xCallback;
17314  mem0.alarmArg = pArg;
17315}
17316
17317/*
17318** Do a memory allocation with statistics and alarms.  Assume the
17319** lock is already held.
17320*/
17321static int mallocWithAlarm(int n, void **pp){
17322  int nFull;
17323  void *p;
17324  assert( sqlite3_mutex_held(mem0.mutex) );
17325  nFull = sqlite3GlobalConfig.m.xRoundup(n);
17326  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17327  if( mem0.alarmCallback!=0 ){
17328    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17329    if( nUsed+nFull >= mem0.alarmThreshold ){
17330      sqlite3MallocAlarm(nFull);
17331    }
17332  }
17333  p = sqlite3GlobalConfig.m.xMalloc(nFull);
17334  if( p==0 && mem0.alarmCallback ){
17335    sqlite3MallocAlarm(nFull);
17336    p = sqlite3GlobalConfig.m.xMalloc(nFull);
17337  }
17338  if( p ){
17339    nFull = sqlite3MallocSize(p);
17340    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17341    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17342  }
17343  *pp = p;
17344  return nFull;
17345}
17346
17347/*
17348** Allocate memory.  This routine is like sqlite3_malloc() except that it
17349** assumes the memory subsystem has already been initialized.
17350*/
17351SQLITE_PRIVATE void *sqlite3Malloc(int n){
17352  void *p;
17353  if( n<=0 || n>=0x7fffff00 ){
17354    /* A memory allocation of a number of bytes which is near the maximum
17355    ** signed integer value might cause an integer overflow inside of the
17356    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17357    ** 255 bytes of overhead.  SQLite itself will never use anything near
17358    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17359    p = 0;
17360  }else if( sqlite3GlobalConfig.bMemstat ){
17361    sqlite3_mutex_enter(mem0.mutex);
17362    mallocWithAlarm(n, &p);
17363    sqlite3_mutex_leave(mem0.mutex);
17364  }else{
17365    p = sqlite3GlobalConfig.m.xMalloc(n);
17366  }
17367  return p;
17368}
17369
17370/*
17371** This version of the memory allocation is for use by the application.
17372** First make sure the memory subsystem is initialized, then do the
17373** allocation.
17374*/
17375SQLITE_API void *sqlite3_malloc(int n){
17376#ifndef SQLITE_OMIT_AUTOINIT
17377  if( sqlite3_initialize() ) return 0;
17378#endif
17379  return sqlite3Malloc(n);
17380}
17381
17382/*
17383** Each thread may only have a single outstanding allocation from
17384** xScratchMalloc().  We verify this constraint in the single-threaded
17385** case by setting scratchAllocOut to 1 when an allocation
17386** is outstanding clearing it when the allocation is freed.
17387*/
17388#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17389static int scratchAllocOut = 0;
17390#endif
17391
17392
17393/*
17394** Allocate memory that is to be used and released right away.
17395** This routine is similar to alloca() in that it is not intended
17396** for situations where the memory might be held long-term.  This
17397** routine is intended to get memory to old large transient data
17398** structures that would not normally fit on the stack of an
17399** embedded processor.
17400*/
17401SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17402  void *p;
17403  assert( n>0 );
17404
17405#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17406  /* Verify that no more than two scratch allocation per thread
17407  ** is outstanding at one time.  (This is only checked in the
17408  ** single-threaded case since checking in the multi-threaded case
17409  ** would be much more complicated.) */
17410  assert( scratchAllocOut<=1 );
17411#endif
17412
17413  if( sqlite3GlobalConfig.szScratch<n ){
17414    goto scratch_overflow;
17415  }else{
17416    sqlite3_mutex_enter(mem0.mutex);
17417    if( mem0.nScratchFree==0 ){
17418      sqlite3_mutex_leave(mem0.mutex);
17419      goto scratch_overflow;
17420    }else{
17421      int i;
17422      i = mem0.aScratchFree[--mem0.nScratchFree];
17423      i *= sqlite3GlobalConfig.szScratch;
17424      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17425      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17426      sqlite3_mutex_leave(mem0.mutex);
17427      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
17428      assert(  (((u8*)p - (u8*)0) & 7)==0 );
17429    }
17430  }
17431#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17432  scratchAllocOut = p!=0;
17433#endif
17434
17435  return p;
17436
17437scratch_overflow:
17438  if( sqlite3GlobalConfig.bMemstat ){
17439    sqlite3_mutex_enter(mem0.mutex);
17440    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17441    n = mallocWithAlarm(n, &p);
17442    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17443    sqlite3_mutex_leave(mem0.mutex);
17444  }else{
17445    p = sqlite3GlobalConfig.m.xMalloc(n);
17446  }
17447  sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17448#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17449  scratchAllocOut = p!=0;
17450#endif
17451  return p;
17452}
17453SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17454  if( p ){
17455    if( sqlite3GlobalConfig.pScratch==0
17456           || p<sqlite3GlobalConfig.pScratch
17457           || p>=(void*)mem0.aScratchFree ){
17458      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17459      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17460      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17461      if( sqlite3GlobalConfig.bMemstat ){
17462        int iSize = sqlite3MallocSize(p);
17463        sqlite3_mutex_enter(mem0.mutex);
17464        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
17465        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
17466        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17467        sqlite3GlobalConfig.m.xFree(p);
17468        sqlite3_mutex_leave(mem0.mutex);
17469      }else{
17470        sqlite3GlobalConfig.m.xFree(p);
17471      }
17472    }else{
17473      int i;
17474      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
17475      i /= sqlite3GlobalConfig.szScratch;
17476      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
17477      sqlite3_mutex_enter(mem0.mutex);
17478      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
17479      mem0.aScratchFree[mem0.nScratchFree++] = i;
17480      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17481      sqlite3_mutex_leave(mem0.mutex);
17482
17483#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17484    /* Verify that no more than two scratch allocation per thread
17485    ** is outstanding at one time.  (This is only checked in the
17486    ** single-threaded case since checking in the multi-threaded case
17487    ** would be much more complicated.) */
17488    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17489    scratchAllocOut = 0;
17490#endif
17491
17492    }
17493  }
17494}
17495
17496/*
17497** TRUE if p is a lookaside memory allocation from db
17498*/
17499#ifndef SQLITE_OMIT_LOOKASIDE
17500static int isLookaside(sqlite3 *db, void *p){
17501  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
17502}
17503#else
17504#define isLookaside(A,B) 0
17505#endif
17506
17507/*
17508** Return the size of a memory allocation previously obtained from
17509** sqlite3Malloc() or sqlite3_malloc().
17510*/
17511SQLITE_PRIVATE int sqlite3MallocSize(void *p){
17512  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17513  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17514  return sqlite3GlobalConfig.m.xSize(p);
17515}
17516SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
17517  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17518  if( db && isLookaside(db, p) ){
17519    return db->lookaside.sz;
17520  }else{
17521    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17522    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17523    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17524    return sqlite3GlobalConfig.m.xSize(p);
17525  }
17526}
17527
17528/*
17529** Free memory previously obtained from sqlite3Malloc().
17530*/
17531SQLITE_API void sqlite3_free(void *p){
17532  if( p==0 ) return;
17533  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17534  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17535  if( sqlite3GlobalConfig.bMemstat ){
17536    sqlite3_mutex_enter(mem0.mutex);
17537    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
17538    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17539    sqlite3GlobalConfig.m.xFree(p);
17540    sqlite3_mutex_leave(mem0.mutex);
17541  }else{
17542    sqlite3GlobalConfig.m.xFree(p);
17543  }
17544}
17545
17546/*
17547** Free memory that might be associated with a particular database
17548** connection.
17549*/
17550SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
17551  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17552  if( db ){
17553    if( db->pnBytesFreed ){
17554      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
17555      return;
17556    }
17557    if( isLookaside(db, p) ){
17558      LookasideSlot *pBuf = (LookasideSlot*)p;
17559      pBuf->pNext = db->lookaside.pFree;
17560      db->lookaside.pFree = pBuf;
17561      db->lookaside.nOut--;
17562      return;
17563    }
17564  }
17565  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17566  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17567  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17568  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17569  sqlite3_free(p);
17570}
17571
17572/*
17573** Change the size of an existing memory allocation
17574*/
17575SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
17576  int nOld, nNew;
17577  void *pNew;
17578  if( pOld==0 ){
17579    return sqlite3Malloc(nBytes);
17580  }
17581  if( nBytes<=0 ){
17582    sqlite3_free(pOld);
17583    return 0;
17584  }
17585  if( nBytes>=0x7fffff00 ){
17586    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17587    return 0;
17588  }
17589  nOld = sqlite3MallocSize(pOld);
17590  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17591  if( nOld==nNew ){
17592    pNew = pOld;
17593  }else if( sqlite3GlobalConfig.bMemstat ){
17594    sqlite3_mutex_enter(mem0.mutex);
17595    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
17596    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
17597          mem0.alarmThreshold ){
17598      sqlite3MallocAlarm(nNew-nOld);
17599    }
17600    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
17601    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
17602    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17603    if( pNew==0 && mem0.alarmCallback ){
17604      sqlite3MallocAlarm(nBytes);
17605      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17606    }
17607    if( pNew ){
17608      nNew = sqlite3MallocSize(pNew);
17609      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
17610    }
17611    sqlite3_mutex_leave(mem0.mutex);
17612  }else{
17613    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17614  }
17615  return pNew;
17616}
17617
17618/*
17619** The public interface to sqlite3Realloc.  Make sure that the memory
17620** subsystem is initialized prior to invoking sqliteRealloc.
17621*/
17622SQLITE_API void *sqlite3_realloc(void *pOld, int n){
17623#ifndef SQLITE_OMIT_AUTOINIT
17624  if( sqlite3_initialize() ) return 0;
17625#endif
17626  return sqlite3Realloc(pOld, n);
17627}
17628
17629
17630/*
17631** Allocate and zero memory.
17632*/
17633SQLITE_PRIVATE void *sqlite3MallocZero(int n){
17634  void *p = sqlite3Malloc(n);
17635  if( p ){
17636    memset(p, 0, n);
17637  }
17638  return p;
17639}
17640
17641/*
17642** Allocate and zero memory.  If the allocation fails, make
17643** the mallocFailed flag in the connection pointer.
17644*/
17645SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
17646  void *p = sqlite3DbMallocRaw(db, n);
17647  if( p ){
17648    memset(p, 0, n);
17649  }
17650  return p;
17651}
17652
17653/*
17654** Allocate and zero memory.  If the allocation fails, make
17655** the mallocFailed flag in the connection pointer.
17656**
17657** If db!=0 and db->mallocFailed is true (indicating a prior malloc
17658** failure on the same database connection) then always return 0.
17659** Hence for a particular database connection, once malloc starts
17660** failing, it fails consistently until mallocFailed is reset.
17661** This is an important assumption.  There are many places in the
17662** code that do things like this:
17663**
17664**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
17665**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
17666**         if( b ) a[10] = 9;
17667**
17668** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
17669** that all prior mallocs (ex: "a") worked too.
17670*/
17671SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
17672  void *p;
17673  assert( db==0 || sqlite3_mutex_held(db->mutex) );
17674  assert( db==0 || db->pnBytesFreed==0 );
17675#ifndef SQLITE_OMIT_LOOKASIDE
17676  if( db ){
17677    LookasideSlot *pBuf;
17678    if( db->mallocFailed ){
17679      return 0;
17680    }
17681    if( db->lookaside.bEnabled && n<=db->lookaside.sz
17682         && (pBuf = db->lookaside.pFree)!=0 ){
17683      db->lookaside.pFree = pBuf->pNext;
17684      db->lookaside.nOut++;
17685      if( db->lookaside.nOut>db->lookaside.mxOut ){
17686        db->lookaside.mxOut = db->lookaside.nOut;
17687      }
17688      return (void*)pBuf;
17689    }
17690  }
17691#else
17692  if( db && db->mallocFailed ){
17693    return 0;
17694  }
17695#endif
17696  p = sqlite3Malloc(n);
17697  if( !p && db ){
17698    db->mallocFailed = 1;
17699  }
17700  sqlite3MemdebugSetType(p, MEMTYPE_DB |
17701         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
17702  return p;
17703}
17704
17705/*
17706** Resize the block of memory pointed to by p to n bytes. If the
17707** resize fails, set the mallocFailed flag in the connection object.
17708*/
17709SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
17710  void *pNew = 0;
17711  assert( db!=0 );
17712  assert( sqlite3_mutex_held(db->mutex) );
17713  if( db->mallocFailed==0 ){
17714    if( p==0 ){
17715      return sqlite3DbMallocRaw(db, n);
17716    }
17717    if( isLookaside(db, p) ){
17718      if( n<=db->lookaside.sz ){
17719        return p;
17720      }
17721      pNew = sqlite3DbMallocRaw(db, n);
17722      if( pNew ){
17723        memcpy(pNew, p, db->lookaside.sz);
17724        sqlite3DbFree(db, p);
17725      }
17726    }else{
17727      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17728      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17729      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17730      pNew = sqlite3_realloc(p, n);
17731      if( !pNew ){
17732        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
17733        db->mallocFailed = 1;
17734      }
17735      sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
17736            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
17737    }
17738  }
17739  return pNew;
17740}
17741
17742/*
17743** Attempt to reallocate p.  If the reallocation fails, then free p
17744** and set the mallocFailed flag in the database connection.
17745*/
17746SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
17747  void *pNew;
17748  pNew = sqlite3DbRealloc(db, p, n);
17749  if( !pNew ){
17750    sqlite3DbFree(db, p);
17751  }
17752  return pNew;
17753}
17754
17755/*
17756** Make a copy of a string in memory obtained from sqliteMalloc(). These
17757** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
17758** is because when memory debugging is turned on, these two functions are
17759** called via macros that record the current file and line number in the
17760** ThreadData structure.
17761*/
17762SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
17763  char *zNew;
17764  size_t n;
17765  if( z==0 ){
17766    return 0;
17767  }
17768  n = sqlite3Strlen30(z) + 1;
17769  assert( (n&0x7fffffff)==n );
17770  zNew = sqlite3DbMallocRaw(db, (int)n);
17771  if( zNew ){
17772    memcpy(zNew, z, n);
17773  }
17774  return zNew;
17775}
17776SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
17777  char *zNew;
17778  if( z==0 ){
17779    return 0;
17780  }
17781  assert( (n&0x7fffffff)==n );
17782  zNew = sqlite3DbMallocRaw(db, n+1);
17783  if( zNew ){
17784    memcpy(zNew, z, n);
17785    zNew[n] = 0;
17786  }
17787  return zNew;
17788}
17789
17790/*
17791** Create a string from the zFromat argument and the va_list that follows.
17792** Store the string in memory obtained from sqliteMalloc() and make *pz
17793** point to that string.
17794*/
17795SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
17796  va_list ap;
17797  char *z;
17798
17799  va_start(ap, zFormat);
17800  z = sqlite3VMPrintf(db, zFormat, ap);
17801  va_end(ap);
17802  sqlite3DbFree(db, *pz);
17803  *pz = z;
17804}
17805
17806
17807/*
17808** This function must be called before exiting any API function (i.e.
17809** returning control to the user) that has called sqlite3_malloc or
17810** sqlite3_realloc.
17811**
17812** The returned value is normally a copy of the second argument to this
17813** function. However, if a malloc() failure has occurred since the previous
17814** invocation SQLITE_NOMEM is returned instead.
17815**
17816** If the first argument, db, is not NULL and a malloc() error has occurred,
17817** then the connection error-code (the value returned by sqlite3_errcode())
17818** is set to SQLITE_NOMEM.
17819*/
17820SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
17821  /* If the db handle is not NULL, then we must hold the connection handle
17822  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
17823  ** is unsafe, as is the call to sqlite3Error().
17824  */
17825  assert( !db || sqlite3_mutex_held(db->mutex) );
17826  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
17827    sqlite3Error(db, SQLITE_NOMEM, 0);
17828    db->mallocFailed = 0;
17829    rc = SQLITE_NOMEM;
17830  }
17831  return rc & (db ? db->errMask : 0xff);
17832}
17833
17834/************** End of malloc.c **********************************************/
17835/************** Begin file printf.c ******************************************/
17836/*
17837** The "printf" code that follows dates from the 1980's.  It is in
17838** the public domain.  The original comments are included here for
17839** completeness.  They are very out-of-date but might be useful as
17840** an historical reference.  Most of the "enhancements" have been backed
17841** out so that the functionality is now the same as standard printf().
17842**
17843**************************************************************************
17844**
17845** The following modules is an enhanced replacement for the "printf" subroutines
17846** found in the standard C library.  The following enhancements are
17847** supported:
17848**
17849**      +  Additional functions.  The standard set of "printf" functions
17850**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
17851**         vsprintf.  This module adds the following:
17852**
17853**           *  snprintf -- Works like sprintf, but has an extra argument
17854**                          which is the size of the buffer written to.
17855**
17856**           *  mprintf --  Similar to sprintf.  Writes output to memory
17857**                          obtained from malloc.
17858**
17859**           *  xprintf --  Calls a function to dispose of output.
17860**
17861**           *  nprintf --  No output, but returns the number of characters
17862**                          that would have been output by printf.
17863**
17864**           *  A v- version (ex: vsnprintf) of every function is also
17865**              supplied.
17866**
17867**      +  A few extensions to the formatting notation are supported:
17868**
17869**           *  The "=" flag (similar to "-") causes the output to be
17870**              be centered in the appropriately sized field.
17871**
17872**           *  The %b field outputs an integer in binary notation.
17873**
17874**           *  The %c field now accepts a precision.  The character output
17875**              is repeated by the number of times the precision specifies.
17876**
17877**           *  The %' field works like %c, but takes as its character the
17878**              next character of the format string, instead of the next
17879**              argument.  For example,  printf("%.78'-")  prints 78 minus
17880**              signs, the same as  printf("%.78c",'-').
17881**
17882**      +  When compiled using GCC on a SPARC, this version of printf is
17883**         faster than the library printf for SUN OS 4.1.
17884**
17885**      +  All functions are fully reentrant.
17886**
17887*/
17888
17889/*
17890** Conversion types fall into various categories as defined by the
17891** following enumeration.
17892*/
17893#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
17894#define etFLOAT       2 /* Floating point.  %f */
17895#define etEXP         3 /* Exponentional notation. %e and %E */
17896#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
17897#define etSIZE        5 /* Return number of characters processed so far. %n */
17898#define etSTRING      6 /* Strings. %s */
17899#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
17900#define etPERCENT     8 /* Percent symbol. %% */
17901#define etCHARX       9 /* Characters. %c */
17902/* The rest are extensions, not normally found in printf() */
17903#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
17904#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
17905                          NULL pointers replaced by SQL NULL.  %Q */
17906#define etTOKEN      12 /* a pointer to a Token structure */
17907#define etSRCLIST    13 /* a pointer to a SrcList */
17908#define etPOINTER    14 /* The %p conversion */
17909#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
17910#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
17911
17912#define etINVALID     0 /* Any unrecognized conversion type */
17913
17914
17915/*
17916** An "etByte" is an 8-bit unsigned value.
17917*/
17918typedef unsigned char etByte;
17919
17920/*
17921** Each builtin conversion character (ex: the 'd' in "%d") is described
17922** by an instance of the following structure
17923*/
17924typedef struct et_info {   /* Information about each format field */
17925  char fmttype;            /* The format field code letter */
17926  etByte base;             /* The base for radix conversion */
17927  etByte flags;            /* One or more of FLAG_ constants below */
17928  etByte type;             /* Conversion paradigm */
17929  etByte charset;          /* Offset into aDigits[] of the digits string */
17930  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
17931} et_info;
17932
17933/*
17934** Allowed values for et_info.flags
17935*/
17936#define FLAG_SIGNED  1     /* True if the value to convert is signed */
17937#define FLAG_INTERN  2     /* True if for internal use only */
17938#define FLAG_STRING  4     /* Allow infinity precision */
17939
17940
17941/*
17942** The following table is searched linearly, so it is good to put the
17943** most frequently used conversion types first.
17944*/
17945static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
17946static const char aPrefix[] = "-x0\000X0";
17947static const et_info fmtinfo[] = {
17948  {  'd', 10, 1, etRADIX,      0,  0 },
17949  {  's',  0, 4, etSTRING,     0,  0 },
17950  {  'g',  0, 1, etGENERIC,    30, 0 },
17951  {  'z',  0, 4, etDYNSTRING,  0,  0 },
17952  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
17953  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
17954  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
17955  {  'c',  0, 0, etCHARX,      0,  0 },
17956  {  'o',  8, 0, etRADIX,      0,  2 },
17957  {  'u', 10, 0, etRADIX,      0,  0 },
17958  {  'x', 16, 0, etRADIX,      16, 1 },
17959  {  'X', 16, 0, etRADIX,      0,  4 },
17960#ifndef SQLITE_OMIT_FLOATING_POINT
17961  {  'f',  0, 1, etFLOAT,      0,  0 },
17962  {  'e',  0, 1, etEXP,        30, 0 },
17963  {  'E',  0, 1, etEXP,        14, 0 },
17964  {  'G',  0, 1, etGENERIC,    14, 0 },
17965#endif
17966  {  'i', 10, 1, etRADIX,      0,  0 },
17967  {  'n',  0, 0, etSIZE,       0,  0 },
17968  {  '%',  0, 0, etPERCENT,    0,  0 },
17969  {  'p', 16, 0, etPOINTER,    0,  1 },
17970
17971/* All the rest have the FLAG_INTERN bit set and are thus for internal
17972** use only */
17973  {  'T',  0, 2, etTOKEN,      0,  0 },
17974  {  'S',  0, 2, etSRCLIST,    0,  0 },
17975  {  'r', 10, 3, etORDINAL,    0,  0 },
17976};
17977
17978/*
17979** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
17980** conversions will work.
17981*/
17982#ifndef SQLITE_OMIT_FLOATING_POINT
17983/*
17984** "*val" is a double such that 0.1 <= *val < 10.0
17985** Return the ascii code for the leading digit of *val, then
17986** multiply "*val" by 10.0 to renormalize.
17987**
17988** Example:
17989**     input:     *val = 3.14159
17990**     output:    *val = 1.4159    function return = '3'
17991**
17992** The counter *cnt is incremented each time.  After counter exceeds
17993** 16 (the number of significant digits in a 64-bit float) '0' is
17994** always returned.
17995*/
17996static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
17997  int digit;
17998  LONGDOUBLE_TYPE d;
17999  if( (*cnt)++ >= 16 ) return '0';
18000  digit = (int)*val;
18001  d = digit;
18002  digit += '0';
18003  *val = (*val - d)*10.0;
18004  return (char)digit;
18005}
18006#endif /* SQLITE_OMIT_FLOATING_POINT */
18007
18008/*
18009** Append N space characters to the given string buffer.
18010*/
18011static void appendSpace(StrAccum *pAccum, int N){
18012  static const char zSpaces[] = "                             ";
18013  while( N>=(int)sizeof(zSpaces)-1 ){
18014    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18015    N -= sizeof(zSpaces)-1;
18016  }
18017  if( N>0 ){
18018    sqlite3StrAccumAppend(pAccum, zSpaces, N);
18019  }
18020}
18021
18022/*
18023** On machines with a small stack size, you can redefine the
18024** SQLITE_PRINT_BUF_SIZE to be less than 350.
18025*/
18026#ifndef SQLITE_PRINT_BUF_SIZE
18027# if defined(SQLITE_SMALL_STACK)
18028#   define SQLITE_PRINT_BUF_SIZE 50
18029# else
18030#   define SQLITE_PRINT_BUF_SIZE 350
18031# endif
18032#endif
18033#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18034
18035/*
18036** The root program.  All variations call this core.
18037**
18038** INPUTS:
18039**   func   This is a pointer to a function taking three arguments
18040**            1. A pointer to anything.  Same as the "arg" parameter.
18041**            2. A pointer to the list of characters to be output
18042**               (Note, this list is NOT null terminated.)
18043**            3. An integer number of characters to be output.
18044**               (Note: This number might be zero.)
18045**
18046**   arg    This is the pointer to anything which will be passed as the
18047**          first argument to "func".  Use it for whatever you like.
18048**
18049**   fmt    This is the format string, as in the usual print.
18050**
18051**   ap     This is a pointer to a list of arguments.  Same as in
18052**          vfprint.
18053**
18054** OUTPUTS:
18055**          The return value is the total number of characters sent to
18056**          the function "func".  Returns -1 on a error.
18057**
18058** Note that the order in which automatic variables are declared below
18059** seems to make a big difference in determining how fast this beast
18060** will run.
18061*/
18062SQLITE_PRIVATE void sqlite3VXPrintf(
18063  StrAccum *pAccum,                  /* Accumulate results here */
18064  int useExtended,                   /* Allow extended %-conversions */
18065  const char *fmt,                   /* Format string */
18066  va_list ap                         /* arguments */
18067){
18068  int c;                     /* Next character in the format string */
18069  char *bufpt;               /* Pointer to the conversion buffer */
18070  int precision;             /* Precision of the current field */
18071  int length;                /* Length of the field */
18072  int idx;                   /* A general purpose loop counter */
18073  int width;                 /* Width of the current field */
18074  etByte flag_leftjustify;   /* True if "-" flag is present */
18075  etByte flag_plussign;      /* True if "+" flag is present */
18076  etByte flag_blanksign;     /* True if " " flag is present */
18077  etByte flag_alternateform; /* True if "#" flag is present */
18078  etByte flag_altform2;      /* True if "!" flag is present */
18079  etByte flag_zeropad;       /* True if field width constant starts with zero */
18080  etByte flag_long;          /* True if "l" flag is present */
18081  etByte flag_longlong;      /* True if the "ll" flag is present */
18082  etByte done;               /* Loop termination flag */
18083  sqlite_uint64 longvalue;   /* Value for integer types */
18084  LONGDOUBLE_TYPE realvalue; /* Value for real types */
18085  const et_info *infop;      /* Pointer to the appropriate info structure */
18086  char buf[etBUFSIZE];       /* Conversion buffer */
18087  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18088  etByte xtype = 0;          /* Conversion paradigm */
18089  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18090#ifndef SQLITE_OMIT_FLOATING_POINT
18091  int  exp, e2;              /* exponent of real numbers */
18092  double rounder;            /* Used for rounding floating point values */
18093  etByte flag_dp;            /* True if decimal point should be shown */
18094  etByte flag_rtz;           /* True if trailing zeros should be removed */
18095  etByte flag_exp;           /* True to force display of the exponent */
18096  int nsd;                   /* Number of significant digits returned */
18097#endif
18098
18099  length = 0;
18100  bufpt = 0;
18101  for(; (c=(*fmt))!=0; ++fmt){
18102    if( c!='%' ){
18103      int amt;
18104      bufpt = (char *)fmt;
18105      amt = 1;
18106      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18107      sqlite3StrAccumAppend(pAccum, bufpt, amt);
18108      if( c==0 ) break;
18109    }
18110    if( (c=(*++fmt))==0 ){
18111      sqlite3StrAccumAppend(pAccum, "%", 1);
18112      break;
18113    }
18114    /* Find out what flags are present */
18115    flag_leftjustify = flag_plussign = flag_blanksign =
18116     flag_alternateform = flag_altform2 = flag_zeropad = 0;
18117    done = 0;
18118    do{
18119      switch( c ){
18120        case '-':   flag_leftjustify = 1;     break;
18121        case '+':   flag_plussign = 1;        break;
18122        case ' ':   flag_blanksign = 1;       break;
18123        case '#':   flag_alternateform = 1;   break;
18124        case '!':   flag_altform2 = 1;        break;
18125        case '0':   flag_zeropad = 1;         break;
18126        default:    done = 1;                 break;
18127      }
18128    }while( !done && (c=(*++fmt))!=0 );
18129    /* Get the field width */
18130    width = 0;
18131    if( c=='*' ){
18132      width = va_arg(ap,int);
18133      if( width<0 ){
18134        flag_leftjustify = 1;
18135        width = -width;
18136      }
18137      c = *++fmt;
18138    }else{
18139      while( c>='0' && c<='9' ){
18140        width = width*10 + c - '0';
18141        c = *++fmt;
18142      }
18143    }
18144    if( width > etBUFSIZE-10 ){
18145      width = etBUFSIZE-10;
18146    }
18147    /* Get the precision */
18148    if( c=='.' ){
18149      precision = 0;
18150      c = *++fmt;
18151      if( c=='*' ){
18152        precision = va_arg(ap,int);
18153        if( precision<0 ) precision = -precision;
18154        c = *++fmt;
18155      }else{
18156        while( c>='0' && c<='9' ){
18157          precision = precision*10 + c - '0';
18158          c = *++fmt;
18159        }
18160      }
18161    }else{
18162      precision = -1;
18163    }
18164    /* Get the conversion type modifier */
18165    if( c=='l' ){
18166      flag_long = 1;
18167      c = *++fmt;
18168      if( c=='l' ){
18169        flag_longlong = 1;
18170        c = *++fmt;
18171      }else{
18172        flag_longlong = 0;
18173      }
18174    }else{
18175      flag_long = flag_longlong = 0;
18176    }
18177    /* Fetch the info entry for the field */
18178    infop = &fmtinfo[0];
18179    xtype = etINVALID;
18180    for(idx=0; idx<ArraySize(fmtinfo); idx++){
18181      if( c==fmtinfo[idx].fmttype ){
18182        infop = &fmtinfo[idx];
18183        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18184          xtype = infop->type;
18185        }else{
18186          return;
18187        }
18188        break;
18189      }
18190    }
18191    zExtra = 0;
18192
18193
18194    /* Limit the precision to prevent overflowing buf[] during conversion */
18195    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18196      precision = etBUFSIZE-40;
18197    }
18198
18199    /*
18200    ** At this point, variables are initialized as follows:
18201    **
18202    **   flag_alternateform          TRUE if a '#' is present.
18203    **   flag_altform2               TRUE if a '!' is present.
18204    **   flag_plussign               TRUE if a '+' is present.
18205    **   flag_leftjustify            TRUE if a '-' is present or if the
18206    **                               field width was negative.
18207    **   flag_zeropad                TRUE if the width began with 0.
18208    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18209    **                               the conversion character.
18210    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18211    **                               the conversion character.
18212    **   flag_blanksign              TRUE if a ' ' is present.
18213    **   width                       The specified field width.  This is
18214    **                               always non-negative.  Zero is the default.
18215    **   precision                   The specified precision.  The default
18216    **                               is -1.
18217    **   xtype                       The class of the conversion.
18218    **   infop                       Pointer to the appropriate info struct.
18219    */
18220    switch( xtype ){
18221      case etPOINTER:
18222        flag_longlong = sizeof(char*)==sizeof(i64);
18223        flag_long = sizeof(char*)==sizeof(long int);
18224        /* Fall through into the next case */
18225      case etORDINAL:
18226      case etRADIX:
18227        if( infop->flags & FLAG_SIGNED ){
18228          i64 v;
18229          if( flag_longlong ){
18230            v = va_arg(ap,i64);
18231          }else if( flag_long ){
18232            v = va_arg(ap,long int);
18233          }else{
18234            v = va_arg(ap,int);
18235          }
18236          if( v<0 ){
18237            longvalue = -v;
18238            prefix = '-';
18239          }else{
18240            longvalue = v;
18241            if( flag_plussign )        prefix = '+';
18242            else if( flag_blanksign )  prefix = ' ';
18243            else                       prefix = 0;
18244          }
18245        }else{
18246          if( flag_longlong ){
18247            longvalue = va_arg(ap,u64);
18248          }else if( flag_long ){
18249            longvalue = va_arg(ap,unsigned long int);
18250          }else{
18251            longvalue = va_arg(ap,unsigned int);
18252          }
18253          prefix = 0;
18254        }
18255        if( longvalue==0 ) flag_alternateform = 0;
18256        if( flag_zeropad && precision<width-(prefix!=0) ){
18257          precision = width-(prefix!=0);
18258        }
18259        bufpt = &buf[etBUFSIZE-1];
18260        if( xtype==etORDINAL ){
18261          static const char zOrd[] = "thstndrd";
18262          int x = (int)(longvalue % 10);
18263          if( x>=4 || (longvalue/10)%10==1 ){
18264            x = 0;
18265          }
18266          buf[etBUFSIZE-3] = zOrd[x*2];
18267          buf[etBUFSIZE-2] = zOrd[x*2+1];
18268          bufpt -= 2;
18269        }
18270        {
18271          register const char *cset;      /* Use registers for speed */
18272          register int base;
18273          cset = &aDigits[infop->charset];
18274          base = infop->base;
18275          do{                                           /* Convert to ascii */
18276            *(--bufpt) = cset[longvalue%base];
18277            longvalue = longvalue/base;
18278          }while( longvalue>0 );
18279        }
18280        length = (int)(&buf[etBUFSIZE-1]-bufpt);
18281        for(idx=precision-length; idx>0; idx--){
18282          *(--bufpt) = '0';                             /* Zero pad */
18283        }
18284        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18285        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18286          const char *pre;
18287          char x;
18288          pre = &aPrefix[infop->prefix];
18289          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18290        }
18291        length = (int)(&buf[etBUFSIZE-1]-bufpt);
18292        break;
18293      case etFLOAT:
18294      case etEXP:
18295      case etGENERIC:
18296        realvalue = va_arg(ap,double);
18297#ifdef SQLITE_OMIT_FLOATING_POINT
18298        length = 0;
18299#else
18300        if( precision<0 ) precision = 6;         /* Set default precision */
18301        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18302        if( realvalue<0.0 ){
18303          realvalue = -realvalue;
18304          prefix = '-';
18305        }else{
18306          if( flag_plussign )          prefix = '+';
18307          else if( flag_blanksign )    prefix = ' ';
18308          else                         prefix = 0;
18309        }
18310        if( xtype==etGENERIC && precision>0 ) precision--;
18311#if 0
18312        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18313        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18314#else
18315        /* It makes more sense to use 0.5 */
18316        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18317#endif
18318        if( xtype==etFLOAT ) realvalue += rounder;
18319        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18320        exp = 0;
18321        if( sqlite3IsNaN((double)realvalue) ){
18322          bufpt = "NaN";
18323          length = 3;
18324          break;
18325        }
18326        if( realvalue>0.0 ){
18327          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18328          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18329          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18330          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18331          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18332          if( exp>350 ){
18333            if( prefix=='-' ){
18334              bufpt = "-Inf";
18335            }else if( prefix=='+' ){
18336              bufpt = "+Inf";
18337            }else{
18338              bufpt = "Inf";
18339            }
18340            length = sqlite3Strlen30(bufpt);
18341            break;
18342          }
18343        }
18344        bufpt = buf;
18345        /*
18346        ** If the field type is etGENERIC, then convert to either etEXP
18347        ** or etFLOAT, as appropriate.
18348        */
18349        flag_exp = xtype==etEXP;
18350        if( xtype!=etFLOAT ){
18351          realvalue += rounder;
18352          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18353        }
18354        if( xtype==etGENERIC ){
18355          flag_rtz = !flag_alternateform;
18356          if( exp<-4 || exp>precision ){
18357            xtype = etEXP;
18358          }else{
18359            precision = precision - exp;
18360            xtype = etFLOAT;
18361          }
18362        }else{
18363          flag_rtz = 0;
18364        }
18365        if( xtype==etEXP ){
18366          e2 = 0;
18367        }else{
18368          e2 = exp;
18369        }
18370        nsd = 0;
18371        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
18372        /* The sign in front of the number */
18373        if( prefix ){
18374          *(bufpt++) = prefix;
18375        }
18376        /* Digits prior to the decimal point */
18377        if( e2<0 ){
18378          *(bufpt++) = '0';
18379        }else{
18380          for(; e2>=0; e2--){
18381            *(bufpt++) = et_getdigit(&realvalue,&nsd);
18382          }
18383        }
18384        /* The decimal point */
18385        if( flag_dp ){
18386          *(bufpt++) = '.';
18387        }
18388        /* "0" digits after the decimal point but before the first
18389        ** significant digit of the number */
18390        for(e2++; e2<0; precision--, e2++){
18391          assert( precision>0 );
18392          *(bufpt++) = '0';
18393        }
18394        /* Significant digits after the decimal point */
18395        while( (precision--)>0 ){
18396          *(bufpt++) = et_getdigit(&realvalue,&nsd);
18397        }
18398        /* Remove trailing zeros and the "." if no digits follow the "." */
18399        if( flag_rtz && flag_dp ){
18400          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
18401          assert( bufpt>buf );
18402          if( bufpt[-1]=='.' ){
18403            if( flag_altform2 ){
18404              *(bufpt++) = '0';
18405            }else{
18406              *(--bufpt) = 0;
18407            }
18408          }
18409        }
18410        /* Add the "eNNN" suffix */
18411        if( flag_exp || xtype==etEXP ){
18412          *(bufpt++) = aDigits[infop->charset];
18413          if( exp<0 ){
18414            *(bufpt++) = '-'; exp = -exp;
18415          }else{
18416            *(bufpt++) = '+';
18417          }
18418          if( exp>=100 ){
18419            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
18420            exp %= 100;
18421          }
18422          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
18423          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
18424        }
18425        *bufpt = 0;
18426
18427        /* The converted number is in buf[] and zero terminated. Output it.
18428        ** Note that the number is in the usual order, not reversed as with
18429        ** integer conversions. */
18430        length = (int)(bufpt-buf);
18431        bufpt = buf;
18432
18433        /* Special case:  Add leading zeros if the flag_zeropad flag is
18434        ** set and we are not left justified */
18435        if( flag_zeropad && !flag_leftjustify && length < width){
18436          int i;
18437          int nPad = width - length;
18438          for(i=width; i>=nPad; i--){
18439            bufpt[i] = bufpt[i-nPad];
18440          }
18441          i = prefix!=0;
18442          while( nPad-- ) bufpt[i++] = '0';
18443          length = width;
18444        }
18445#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
18446        break;
18447      case etSIZE:
18448        *(va_arg(ap,int*)) = pAccum->nChar;
18449        length = width = 0;
18450        break;
18451      case etPERCENT:
18452        buf[0] = '%';
18453        bufpt = buf;
18454        length = 1;
18455        break;
18456      case etCHARX:
18457        c = va_arg(ap,int);
18458        buf[0] = (char)c;
18459        if( precision>=0 ){
18460          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
18461          length = precision;
18462        }else{
18463          length =1;
18464        }
18465        bufpt = buf;
18466        break;
18467      case etSTRING:
18468      case etDYNSTRING:
18469        bufpt = va_arg(ap,char*);
18470        if( bufpt==0 ){
18471          bufpt = "";
18472        }else if( xtype==etDYNSTRING ){
18473          zExtra = bufpt;
18474        }
18475        if( precision>=0 ){
18476          for(length=0; length<precision && bufpt[length]; length++){}
18477        }else{
18478          length = sqlite3Strlen30(bufpt);
18479        }
18480        break;
18481      case etSQLESCAPE:
18482      case etSQLESCAPE2:
18483      case etSQLESCAPE3: {
18484        int i, j, k, n, isnull;
18485        int needQuote;
18486        char ch;
18487        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
18488        char *escarg = va_arg(ap,char*);
18489        isnull = escarg==0;
18490        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
18491        k = precision;
18492        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
18493          if( ch==q )  n++;
18494        }
18495        needQuote = !isnull && xtype==etSQLESCAPE2;
18496        n += i + 1 + needQuote*2;
18497        if( n>etBUFSIZE ){
18498          bufpt = zExtra = sqlite3Malloc( n );
18499          if( bufpt==0 ){
18500            pAccum->mallocFailed = 1;
18501            return;
18502          }
18503        }else{
18504          bufpt = buf;
18505        }
18506        j = 0;
18507        if( needQuote ) bufpt[j++] = q;
18508        k = i;
18509        for(i=0; i<k; i++){
18510          bufpt[j++] = ch = escarg[i];
18511          if( ch==q ) bufpt[j++] = ch;
18512        }
18513        if( needQuote ) bufpt[j++] = q;
18514        bufpt[j] = 0;
18515        length = j;
18516        /* The precision in %q and %Q means how many input characters to
18517        ** consume, not the length of the output...
18518        ** if( precision>=0 && precision<length ) length = precision; */
18519        break;
18520      }
18521      case etTOKEN: {
18522        Token *pToken = va_arg(ap, Token*);
18523        if( pToken ){
18524          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
18525        }
18526        length = width = 0;
18527        break;
18528      }
18529      case etSRCLIST: {
18530        SrcList *pSrc = va_arg(ap, SrcList*);
18531        int k = va_arg(ap, int);
18532        struct SrcList_item *pItem = &pSrc->a[k];
18533        assert( k>=0 && k<pSrc->nSrc );
18534        if( pItem->zDatabase ){
18535          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
18536          sqlite3StrAccumAppend(pAccum, ".", 1);
18537        }
18538        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
18539        length = width = 0;
18540        break;
18541      }
18542      default: {
18543        assert( xtype==etINVALID );
18544        return;
18545      }
18546    }/* End switch over the format type */
18547    /*
18548    ** The text of the conversion is pointed to by "bufpt" and is
18549    ** "length" characters long.  The field width is "width".  Do
18550    ** the output.
18551    */
18552    if( !flag_leftjustify ){
18553      register int nspace;
18554      nspace = width-length;
18555      if( nspace>0 ){
18556        appendSpace(pAccum, nspace);
18557      }
18558    }
18559    if( length>0 ){
18560      sqlite3StrAccumAppend(pAccum, bufpt, length);
18561    }
18562    if( flag_leftjustify ){
18563      register int nspace;
18564      nspace = width-length;
18565      if( nspace>0 ){
18566        appendSpace(pAccum, nspace);
18567      }
18568    }
18569    if( zExtra ){
18570      sqlite3_free(zExtra);
18571    }
18572  }/* End for loop over the format string */
18573} /* End of function */
18574
18575/*
18576** Append N bytes of text from z to the StrAccum object.
18577*/
18578SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
18579  assert( z!=0 || N==0 );
18580  if( p->tooBig | p->mallocFailed ){
18581    testcase(p->tooBig);
18582    testcase(p->mallocFailed);
18583    return;
18584  }
18585  if( N<0 ){
18586    N = sqlite3Strlen30(z);
18587  }
18588  if( N==0 || NEVER(z==0) ){
18589    return;
18590  }
18591  if( p->nChar+N >= p->nAlloc ){
18592    char *zNew;
18593    if( !p->useMalloc ){
18594      p->tooBig = 1;
18595      N = p->nAlloc - p->nChar - 1;
18596      if( N<=0 ){
18597        return;
18598      }
18599    }else{
18600      i64 szNew = p->nChar;
18601      szNew += N + 1;
18602      if( szNew > p->mxAlloc ){
18603        sqlite3StrAccumReset(p);
18604        p->tooBig = 1;
18605        return;
18606      }else{
18607        p->nAlloc = (int)szNew;
18608      }
18609      if( p->useMalloc==1 ){
18610        zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
18611      }else{
18612        zNew = sqlite3_malloc(p->nAlloc);
18613      }
18614      if( zNew ){
18615        memcpy(zNew, p->zText, p->nChar);
18616        sqlite3StrAccumReset(p);
18617        p->zText = zNew;
18618      }else{
18619        p->mallocFailed = 1;
18620        sqlite3StrAccumReset(p);
18621        return;
18622      }
18623    }
18624  }
18625  memcpy(&p->zText[p->nChar], z, N);
18626  p->nChar += N;
18627}
18628
18629/*
18630** Finish off a string by making sure it is zero-terminated.
18631** Return a pointer to the resulting string.  Return a NULL
18632** pointer if any kind of error was encountered.
18633*/
18634SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
18635  if( p->zText ){
18636    p->zText[p->nChar] = 0;
18637    if( p->useMalloc && p->zText==p->zBase ){
18638      if( p->useMalloc==1 ){
18639        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
18640      }else{
18641        p->zText = sqlite3_malloc(p->nChar+1);
18642      }
18643      if( p->zText ){
18644        memcpy(p->zText, p->zBase, p->nChar+1);
18645      }else{
18646        p->mallocFailed = 1;
18647      }
18648    }
18649  }
18650  return p->zText;
18651}
18652
18653/*
18654** Reset an StrAccum string.  Reclaim all malloced memory.
18655*/
18656SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
18657  if( p->zText!=p->zBase ){
18658    if( p->useMalloc==1 ){
18659      sqlite3DbFree(p->db, p->zText);
18660    }else{
18661      sqlite3_free(p->zText);
18662    }
18663  }
18664  p->zText = 0;
18665}
18666
18667/*
18668** Initialize a string accumulator
18669*/
18670SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
18671  p->zText = p->zBase = zBase;
18672  p->db = 0;
18673  p->nChar = 0;
18674  p->nAlloc = n;
18675  p->mxAlloc = mx;
18676  p->useMalloc = 1;
18677  p->tooBig = 0;
18678  p->mallocFailed = 0;
18679}
18680
18681/*
18682** Print into memory obtained from sqliteMalloc().  Use the internal
18683** %-conversion extensions.
18684*/
18685SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
18686  char *z;
18687  char zBase[SQLITE_PRINT_BUF_SIZE];
18688  StrAccum acc;
18689  assert( db!=0 );
18690  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
18691                      db->aLimit[SQLITE_LIMIT_LENGTH]);
18692  acc.db = db;
18693  sqlite3VXPrintf(&acc, 1, zFormat, ap);
18694  z = sqlite3StrAccumFinish(&acc);
18695  if( acc.mallocFailed ){
18696    db->mallocFailed = 1;
18697  }
18698  return z;
18699}
18700
18701/*
18702** Print into memory obtained from sqliteMalloc().  Use the internal
18703** %-conversion extensions.
18704*/
18705SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
18706  va_list ap;
18707  char *z;
18708  va_start(ap, zFormat);
18709  z = sqlite3VMPrintf(db, zFormat, ap);
18710  va_end(ap);
18711  return z;
18712}
18713
18714/*
18715** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
18716** the string and before returnning.  This routine is intended to be used
18717** to modify an existing string.  For example:
18718**
18719**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
18720**
18721*/
18722SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
18723  va_list ap;
18724  char *z;
18725  va_start(ap, zFormat);
18726  z = sqlite3VMPrintf(db, zFormat, ap);
18727  va_end(ap);
18728  sqlite3DbFree(db, zStr);
18729  return z;
18730}
18731
18732/*
18733** Print into memory obtained from sqlite3_malloc().  Omit the internal
18734** %-conversion extensions.
18735*/
18736SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
18737  char *z;
18738  char zBase[SQLITE_PRINT_BUF_SIZE];
18739  StrAccum acc;
18740#ifndef SQLITE_OMIT_AUTOINIT
18741  if( sqlite3_initialize() ) return 0;
18742#endif
18743  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
18744  acc.useMalloc = 2;
18745  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18746  z = sqlite3StrAccumFinish(&acc);
18747  return z;
18748}
18749
18750/*
18751** Print into memory obtained from sqlite3_malloc()().  Omit the internal
18752** %-conversion extensions.
18753*/
18754SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
18755  va_list ap;
18756  char *z;
18757#ifndef SQLITE_OMIT_AUTOINIT
18758  if( sqlite3_initialize() ) return 0;
18759#endif
18760  va_start(ap, zFormat);
18761  z = sqlite3_vmprintf(zFormat, ap);
18762  va_end(ap);
18763  return z;
18764}
18765
18766/*
18767** sqlite3_snprintf() works like snprintf() except that it ignores the
18768** current locale settings.  This is important for SQLite because we
18769** are not able to use a "," as the decimal point in place of "." as
18770** specified by some locales.
18771*/
18772SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
18773  char *z;
18774  va_list ap;
18775  StrAccum acc;
18776
18777  if( n<=0 ){
18778    return zBuf;
18779  }
18780  sqlite3StrAccumInit(&acc, zBuf, n, 0);
18781  acc.useMalloc = 0;
18782  va_start(ap,zFormat);
18783  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18784  va_end(ap);
18785  z = sqlite3StrAccumFinish(&acc);
18786  return z;
18787}
18788
18789/*
18790** This is the routine that actually formats the sqlite3_log() message.
18791** We house it in a separate routine from sqlite3_log() to avoid using
18792** stack space on small-stack systems when logging is disabled.
18793**
18794** sqlite3_log() must render into a static buffer.  It cannot dynamically
18795** allocate memory because it might be called while the memory allocator
18796** mutex is held.
18797*/
18798static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
18799  StrAccum acc;                          /* String accumulator */
18800  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
18801
18802  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
18803  acc.useMalloc = 0;
18804  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18805  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
18806                           sqlite3StrAccumFinish(&acc));
18807}
18808
18809/*
18810** Format and write a message to the log if logging is enabled.
18811*/
18812SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
18813  va_list ap;                             /* Vararg list */
18814  if( sqlite3GlobalConfig.xLog ){
18815    va_start(ap, zFormat);
18816    renderLogMsg(iErrCode, zFormat, ap);
18817    va_end(ap);
18818  }
18819}
18820
18821#if defined(SQLITE_DEBUG)
18822/*
18823** A version of printf() that understands %lld.  Used for debugging.
18824** The printf() built into some versions of windows does not understand %lld
18825** and segfaults if you give it a long long int.
18826*/
18827SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
18828  va_list ap;
18829  StrAccum acc;
18830  char zBuf[500];
18831  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
18832  acc.useMalloc = 0;
18833  va_start(ap,zFormat);
18834  sqlite3VXPrintf(&acc, 0, zFormat, ap);
18835  va_end(ap);
18836  sqlite3StrAccumFinish(&acc);
18837  fprintf(stdout,"%s", zBuf);
18838  fflush(stdout);
18839}
18840#endif
18841
18842#ifndef SQLITE_OMIT_TRACE
18843/*
18844** variable-argument wrapper around sqlite3VXPrintf().
18845*/
18846SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
18847  va_list ap;
18848  va_start(ap,zFormat);
18849  sqlite3VXPrintf(p, 1, zFormat, ap);
18850  va_end(ap);
18851}
18852#endif
18853
18854/************** End of printf.c **********************************************/
18855/************** Begin file random.c ******************************************/
18856/*
18857** 2001 September 15
18858**
18859** The author disclaims copyright to this source code.  In place of
18860** a legal notice, here is a blessing:
18861**
18862**    May you do good and not evil.
18863**    May you find forgiveness for yourself and forgive others.
18864**    May you share freely, never taking more than you give.
18865**
18866*************************************************************************
18867** This file contains code to implement a pseudo-random number
18868** generator (PRNG) for SQLite.
18869**
18870** Random numbers are used by some of the database backends in order
18871** to generate random integer keys for tables or random filenames.
18872*/
18873
18874
18875/* All threads share a single random number generator.
18876** This structure is the current state of the generator.
18877*/
18878static SQLITE_WSD struct sqlite3PrngType {
18879  unsigned char isInit;          /* True if initialized */
18880  unsigned char i, j;            /* State variables */
18881  unsigned char s[256];          /* State variables */
18882} sqlite3Prng;
18883
18884/*
18885** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
18886** must be held while executing this routine.
18887**
18888** Why not just use a library random generator like lrand48() for this?
18889** Because the OP_NewRowid opcode in the VDBE depends on having a very
18890** good source of random numbers.  The lrand48() library function may
18891** well be good enough.  But maybe not.  Or maybe lrand48() has some
18892** subtle problems on some systems that could cause problems.  It is hard
18893** to know.  To minimize the risk of problems due to bad lrand48()
18894** implementations, SQLite uses this random number generator based
18895** on RC4, which we know works very well.
18896**
18897** (Later):  Actually, OP_NewRowid does not depend on a good source of
18898** randomness any more.  But we will leave this code in all the same.
18899*/
18900static u8 randomByte(void){
18901  unsigned char t;
18902
18903
18904  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
18905  ** state vector.  If writable static data is unsupported on the target,
18906  ** we have to locate the state vector at run-time.  In the more common
18907  ** case where writable static data is supported, wsdPrng can refer directly
18908  ** to the "sqlite3Prng" state vector declared above.
18909  */
18910#ifdef SQLITE_OMIT_WSD
18911  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
18912# define wsdPrng p[0]
18913#else
18914# define wsdPrng sqlite3Prng
18915#endif
18916
18917
18918  /* Initialize the state of the random number generator once,
18919  ** the first time this routine is called.  The seed value does
18920  ** not need to contain a lot of randomness since we are not
18921  ** trying to do secure encryption or anything like that...
18922  **
18923  ** Nothing in this file or anywhere else in SQLite does any kind of
18924  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
18925  ** number generator) not as an encryption device.
18926  */
18927  if( !wsdPrng.isInit ){
18928    int i;
18929    char k[256];
18930    wsdPrng.j = 0;
18931    wsdPrng.i = 0;
18932    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
18933    for(i=0; i<256; i++){
18934      wsdPrng.s[i] = (u8)i;
18935    }
18936    for(i=0; i<256; i++){
18937      wsdPrng.j += wsdPrng.s[i] + k[i];
18938      t = wsdPrng.s[wsdPrng.j];
18939      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
18940      wsdPrng.s[i] = t;
18941    }
18942    wsdPrng.isInit = 1;
18943  }
18944
18945  /* Generate and return single random byte
18946  */
18947  wsdPrng.i++;
18948  t = wsdPrng.s[wsdPrng.i];
18949  wsdPrng.j += t;
18950  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
18951  wsdPrng.s[wsdPrng.j] = t;
18952  t += wsdPrng.s[wsdPrng.i];
18953  return wsdPrng.s[t];
18954}
18955
18956/*
18957** Return N random bytes.
18958*/
18959SQLITE_API void sqlite3_randomness(int N, void *pBuf){
18960  unsigned char *zBuf = pBuf;
18961#if SQLITE_THREADSAFE
18962  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
18963#endif
18964  sqlite3_mutex_enter(mutex);
18965  while( N-- ){
18966    *(zBuf++) = randomByte();
18967  }
18968  sqlite3_mutex_leave(mutex);
18969}
18970
18971#ifndef SQLITE_OMIT_BUILTIN_TEST
18972/*
18973** For testing purposes, we sometimes want to preserve the state of
18974** PRNG and restore the PRNG to its saved state at a later time, or
18975** to reset the PRNG to its initial state.  These routines accomplish
18976** those tasks.
18977**
18978** The sqlite3_test_control() interface calls these routines to
18979** control the PRNG.
18980*/
18981static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
18982SQLITE_PRIVATE void sqlite3PrngSaveState(void){
18983  memcpy(
18984    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18985    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18986    sizeof(sqlite3Prng)
18987  );
18988}
18989SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
18990  memcpy(
18991    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
18992    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
18993    sizeof(sqlite3Prng)
18994  );
18995}
18996SQLITE_PRIVATE void sqlite3PrngResetState(void){
18997  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
18998}
18999#endif /* SQLITE_OMIT_BUILTIN_TEST */
19000
19001/************** End of random.c **********************************************/
19002/************** Begin file utf.c *********************************************/
19003/*
19004** 2004 April 13
19005**
19006** The author disclaims copyright to this source code.  In place of
19007** a legal notice, here is a blessing:
19008**
19009**    May you do good and not evil.
19010**    May you find forgiveness for yourself and forgive others.
19011**    May you share freely, never taking more than you give.
19012**
19013*************************************************************************
19014** This file contains routines used to translate between UTF-8,
19015** UTF-16, UTF-16BE, and UTF-16LE.
19016**
19017** Notes on UTF-8:
19018**
19019**   Byte-0    Byte-1    Byte-2    Byte-3    Value
19020**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19021**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19022**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19023**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19024**
19025**
19026** Notes on UTF-16:  (with wwww+1==uuuuu)
19027**
19028**      Word-0               Word-1          Value
19029**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19030**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19031**
19032**
19033** BOM or Byte Order Mark:
19034**     0xff 0xfe   little-endian utf-16 follows
19035**     0xfe 0xff   big-endian utf-16 follows
19036**
19037*/
19038
19039#ifndef SQLITE_AMALGAMATION
19040/*
19041** The following constant value is used by the SQLITE_BIGENDIAN and
19042** SQLITE_LITTLEENDIAN macros.
19043*/
19044SQLITE_PRIVATE const int sqlite3one = 1;
19045#endif /* SQLITE_AMALGAMATION */
19046
19047/*
19048** This lookup table is used to help decode the first byte of
19049** a multi-byte UTF8 character.
19050*/
19051static const unsigned char sqlite3Utf8Trans1[] = {
19052  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19053  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19054  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19055  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19056  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19057  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19058  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19059  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19060};
19061
19062
19063#define WRITE_UTF8(zOut, c) {                          \
19064  if( c<0x00080 ){                                     \
19065    *zOut++ = (u8)(c&0xFF);                            \
19066  }                                                    \
19067  else if( c<0x00800 ){                                \
19068    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19069    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19070  }                                                    \
19071  else if( c<0x10000 ){                                \
19072    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19073    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19074    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19075  }else{                                               \
19076    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19077    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19078    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19079    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19080  }                                                    \
19081}
19082
19083#define WRITE_UTF16LE(zOut, c) {                                    \
19084  if( c<=0xFFFF ){                                                  \
19085    *zOut++ = (u8)(c&0x00FF);                                       \
19086    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19087  }else{                                                            \
19088    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19089    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19090    *zOut++ = (u8)(c&0x00FF);                                       \
19091    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19092  }                                                                 \
19093}
19094
19095#define WRITE_UTF16BE(zOut, c) {                                    \
19096  if( c<=0xFFFF ){                                                  \
19097    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19098    *zOut++ = (u8)(c&0x00FF);                                       \
19099  }else{                                                            \
19100    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19101    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19102    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19103    *zOut++ = (u8)(c&0x00FF);                                       \
19104  }                                                                 \
19105}
19106
19107#define READ_UTF16LE(zIn, TERM, c){                                   \
19108  c = (*zIn++);                                                       \
19109  c += ((*zIn++)<<8);                                                 \
19110  if( c>=0xD800 && c<0xE000 && TERM ){                                \
19111    int c2 = (*zIn++);                                                \
19112    c2 += ((*zIn++)<<8);                                              \
19113    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19114  }                                                                   \
19115}
19116
19117#define READ_UTF16BE(zIn, TERM, c){                                   \
19118  c = ((*zIn++)<<8);                                                  \
19119  c += (*zIn++);                                                      \
19120  if( c>=0xD800 && c<0xE000 && TERM ){                                \
19121    int c2 = ((*zIn++)<<8);                                           \
19122    c2 += (*zIn++);                                                   \
19123    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19124  }                                                                   \
19125}
19126
19127/*
19128** Translate a single UTF-8 character.  Return the unicode value.
19129**
19130** During translation, assume that the byte that zTerm points
19131** is a 0x00.
19132**
19133** Write a pointer to the next unread byte back into *pzNext.
19134**
19135** Notes On Invalid UTF-8:
19136**
19137**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19138**     be encoded as a multi-byte character.  Any multi-byte character that
19139**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19140**
19141**  *  This routine never allows a UTF16 surrogate value to be encoded.
19142**     If a multi-byte character attempts to encode a value between
19143**     0xd800 and 0xe000 then it is rendered as 0xfffd.
19144**
19145**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19146**     byte of a character are interpreted as single-byte characters
19147**     and rendered as themselves even though they are technically
19148**     invalid characters.
19149**
19150**  *  This routine accepts an infinite number of different UTF8 encodings
19151**     for unicode values 0x80 and greater.  It do not change over-length
19152**     encodings to 0xfffd as some systems recommend.
19153*/
19154#define READ_UTF8(zIn, zTerm, c)                           \
19155  c = *(zIn++);                                            \
19156  if( c>=0xc0 ){                                           \
19157    c = sqlite3Utf8Trans1[c-0xc0];                         \
19158    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19159      c = (c<<6) + (0x3f & *(zIn++));                      \
19160    }                                                      \
19161    if( c<0x80                                             \
19162        || (c&0xFFFFF800)==0xD800                          \
19163        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19164  }
19165SQLITE_PRIVATE int sqlite3Utf8Read(
19166  const unsigned char *zIn,       /* First byte of UTF-8 character */
19167  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19168){
19169  int c;
19170
19171  /* Same as READ_UTF8() above but without the zTerm parameter.
19172  ** For this routine, we assume the UTF8 string is always zero-terminated.
19173  */
19174  c = *(zIn++);
19175  if( c>=0xc0 ){
19176    c = sqlite3Utf8Trans1[c-0xc0];
19177    while( (*zIn & 0xc0)==0x80 ){
19178      c = (c<<6) + (0x3f & *(zIn++));
19179    }
19180    if( c<0x80
19181        || (c&0xFFFFF800)==0xD800
19182        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19183  }
19184  *pzNext = zIn;
19185  return c;
19186}
19187
19188
19189
19190
19191/*
19192** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19193** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19194*/
19195/* #define TRANSLATE_TRACE 1 */
19196
19197#ifndef SQLITE_OMIT_UTF16
19198/*
19199** This routine transforms the internal text encoding used by pMem to
19200** desiredEnc. It is an error if the string is already of the desired
19201** encoding, or if *pMem does not contain a string value.
19202*/
19203SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19204  int len;                    /* Maximum length of output string in bytes */
19205  unsigned char *zOut;                  /* Output buffer */
19206  unsigned char *zIn;                   /* Input iterator */
19207  unsigned char *zTerm;                 /* End of input */
19208  unsigned char *z;                     /* Output iterator */
19209  unsigned int c;
19210
19211  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19212  assert( pMem->flags&MEM_Str );
19213  assert( pMem->enc!=desiredEnc );
19214  assert( pMem->enc!=0 );
19215  assert( pMem->n>=0 );
19216
19217#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19218  {
19219    char zBuf[100];
19220    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19221    fprintf(stderr, "INPUT:  %s\n", zBuf);
19222  }
19223#endif
19224
19225  /* If the translation is between UTF-16 little and big endian, then
19226  ** all that is required is to swap the byte order. This case is handled
19227  ** differently from the others.
19228  */
19229  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19230    u8 temp;
19231    int rc;
19232    rc = sqlite3VdbeMemMakeWriteable(pMem);
19233    if( rc!=SQLITE_OK ){
19234      assert( rc==SQLITE_NOMEM );
19235      return SQLITE_NOMEM;
19236    }
19237    zIn = (u8*)pMem->z;
19238    zTerm = &zIn[pMem->n&~1];
19239    while( zIn<zTerm ){
19240      temp = *zIn;
19241      *zIn = *(zIn+1);
19242      zIn++;
19243      *zIn++ = temp;
19244    }
19245    pMem->enc = desiredEnc;
19246    goto translate_out;
19247  }
19248
19249  /* Set len to the maximum number of bytes required in the output buffer. */
19250  if( desiredEnc==SQLITE_UTF8 ){
19251    /* When converting from UTF-16, the maximum growth results from
19252    ** translating a 2-byte character to a 4-byte UTF-8 character.
19253    ** A single byte is required for the output string
19254    ** nul-terminator.
19255    */
19256    pMem->n &= ~1;
19257    len = pMem->n * 2 + 1;
19258  }else{
19259    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19260    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19261    ** character. Two bytes are required in the output buffer for the
19262    ** nul-terminator.
19263    */
19264    len = pMem->n * 2 + 2;
19265  }
19266
19267  /* Set zIn to point at the start of the input buffer and zTerm to point 1
19268  ** byte past the end.
19269  **
19270  ** Variable zOut is set to point at the output buffer, space obtained
19271  ** from sqlite3_malloc().
19272  */
19273  zIn = (u8*)pMem->z;
19274  zTerm = &zIn[pMem->n];
19275  zOut = sqlite3DbMallocRaw(pMem->db, len);
19276  if( !zOut ){
19277    return SQLITE_NOMEM;
19278  }
19279  z = zOut;
19280
19281  if( pMem->enc==SQLITE_UTF8 ){
19282    if( desiredEnc==SQLITE_UTF16LE ){
19283      /* UTF-8 -> UTF-16 Little-endian */
19284      while( zIn<zTerm ){
19285        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19286        READ_UTF8(zIn, zTerm, c);
19287        WRITE_UTF16LE(z, c);
19288      }
19289    }else{
19290      assert( desiredEnc==SQLITE_UTF16BE );
19291      /* UTF-8 -> UTF-16 Big-endian */
19292      while( zIn<zTerm ){
19293        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19294        READ_UTF8(zIn, zTerm, c);
19295        WRITE_UTF16BE(z, c);
19296      }
19297    }
19298    pMem->n = (int)(z - zOut);
19299    *z++ = 0;
19300  }else{
19301    assert( desiredEnc==SQLITE_UTF8 );
19302    if( pMem->enc==SQLITE_UTF16LE ){
19303      /* UTF-16 Little-endian -> UTF-8 */
19304      while( zIn<zTerm ){
19305        READ_UTF16LE(zIn, zIn<zTerm, c);
19306        WRITE_UTF8(z, c);
19307      }
19308    }else{
19309      /* UTF-16 Big-endian -> UTF-8 */
19310      while( zIn<zTerm ){
19311        READ_UTF16BE(zIn, zIn<zTerm, c);
19312        WRITE_UTF8(z, c);
19313      }
19314    }
19315    pMem->n = (int)(z - zOut);
19316  }
19317  *z = 0;
19318  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19319
19320  sqlite3VdbeMemRelease(pMem);
19321  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19322  pMem->enc = desiredEnc;
19323  pMem->flags |= (MEM_Term|MEM_Dyn);
19324  pMem->z = (char*)zOut;
19325  pMem->zMalloc = pMem->z;
19326
19327translate_out:
19328#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19329  {
19330    char zBuf[100];
19331    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19332    fprintf(stderr, "OUTPUT: %s\n", zBuf);
19333  }
19334#endif
19335  return SQLITE_OK;
19336}
19337
19338/*
19339** This routine checks for a byte-order mark at the beginning of the
19340** UTF-16 string stored in *pMem. If one is present, it is removed and
19341** the encoding of the Mem adjusted. This routine does not do any
19342** byte-swapping, it just sets Mem.enc appropriately.
19343**
19344** The allocation (static, dynamic etc.) and encoding of the Mem may be
19345** changed by this function.
19346*/
19347SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19348  int rc = SQLITE_OK;
19349  u8 bom = 0;
19350
19351  assert( pMem->n>=0 );
19352  if( pMem->n>1 ){
19353    u8 b1 = *(u8 *)pMem->z;
19354    u8 b2 = *(((u8 *)pMem->z) + 1);
19355    if( b1==0xFE && b2==0xFF ){
19356      bom = SQLITE_UTF16BE;
19357    }
19358    if( b1==0xFF && b2==0xFE ){
19359      bom = SQLITE_UTF16LE;
19360    }
19361  }
19362
19363  if( bom ){
19364    rc = sqlite3VdbeMemMakeWriteable(pMem);
19365    if( rc==SQLITE_OK ){
19366      pMem->n -= 2;
19367      memmove(pMem->z, &pMem->z[2], pMem->n);
19368      pMem->z[pMem->n] = '\0';
19369      pMem->z[pMem->n+1] = '\0';
19370      pMem->flags |= MEM_Term;
19371      pMem->enc = bom;
19372    }
19373  }
19374  return rc;
19375}
19376#endif /* SQLITE_OMIT_UTF16 */
19377
19378/*
19379** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19380** return the number of unicode characters in pZ up to (but not including)
19381** the first 0x00 byte. If nByte is not less than zero, return the
19382** number of unicode characters in the first nByte of pZ (or up to
19383** the first 0x00, whichever comes first).
19384*/
19385SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19386  int r = 0;
19387  const u8 *z = (const u8*)zIn;
19388  const u8 *zTerm;
19389  if( nByte>=0 ){
19390    zTerm = &z[nByte];
19391  }else{
19392    zTerm = (const u8*)(-1);
19393  }
19394  assert( z<=zTerm );
19395  while( *z!=0 && z<zTerm ){
19396    SQLITE_SKIP_UTF8(z);
19397    r++;
19398  }
19399  return r;
19400}
19401
19402/* This test function is not currently used by the automated test-suite.
19403** Hence it is only available in debug builds.
19404*/
19405#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19406/*
19407** Translate UTF-8 to UTF-8.
19408**
19409** This has the effect of making sure that the string is well-formed
19410** UTF-8.  Miscoded characters are removed.
19411**
19412** The translation is done in-place (since it is impossible for the
19413** correct UTF-8 encoding to be longer than a malformed encoding).
19414*/
19415SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19416  unsigned char *zOut = zIn;
19417  unsigned char *zStart = zIn;
19418  u32 c;
19419
19420  while( zIn[0] ){
19421    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19422    if( c!=0xfffd ){
19423      WRITE_UTF8(zOut, c);
19424    }
19425  }
19426  *zOut = 0;
19427  return (int)(zOut - zStart);
19428}
19429#endif
19430
19431#ifndef SQLITE_OMIT_UTF16
19432/*
19433** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19434** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19435** be freed by the calling function.
19436**
19437** NULL is returned if there is an allocation error.
19438*/
19439SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19440  Mem m;
19441  memset(&m, 0, sizeof(m));
19442  m.db = db;
19443  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19444  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19445  if( db->mallocFailed ){
19446    sqlite3VdbeMemRelease(&m);
19447    m.z = 0;
19448  }
19449  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19450  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19451  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19452  assert( m.z || db->mallocFailed );
19453  return m.z;
19454}
19455
19456/*
19457** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19458** enc. A pointer to the new string is returned, and the value of *pnOut
19459** is set to the length of the returned string in bytes. The call should
19460** arrange to call sqlite3DbFree() on the returned pointer when it is
19461** no longer required.
19462**
19463** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19464** flag set.
19465*/
19466#ifdef SQLITE_ENABLE_STAT2
19467SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19468  Mem m;
19469  memset(&m, 0, sizeof(m));
19470  m.db = db;
19471  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19472  if( sqlite3VdbeMemTranslate(&m, enc) ){
19473    assert( db->mallocFailed );
19474    return 0;
19475  }
19476  assert( m.z==m.zMalloc );
19477  *pnOut = m.n;
19478  return m.z;
19479}
19480#endif
19481
19482/*
19483** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19484** Return the number of bytes in the first nChar unicode characters
19485** in pZ.  nChar must be non-negative.
19486*/
19487SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19488  int c;
19489  unsigned char const *z = zIn;
19490  int n = 0;
19491
19492  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19493    while( n<nChar ){
19494      READ_UTF16BE(z, 1, c);
19495      n++;
19496    }
19497  }else{
19498    while( n<nChar ){
19499      READ_UTF16LE(z, 1, c);
19500      n++;
19501    }
19502  }
19503  return (int)(z-(unsigned char const *)zIn);
19504}
19505
19506#if defined(SQLITE_TEST)
19507/*
19508** This routine is called from the TCL test function "translate_selftest".
19509** It checks that the primitives for serializing and deserializing
19510** characters in each encoding are inverses of each other.
19511*/
19512SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19513  unsigned int i, t;
19514  unsigned char zBuf[20];
19515  unsigned char *z;
19516  int n;
19517  unsigned int c;
19518
19519  for(i=0; i<0x00110000; i++){
19520    z = zBuf;
19521    WRITE_UTF8(z, i);
19522    n = (int)(z-zBuf);
19523    assert( n>0 && n<=4 );
19524    z[0] = 0;
19525    z = zBuf;
19526    c = sqlite3Utf8Read(z, (const u8**)&z);
19527    t = i;
19528    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19529    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19530    assert( c==t );
19531    assert( (z-zBuf)==n );
19532  }
19533  for(i=0; i<0x00110000; i++){
19534    if( i>=0xD800 && i<0xE000 ) continue;
19535    z = zBuf;
19536    WRITE_UTF16LE(z, i);
19537    n = (int)(z-zBuf);
19538    assert( n>0 && n<=4 );
19539    z[0] = 0;
19540    z = zBuf;
19541    READ_UTF16LE(z, 1, c);
19542    assert( c==i );
19543    assert( (z-zBuf)==n );
19544  }
19545  for(i=0; i<0x00110000; i++){
19546    if( i>=0xD800 && i<0xE000 ) continue;
19547    z = zBuf;
19548    WRITE_UTF16BE(z, i);
19549    n = (int)(z-zBuf);
19550    assert( n>0 && n<=4 );
19551    z[0] = 0;
19552    z = zBuf;
19553    READ_UTF16BE(z, 1, c);
19554    assert( c==i );
19555    assert( (z-zBuf)==n );
19556  }
19557}
19558#endif /* SQLITE_TEST */
19559#endif /* SQLITE_OMIT_UTF16 */
19560
19561/************** End of utf.c *************************************************/
19562/************** Begin file util.c ********************************************/
19563/*
19564** 2001 September 15
19565**
19566** The author disclaims copyright to this source code.  In place of
19567** a legal notice, here is a blessing:
19568**
19569**    May you do good and not evil.
19570**    May you find forgiveness for yourself and forgive others.
19571**    May you share freely, never taking more than you give.
19572**
19573*************************************************************************
19574** Utility functions used throughout sqlite.
19575**
19576** This file contains functions for allocating memory, comparing
19577** strings, and stuff like that.
19578**
19579*/
19580#ifdef SQLITE_HAVE_ISNAN
19581# include <math.h>
19582#endif
19583
19584/*
19585** Routine needed to support the testcase() macro.
19586*/
19587#ifdef SQLITE_COVERAGE_TEST
19588SQLITE_PRIVATE void sqlite3Coverage(int x){
19589  static int dummy = 0;
19590  dummy += x;
19591}
19592#endif
19593
19594#ifndef SQLITE_OMIT_FLOATING_POINT
19595/*
19596** Return true if the floating point value is Not a Number (NaN).
19597**
19598** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
19599** Otherwise, we have our own implementation that works on most systems.
19600*/
19601SQLITE_PRIVATE int sqlite3IsNaN(double x){
19602  int rc;   /* The value return */
19603#if !defined(SQLITE_HAVE_ISNAN)
19604  /*
19605  ** Systems that support the isnan() library function should probably
19606  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
19607  ** found that many systems do not have a working isnan() function so
19608  ** this implementation is provided as an alternative.
19609  **
19610  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
19611  ** On the other hand, the use of -ffast-math comes with the following
19612  ** warning:
19613  **
19614  **      This option [-ffast-math] should never be turned on by any
19615  **      -O option since it can result in incorrect output for programs
19616  **      which depend on an exact implementation of IEEE or ISO
19617  **      rules/specifications for math functions.
19618  **
19619  ** Under MSVC, this NaN test may fail if compiled with a floating-
19620  ** point precision mode other than /fp:precise.  From the MSDN
19621  ** documentation:
19622  **
19623  **      The compiler [with /fp:precise] will properly handle comparisons
19624  **      involving NaN. For example, x != x evaluates to true if x is NaN
19625  **      ...
19626  */
19627#ifdef __FAST_MATH__
19628# error SQLite will not work correctly with the -ffast-math option of GCC.
19629#endif
19630  volatile double y = x;
19631  volatile double z = y;
19632  rc = (y!=z);
19633#else  /* if defined(SQLITE_HAVE_ISNAN) */
19634  rc = isnan(x);
19635#endif /* SQLITE_HAVE_ISNAN */
19636  testcase( rc );
19637  return rc;
19638}
19639#endif /* SQLITE_OMIT_FLOATING_POINT */
19640
19641/*
19642** Compute a string length that is limited to what can be stored in
19643** lower 30 bits of a 32-bit signed integer.
19644**
19645** The value returned will never be negative.  Nor will it ever be greater
19646** than the actual length of the string.  For very long strings (greater
19647** than 1GiB) the value returned might be less than the true string length.
19648*/
19649SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19650  const char *z2 = z;
19651  if( z==0 ) return 0;
19652  while( *z2 ){ z2++; }
19653  return 0x3fffffff & (int)(z2 - z);
19654}
19655
19656/*
19657** Set the most recent error code and error string for the sqlite
19658** handle "db". The error code is set to "err_code".
19659**
19660** If it is not NULL, string zFormat specifies the format of the
19661** error string in the style of the printf functions: The following
19662** format characters are allowed:
19663**
19664**      %s      Insert a string
19665**      %z      A string that should be freed after use
19666**      %d      Insert an integer
19667**      %T      Insert a token
19668**      %S      Insert the first element of a SrcList
19669**
19670** zFormat and any string tokens that follow it are assumed to be
19671** encoded in UTF-8.
19672**
19673** To clear the most recent error for sqlite handle "db", sqlite3Error
19674** should be called with err_code set to SQLITE_OK and zFormat set
19675** to NULL.
19676*/
19677SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19678  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19679    db->errCode = err_code;
19680    if( zFormat ){
19681      char *z;
19682      va_list ap;
19683      va_start(ap, zFormat);
19684      z = sqlite3VMPrintf(db, zFormat, ap);
19685      va_end(ap);
19686      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19687    }else{
19688      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19689    }
19690  }
19691}
19692
19693/*
19694** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19695** The following formatting characters are allowed:
19696**
19697**      %s      Insert a string
19698**      %z      A string that should be freed after use
19699**      %d      Insert an integer
19700**      %T      Insert a token
19701**      %S      Insert the first element of a SrcList
19702**
19703** This function should be used to report any error that occurs whilst
19704** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19705** last thing the sqlite3_prepare() function does is copy the error
19706** stored by this function into the database handle using sqlite3Error().
19707** Function sqlite3Error() should be used during statement execution
19708** (sqlite3_step() etc.).
19709*/
19710SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
19711  char *zMsg;
19712  va_list ap;
19713  sqlite3 *db = pParse->db;
19714  va_start(ap, zFormat);
19715  zMsg = sqlite3VMPrintf(db, zFormat, ap);
19716  va_end(ap);
19717  if( db->suppressErr ){
19718    sqlite3DbFree(db, zMsg);
19719  }else{
19720    pParse->nErr++;
19721    sqlite3DbFree(db, pParse->zErrMsg);
19722    pParse->zErrMsg = zMsg;
19723    pParse->rc = SQLITE_ERROR;
19724  }
19725}
19726
19727/*
19728** Convert an SQL-style quoted string into a normal string by removing
19729** the quote characters.  The conversion is done in-place.  If the
19730** input does not begin with a quote character, then this routine
19731** is a no-op.
19732**
19733** The input string must be zero-terminated.  A new zero-terminator
19734** is added to the dequoted string.
19735**
19736** The return value is -1 if no dequoting occurs or the length of the
19737** dequoted string, exclusive of the zero terminator, if dequoting does
19738** occur.
19739**
19740** 2002-Feb-14: This routine is extended to remove MS-Access style
19741** brackets from around identifers.  For example:  "[a-b-c]" becomes
19742** "a-b-c".
19743*/
19744SQLITE_PRIVATE int sqlite3Dequote(char *z){
19745  char quote;
19746  int i, j;
19747  if( z==0 ) return -1;
19748  quote = z[0];
19749  switch( quote ){
19750    case '\'':  break;
19751    case '"':   break;
19752    case '`':   break;                /* For MySQL compatibility */
19753    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
19754    default:    return -1;
19755  }
19756  for(i=1, j=0; ALWAYS(z[i]); i++){
19757    if( z[i]==quote ){
19758      if( z[i+1]==quote ){
19759        z[j++] = quote;
19760        i++;
19761      }else{
19762        break;
19763      }
19764    }else{
19765      z[j++] = z[i];
19766    }
19767  }
19768  z[j] = 0;
19769  return j;
19770}
19771
19772/* Convenient short-hand */
19773#define UpperToLower sqlite3UpperToLower
19774
19775/*
19776** Some systems have stricmp().  Others have strcasecmp().  Because
19777** there is no consistency, we will define our own.
19778*/
19779SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19780  register unsigned char *a, *b;
19781  a = (unsigned char *)zLeft;
19782  b = (unsigned char *)zRight;
19783  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19784  return UpperToLower[*a] - UpperToLower[*b];
19785}
19786SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
19787  register unsigned char *a, *b;
19788  a = (unsigned char *)zLeft;
19789  b = (unsigned char *)zRight;
19790  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19791  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19792}
19793
19794/*
19795** Return TRUE if z is a pure numeric string.  Return FALSE and leave
19796** *realnum unchanged if the string contains any character which is not
19797** part of a number.
19798**
19799** If the string is pure numeric, set *realnum to TRUE if the string
19800** contains the '.' character or an "E+000" style exponentiation suffix.
19801** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
19802** false does not mean that the number can be successfully converted into
19803** an integer - it might be too big.
19804**
19805** An empty string is considered non-numeric.
19806*/
19807SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19808  int incr = (enc==SQLITE_UTF8?1:2);
19809  if( enc==SQLITE_UTF16BE ) z++;
19810  if( *z=='-' || *z=='+' ) z += incr;
19811  if( !sqlite3Isdigit(*z) ){
19812    return 0;
19813  }
19814  z += incr;
19815  *realnum = 0;
19816  while( sqlite3Isdigit(*z) ){ z += incr; }
19817#ifndef SQLITE_OMIT_FLOATING_POINT
19818  if( *z=='.' ){
19819    z += incr;
19820    if( !sqlite3Isdigit(*z) ) return 0;
19821    while( sqlite3Isdigit(*z) ){ z += incr; }
19822    *realnum = 1;
19823  }
19824  if( *z=='e' || *z=='E' ){
19825    z += incr;
19826    if( *z=='+' || *z=='-' ) z += incr;
19827    if( !sqlite3Isdigit(*z) ) return 0;
19828    while( sqlite3Isdigit(*z) ){ z += incr; }
19829    *realnum = 1;
19830  }
19831#endif
19832  return *z==0;
19833}
19834
19835/*
19836** The string z[] is an ASCII representation of a real number.
19837** Convert this string to a double.
19838**
19839** This routine assumes that z[] really is a valid number.  If it
19840** is not, the result is undefined.
19841**
19842** This routine is used instead of the library atof() function because
19843** the library atof() might want to use "," as the decimal point instead
19844** of "." depending on how locale is set.  But that would cause problems
19845** for SQL.  So this routine always uses "." regardless of locale.
19846*/
19847SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19848#ifndef SQLITE_OMIT_FLOATING_POINT
19849  const char *zBegin = z;
19850  /* sign * significand * (10 ^ (esign * exponent)) */
19851  int sign = 1;   /* sign of significand */
19852  i64 s = 0;      /* significand */
19853  int d = 0;      /* adjust exponent for shifting decimal point */
19854  int esign = 1;  /* sign of exponent */
19855  int e = 0;      /* exponent */
19856  double result;
19857  int nDigits = 0;
19858
19859  /* skip leading spaces */
19860  while( sqlite3Isspace(*z) ) z++;
19861  /* get sign of significand */
19862  if( *z=='-' ){
19863    sign = -1;
19864    z++;
19865  }else if( *z=='+' ){
19866    z++;
19867  }
19868  /* skip leading zeroes */
19869  while( z[0]=='0' ) z++, nDigits++;
19870
19871  /* copy max significant digits to significand */
19872  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19873    s = s*10 + (*z - '0');
19874    z++, nDigits++;
19875  }
19876  /* skip non-significant significand digits
19877  ** (increase exponent by d to shift decimal left) */
19878  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
19879
19880  /* if decimal point is present */
19881  if( *z=='.' ){
19882    z++;
19883    /* copy digits from after decimal to significand
19884    ** (decrease exponent by d to shift decimal right) */
19885    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19886      s = s*10 + (*z - '0');
19887      z++, nDigits++, d--;
19888    }
19889    /* skip non-significant digits */
19890    while( sqlite3Isdigit(*z) ) z++, nDigits++;
19891  }
19892
19893  /* if exponent is present */
19894  if( *z=='e' || *z=='E' ){
19895    z++;
19896    /* get sign of exponent */
19897    if( *z=='-' ){
19898      esign = -1;
19899      z++;
19900    }else if( *z=='+' ){
19901      z++;
19902    }
19903    /* copy digits to exponent */
19904    while( sqlite3Isdigit(*z) ){
19905      e = e*10 + (*z - '0');
19906      z++;
19907    }
19908  }
19909
19910  /* adjust exponent by d, and update sign */
19911  e = (e*esign) + d;
19912  if( e<0 ) {
19913    esign = -1;
19914    e *= -1;
19915  } else {
19916    esign = 1;
19917  }
19918
19919  /* if 0 significand */
19920  if( !s ) {
19921    /* In the IEEE 754 standard, zero is signed.
19922    ** Add the sign if we've seen at least one digit */
19923    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
19924  } else {
19925    /* attempt to reduce exponent */
19926    if( esign>0 ){
19927      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
19928    }else{
19929      while( !(s%10) && e>0 ) e--,s/=10;
19930    }
19931
19932    /* adjust the sign of significand */
19933    s = sign<0 ? -s : s;
19934
19935    /* if exponent, scale significand as appropriate
19936    ** and store in result. */
19937    if( e ){
19938      double scale = 1.0;
19939      /* attempt to handle extremely small/large numbers better */
19940      if( e>307 && e<342 ){
19941        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
19942        if( esign<0 ){
19943          result = s / scale;
19944          result /= 1.0e+308;
19945        }else{
19946          result = s * scale;
19947          result *= 1.0e+308;
19948        }
19949      }else{
19950        /* 1.0e+22 is the largest power of 10 than can be
19951        ** represented exactly. */
19952        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
19953        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
19954        if( esign<0 ){
19955          result = s / scale;
19956        }else{
19957          result = s * scale;
19958        }
19959      }
19960    } else {
19961      result = (double)s;
19962    }
19963  }
19964
19965  /* store the result */
19966  *pResult = result;
19967
19968  /* return number of characters used */
19969  return (int)(z - zBegin);
19970#else
19971  return sqlite3Atoi64(z, pResult);
19972#endif /* SQLITE_OMIT_FLOATING_POINT */
19973}
19974
19975/*
19976** Compare the 19-character string zNum against the text representation
19977** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19978** if zNum is less than, equal to, or greater than the string.
19979**
19980** Unlike memcmp() this routine is guaranteed to return the difference
19981** in the values of the last digit if the only difference is in the
19982** last digit.  So, for example,
19983**
19984**      compare2pow63("9223372036854775800")
19985**
19986** will return -8.
19987*/
19988static int compare2pow63(const char *zNum){
19989  int c;
19990  c = memcmp(zNum,"922337203685477580",18)*10;
19991  if( c==0 ){
19992    c = zNum[18] - '8';
19993    testcase( c==(-1) );
19994    testcase( c==0 );
19995    testcase( c==(+1) );
19996  }
19997  return c;
19998}
19999
20000
20001/*
20002** Return TRUE if zNum is a 64-bit signed integer and write
20003** the value of the integer into *pNum.  If zNum is not an integer
20004** or is an integer that is too large to be expressed with 64 bits,
20005** then return false.
20006**
20007** When this routine was originally written it dealt with only
20008** 32-bit numbers.  At that time, it was much faster than the
20009** atoi() library routine in RedHat 7.2.
20010*/
20011SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
20012  i64 v = 0;
20013  int neg;
20014  int i, c;
20015  const char *zStart;
20016  while( sqlite3Isspace(*zNum) ) zNum++;
20017  if( *zNum=='-' ){
20018    neg = 1;
20019    zNum++;
20020  }else if( *zNum=='+' ){
20021    neg = 0;
20022    zNum++;
20023  }else{
20024    neg = 0;
20025  }
20026  zStart = zNum;
20027  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
20028  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
20029    v = v*10 + c - '0';
20030  }
20031  *pNum = neg ? -v : v;
20032  testcase( i==18 );
20033  testcase( i==19 );
20034  testcase( i==20 );
20035  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
20036    /* zNum is empty or contains non-numeric text or is longer
20037    ** than 19 digits (thus guaranting that it is too large) */
20038    return 0;
20039  }else if( i<19 ){
20040    /* Less than 19 digits, so we know that it fits in 64 bits */
20041    return 1;
20042  }else{
20043    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
20044    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
20045    ** is 2^63. */
20046    return compare2pow63(zNum)<neg;
20047  }
20048}
20049
20050/*
20051** The string zNum represents an unsigned integer.  The zNum string
20052** consists of one or more digit characters and is terminated by
20053** a zero character.  Any stray characters in zNum result in undefined
20054** behavior.
20055**
20056** If the unsigned integer that zNum represents will fit in a
20057** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
20058**
20059** If the negFlag parameter is true, that means that zNum really represents
20060** a negative number.  (The leading "-" is omitted from zNum.)  This
20061** parameter is needed to determine a boundary case.  A string
20062** of "9223373036854775808" returns false if negFlag is false or true
20063** if negFlag is true.
20064**
20065** Leading zeros are ignored.
20066*/
20067SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
20068  int i;
20069  int neg = 0;
20070
20071  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
20072
20073  if( negFlag ) neg = 1-neg;
20074  while( *zNum=='0' ){
20075    zNum++;   /* Skip leading zeros.  Ticket #2454 */
20076  }
20077  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
20078  testcase( i==18 );
20079  testcase( i==19 );
20080  testcase( i==20 );
20081  if( i<19 ){
20082    /* Guaranteed to fit if less than 19 digits */
20083    return 1;
20084  }else if( i>19 ){
20085    /* Guaranteed to be too big if greater than 19 digits */
20086    return 0;
20087  }else{
20088    /* Compare against 2^63. */
20089    return compare2pow63(zNum)<neg;
20090  }
20091}
20092
20093/*
20094** If zNum represents an integer that will fit in 32-bits, then set
20095** *pValue to that integer and return true.  Otherwise return false.
20096**
20097** Any non-numeric characters that following zNum are ignored.
20098** This is different from sqlite3Atoi64() which requires the
20099** input number to be zero-terminated.
20100*/
20101SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20102  sqlite_int64 v = 0;
20103  int i, c;
20104  int neg = 0;
20105  if( zNum[0]=='-' ){
20106    neg = 1;
20107    zNum++;
20108  }else if( zNum[0]=='+' ){
20109    zNum++;
20110  }
20111  while( zNum[0]=='0' ) zNum++;
20112  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20113    v = v*10 + c;
20114  }
20115
20116  /* The longest decimal representation of a 32 bit integer is 10 digits:
20117  **
20118  **             1234567890
20119  **     2^31 -> 2147483648
20120  */
20121  testcase( i==10 );
20122  if( i>10 ){
20123    return 0;
20124  }
20125  testcase( v-neg==2147483647 );
20126  if( v-neg>2147483647 ){
20127    return 0;
20128  }
20129  if( neg ){
20130    v = -v;
20131  }
20132  *pValue = (int)v;
20133  return 1;
20134}
20135
20136/*
20137** The variable-length integer encoding is as follows:
20138**
20139** KEY:
20140**         A = 0xxxxxxx    7 bits of data and one flag bit
20141**         B = 1xxxxxxx    7 bits of data and one flag bit
20142**         C = xxxxxxxx    8 bits of data
20143**
20144**  7 bits - A
20145** 14 bits - BA
20146** 21 bits - BBA
20147** 28 bits - BBBA
20148** 35 bits - BBBBA
20149** 42 bits - BBBBBA
20150** 49 bits - BBBBBBA
20151** 56 bits - BBBBBBBA
20152** 64 bits - BBBBBBBBC
20153*/
20154
20155/*
20156** Write a 64-bit variable-length integer to memory starting at p[0].
20157** The length of data write will be between 1 and 9 bytes.  The number
20158** of bytes written is returned.
20159**
20160** A variable-length integer consists of the lower 7 bits of each byte
20161** for all bytes that have the 8th bit set and one byte with the 8th
20162** bit clear.  Except, if we get to the 9th byte, it stores the full
20163** 8 bits and is the last byte.
20164*/
20165SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20166  int i, j, n;
20167  u8 buf[10];
20168  if( v & (((u64)0xff000000)<<32) ){
20169    p[8] = (u8)v;
20170    v >>= 8;
20171    for(i=7; i>=0; i--){
20172      p[i] = (u8)((v & 0x7f) | 0x80);
20173      v >>= 7;
20174    }
20175    return 9;
20176  }
20177  n = 0;
20178  do{
20179    buf[n++] = (u8)((v & 0x7f) | 0x80);
20180    v >>= 7;
20181  }while( v!=0 );
20182  buf[0] &= 0x7f;
20183  assert( n<=9 );
20184  for(i=0, j=n-1; j>=0; j--, i++){
20185    p[i] = buf[j];
20186  }
20187  return n;
20188}
20189
20190/*
20191** This routine is a faster version of sqlite3PutVarint() that only
20192** works for 32-bit positive integers and which is optimized for
20193** the common case of small integers.  A MACRO version, putVarint32,
20194** is provided which inlines the single-byte case.  All code should use
20195** the MACRO version as this function assumes the single-byte case has
20196** already been handled.
20197*/
20198SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20199#ifndef putVarint32
20200  if( (v & ~0x7f)==0 ){
20201    p[0] = v;
20202    return 1;
20203  }
20204#endif
20205  if( (v & ~0x3fff)==0 ){
20206    p[0] = (u8)((v>>7) | 0x80);
20207    p[1] = (u8)(v & 0x7f);
20208    return 2;
20209  }
20210  return sqlite3PutVarint(p, v);
20211}
20212
20213/*
20214** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20215** are defined here rather than simply putting the constant expressions
20216** inline in order to work around bugs in the RVT compiler.
20217**
20218** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20219**
20220** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20221*/
20222#define SLOT_2_0     0x001fc07f
20223#define SLOT_4_2_0   0xf01fc07f
20224
20225
20226/*
20227** Read a 64-bit variable-length integer from memory starting at p[0].
20228** Return the number of bytes read.  The value is stored in *v.
20229*/
20230SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20231  u32 a,b,s;
20232
20233  a = *p;
20234  /* a: p0 (unmasked) */
20235  if (!(a&0x80))
20236  {
20237    *v = a;
20238    return 1;
20239  }
20240
20241  p++;
20242  b = *p;
20243  /* b: p1 (unmasked) */
20244  if (!(b&0x80))
20245  {
20246    a &= 0x7f;
20247    a = a<<7;
20248    a |= b;
20249    *v = a;
20250    return 2;
20251  }
20252
20253  /* Verify that constants are precomputed correctly */
20254  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20255  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20256
20257  p++;
20258  a = a<<14;
20259  a |= *p;
20260  /* a: p0<<14 | p2 (unmasked) */
20261  if (!(a&0x80))
20262  {
20263    a &= SLOT_2_0;
20264    b &= 0x7f;
20265    b = b<<7;
20266    a |= b;
20267    *v = a;
20268    return 3;
20269  }
20270
20271  /* CSE1 from below */
20272  a &= SLOT_2_0;
20273  p++;
20274  b = b<<14;
20275  b |= *p;
20276  /* b: p1<<14 | p3 (unmasked) */
20277  if (!(b&0x80))
20278  {
20279    b &= SLOT_2_0;
20280    /* moved CSE1 up */
20281    /* a &= (0x7f<<14)|(0x7f); */
20282    a = a<<7;
20283    a |= b;
20284    *v = a;
20285    return 4;
20286  }
20287
20288  /* a: p0<<14 | p2 (masked) */
20289  /* b: p1<<14 | p3 (unmasked) */
20290  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20291  /* moved CSE1 up */
20292  /* a &= (0x7f<<14)|(0x7f); */
20293  b &= SLOT_2_0;
20294  s = a;
20295  /* s: p0<<14 | p2 (masked) */
20296
20297  p++;
20298  a = a<<14;
20299  a |= *p;
20300  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20301  if (!(a&0x80))
20302  {
20303    /* we can skip these cause they were (effectively) done above in calc'ing s */
20304    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20305    /* b &= (0x7f<<14)|(0x7f); */
20306    b = b<<7;
20307    a |= b;
20308    s = s>>18;
20309    *v = ((u64)s)<<32 | a;
20310    return 5;
20311  }
20312
20313  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20314  s = s<<7;
20315  s |= b;
20316  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20317
20318  p++;
20319  b = b<<14;
20320  b |= *p;
20321  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20322  if (!(b&0x80))
20323  {
20324    /* we can skip this cause it was (effectively) done above in calc'ing s */
20325    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20326    a &= SLOT_2_0;
20327    a = a<<7;
20328    a |= b;
20329    s = s>>18;
20330    *v = ((u64)s)<<32 | a;
20331    return 6;
20332  }
20333
20334  p++;
20335  a = a<<14;
20336  a |= *p;
20337  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20338  if (!(a&0x80))
20339  {
20340    a &= SLOT_4_2_0;
20341    b &= SLOT_2_0;
20342    b = b<<7;
20343    a |= b;
20344    s = s>>11;
20345    *v = ((u64)s)<<32 | a;
20346    return 7;
20347  }
20348
20349  /* CSE2 from below */
20350  a &= SLOT_2_0;
20351  p++;
20352  b = b<<14;
20353  b |= *p;
20354  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20355  if (!(b&0x80))
20356  {
20357    b &= SLOT_4_2_0;
20358    /* moved CSE2 up */
20359    /* a &= (0x7f<<14)|(0x7f); */
20360    a = a<<7;
20361    a |= b;
20362    s = s>>4;
20363    *v = ((u64)s)<<32 | a;
20364    return 8;
20365  }
20366
20367  p++;
20368  a = a<<15;
20369  a |= *p;
20370  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20371
20372  /* moved CSE2 up */
20373  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20374  b &= SLOT_2_0;
20375  b = b<<8;
20376  a |= b;
20377
20378  s = s<<4;
20379  b = p[-4];
20380  b &= 0x7f;
20381  b = b>>3;
20382  s |= b;
20383
20384  *v = ((u64)s)<<32 | a;
20385
20386  return 9;
20387}
20388
20389/*
20390** Read a 32-bit variable-length integer from memory starting at p[0].
20391** Return the number of bytes read.  The value is stored in *v.
20392**
20393** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20394** integer, then set *v to 0xffffffff.
20395**
20396** A MACRO version, getVarint32, is provided which inlines the
20397** single-byte case.  All code should use the MACRO version as
20398** this function assumes the single-byte case has already been handled.
20399*/
20400SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20401  u32 a,b;
20402
20403  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20404  ** by the getVarin32() macro */
20405  a = *p;
20406  /* a: p0 (unmasked) */
20407#ifndef getVarint32
20408  if (!(a&0x80))
20409  {
20410    /* Values between 0 and 127 */
20411    *v = a;
20412    return 1;
20413  }
20414#endif
20415
20416  /* The 2-byte case */
20417  p++;
20418  b = *p;
20419  /* b: p1 (unmasked) */
20420  if (!(b&0x80))
20421  {
20422    /* Values between 128 and 16383 */
20423    a &= 0x7f;
20424    a = a<<7;
20425    *v = a | b;
20426    return 2;
20427  }
20428
20429  /* The 3-byte case */
20430  p++;
20431  a = a<<14;
20432  a |= *p;
20433  /* a: p0<<14 | p2 (unmasked) */
20434  if (!(a&0x80))
20435  {
20436    /* Values between 16384 and 2097151 */
20437    a &= (0x7f<<14)|(0x7f);
20438    b &= 0x7f;
20439    b = b<<7;
20440    *v = a | b;
20441    return 3;
20442  }
20443
20444  /* A 32-bit varint is used to store size information in btrees.
20445  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20446  ** A 3-byte varint is sufficient, for example, to record the size
20447  ** of a 1048569-byte BLOB or string.
20448  **
20449  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20450  ** rare larger cases can be handled by the slower 64-bit varint
20451  ** routine.
20452  */
20453#if 1
20454  {
20455    u64 v64;
20456    u8 n;
20457
20458    p -= 2;
20459    n = sqlite3GetVarint(p, &v64);
20460    assert( n>3 && n<=9 );
20461    if( (v64 & SQLITE_MAX_U32)!=v64 ){
20462      *v = 0xffffffff;
20463    }else{
20464      *v = (u32)v64;
20465    }
20466    return n;
20467  }
20468
20469#else
20470  /* For following code (kept for historical record only) shows an
20471  ** unrolling for the 3- and 4-byte varint cases.  This code is
20472  ** slightly faster, but it is also larger and much harder to test.
20473  */
20474  p++;
20475  b = b<<14;
20476  b |= *p;
20477  /* b: p1<<14 | p3 (unmasked) */
20478  if (!(b&0x80))
20479  {
20480    /* Values between 2097152 and 268435455 */
20481    b &= (0x7f<<14)|(0x7f);
20482    a &= (0x7f<<14)|(0x7f);
20483    a = a<<7;
20484    *v = a | b;
20485    return 4;
20486  }
20487
20488  p++;
20489  a = a<<14;
20490  a |= *p;
20491  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20492  if (!(a&0x80))
20493  {
20494    /* Values  between 268435456 and 34359738367 */
20495    a &= SLOT_4_2_0;
20496    b &= SLOT_4_2_0;
20497    b = b<<7;
20498    *v = a | b;
20499    return 5;
20500  }
20501
20502  /* We can only reach this point when reading a corrupt database
20503  ** file.  In that case we are not in any hurry.  Use the (relatively
20504  ** slow) general-purpose sqlite3GetVarint() routine to extract the
20505  ** value. */
20506  {
20507    u64 v64;
20508    u8 n;
20509
20510    p -= 4;
20511    n = sqlite3GetVarint(p, &v64);
20512    assert( n>5 && n<=9 );
20513    *v = (u32)v64;
20514    return n;
20515  }
20516#endif
20517}
20518
20519/*
20520** Return the number of bytes that will be needed to store the given
20521** 64-bit integer.
20522*/
20523SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20524  int i = 0;
20525  do{
20526    i++;
20527    v >>= 7;
20528  }while( v!=0 && ALWAYS(i<9) );
20529  return i;
20530}
20531
20532
20533/*
20534** Read or write a four-byte big-endian integer value.
20535*/
20536SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20537  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20538}
20539SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20540  p[0] = (u8)(v>>24);
20541  p[1] = (u8)(v>>16);
20542  p[2] = (u8)(v>>8);
20543  p[3] = (u8)v;
20544}
20545
20546
20547
20548#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20549/*
20550** Translate a single byte of Hex into an integer.
20551** This routine only works if h really is a valid hexadecimal
20552** character:  0..9a..fA..F
20553*/
20554static u8 hexToInt(int h){
20555  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
20556#ifdef SQLITE_ASCII
20557  h += 9*(1&(h>>6));
20558#endif
20559#ifdef SQLITE_EBCDIC
20560  h += 9*(1&~(h>>4));
20561#endif
20562  return (u8)(h & 0xf);
20563}
20564#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20565
20566#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20567/*
20568** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
20569** value.  Return a pointer to its binary value.  Space to hold the
20570** binary value has been obtained from malloc and must be freed by
20571** the calling routine.
20572*/
20573SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
20574  char *zBlob;
20575  int i;
20576
20577  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
20578  n--;
20579  if( zBlob ){
20580    for(i=0; i<n; i+=2){
20581      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
20582    }
20583    zBlob[i/2] = 0;
20584  }
20585  return zBlob;
20586}
20587#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20588
20589/*
20590** Log an error that is an API call on a connection pointer that should
20591** not have been used.  The "type" of connection pointer is given as the
20592** argument.  The zType is a word like "NULL" or "closed" or "invalid".
20593*/
20594static void logBadConnection(const char *zType){
20595  sqlite3_log(SQLITE_MISUSE,
20596     "API call with %s database connection pointer",
20597     zType
20598  );
20599}
20600
20601/*
20602** Check to make sure we have a valid db pointer.  This test is not
20603** foolproof but it does provide some measure of protection against
20604** misuse of the interface such as passing in db pointers that are
20605** NULL or which have been previously closed.  If this routine returns
20606** 1 it means that the db pointer is valid and 0 if it should not be
20607** dereferenced for any reason.  The calling function should invoke
20608** SQLITE_MISUSE immediately.
20609**
20610** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20611** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20612** open properly and is not fit for general use but which can be
20613** used as an argument to sqlite3_errmsg() or sqlite3_close().
20614*/
20615SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20616  u32 magic;
20617  if( db==0 ){
20618    logBadConnection("NULL");
20619    return 0;
20620  }
20621  magic = db->magic;
20622  if( magic!=SQLITE_MAGIC_OPEN ){
20623    if( sqlite3SafetyCheckSickOrOk(db) ){
20624      testcase( sqlite3GlobalConfig.xLog!=0 );
20625      logBadConnection("unopened");
20626    }
20627    return 0;
20628  }else{
20629    return 1;
20630  }
20631}
20632SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20633  u32 magic;
20634  magic = db->magic;
20635  if( magic!=SQLITE_MAGIC_SICK &&
20636      magic!=SQLITE_MAGIC_OPEN &&
20637      magic!=SQLITE_MAGIC_BUSY ){
20638    testcase( sqlite3GlobalConfig.xLog!=0 );
20639    logBadConnection("invalid");
20640    return 0;
20641  }else{
20642    return 1;
20643  }
20644}
20645
20646/************** End of util.c ************************************************/
20647/************** Begin file hash.c ********************************************/
20648/*
20649** 2001 September 22
20650**
20651** The author disclaims copyright to this source code.  In place of
20652** a legal notice, here is a blessing:
20653**
20654**    May you do good and not evil.
20655**    May you find forgiveness for yourself and forgive others.
20656**    May you share freely, never taking more than you give.
20657**
20658*************************************************************************
20659** This is the implementation of generic hash-tables
20660** used in SQLite.
20661*/
20662
20663/* Turn bulk memory into a hash table object by initializing the
20664** fields of the Hash structure.
20665**
20666** "pNew" is a pointer to the hash table that is to be initialized.
20667*/
20668SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
20669  assert( pNew!=0 );
20670  pNew->first = 0;
20671  pNew->count = 0;
20672  pNew->htsize = 0;
20673  pNew->ht = 0;
20674}
20675
20676/* Remove all entries from a hash table.  Reclaim all memory.
20677** Call this routine to delete a hash table or to reset a hash table
20678** to the empty state.
20679*/
20680SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20681  HashElem *elem;         /* For looping over all elements of the table */
20682
20683  assert( pH!=0 );
20684  elem = pH->first;
20685  pH->first = 0;
20686  sqlite3_free(pH->ht);
20687  pH->ht = 0;
20688  pH->htsize = 0;
20689  while( elem ){
20690    HashElem *next_elem = elem->next;
20691    sqlite3_free(elem);
20692    elem = next_elem;
20693  }
20694  pH->count = 0;
20695}
20696
20697/*
20698** The hashing function.
20699*/
20700static unsigned int strHash(const char *z, int nKey){
20701  int h = 0;
20702  assert( nKey>=0 );
20703  while( nKey > 0  ){
20704    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20705    nKey--;
20706  }
20707  return h;
20708}
20709
20710
20711/* Link pNew element into the hash table pH.  If pEntry!=0 then also
20712** insert pNew into the pEntry hash bucket.
20713*/
20714static void insertElement(
20715  Hash *pH,              /* The complete hash table */
20716  struct _ht *pEntry,    /* The entry into which pNew is inserted */
20717  HashElem *pNew         /* The element to be inserted */
20718){
20719  HashElem *pHead;       /* First element already in pEntry */
20720  if( pEntry ){
20721    pHead = pEntry->count ? pEntry->chain : 0;
20722    pEntry->count++;
20723    pEntry->chain = pNew;
20724  }else{
20725    pHead = 0;
20726  }
20727  if( pHead ){
20728    pNew->next = pHead;
20729    pNew->prev = pHead->prev;
20730    if( pHead->prev ){ pHead->prev->next = pNew; }
20731    else             { pH->first = pNew; }
20732    pHead->prev = pNew;
20733  }else{
20734    pNew->next = pH->first;
20735    if( pH->first ){ pH->first->prev = pNew; }
20736    pNew->prev = 0;
20737    pH->first = pNew;
20738  }
20739}
20740
20741
20742/* Resize the hash table so that it cantains "new_size" buckets.
20743**
20744** The hash table might fail to resize if sqlite3_malloc() fails or
20745** if the new size is the same as the prior size.
20746** Return TRUE if the resize occurs and false if not.
20747*/
20748static int rehash(Hash *pH, unsigned int new_size){
20749  struct _ht *new_ht;            /* The new hash table */
20750  HashElem *elem, *next_elem;    /* For looping over existing elements */
20751
20752#if SQLITE_MALLOC_SOFT_LIMIT>0
20753  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
20754    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
20755  }
20756  if( new_size==pH->htsize ) return 0;
20757#endif
20758
20759  /* The inability to allocates space for a larger hash table is
20760  ** a performance hit but it is not a fatal error.  So mark the
20761  ** allocation as a benign.
20762  */
20763  sqlite3BeginBenignMalloc();
20764  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
20765  sqlite3EndBenignMalloc();
20766
20767  if( new_ht==0 ) return 0;
20768  sqlite3_free(pH->ht);
20769  pH->ht = new_ht;
20770  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
20771  memset(new_ht, 0, new_size*sizeof(struct _ht));
20772  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
20773    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
20774    next_elem = elem->next;
20775    insertElement(pH, &new_ht[h], elem);
20776  }
20777  return 1;
20778}
20779
20780/* This function (for internal use only) locates an element in an
20781** hash table that matches the given key.  The hash for this key has
20782** already been computed and is passed as the 4th parameter.
20783*/
20784static HashElem *findElementGivenHash(
20785  const Hash *pH,     /* The pH to be searched */
20786  const char *pKey,   /* The key we are searching for */
20787  int nKey,           /* Bytes in key (not counting zero terminator) */
20788  unsigned int h      /* The hash for this key. */
20789){
20790  HashElem *elem;                /* Used to loop thru the element list */
20791  int count;                     /* Number of elements left to test */
20792
20793  if( pH->ht ){
20794    struct _ht *pEntry = &pH->ht[h];
20795    elem = pEntry->chain;
20796    count = pEntry->count;
20797  }else{
20798    elem = pH->first;
20799    count = pH->count;
20800  }
20801  while( count-- && ALWAYS(elem) ){
20802    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
20803      return elem;
20804    }
20805    elem = elem->next;
20806  }
20807  return 0;
20808}
20809
20810/* Remove a single entry from the hash table given a pointer to that
20811** element and a hash on the element's key.
20812*/
20813static void removeElementGivenHash(
20814  Hash *pH,         /* The pH containing "elem" */
20815  HashElem* elem,   /* The element to be removed from the pH */
20816  unsigned int h    /* Hash value for the element */
20817){
20818  struct _ht *pEntry;
20819  if( elem->prev ){
20820    elem->prev->next = elem->next;
20821  }else{
20822    pH->first = elem->next;
20823  }
20824  if( elem->next ){
20825    elem->next->prev = elem->prev;
20826  }
20827  if( pH->ht ){
20828    pEntry = &pH->ht[h];
20829    if( pEntry->chain==elem ){
20830      pEntry->chain = elem->next;
20831    }
20832    pEntry->count--;
20833    assert( pEntry->count>=0 );
20834  }
20835  sqlite3_free( elem );
20836  pH->count--;
20837  if( pH->count<=0 ){
20838    assert( pH->first==0 );
20839    assert( pH->count==0 );
20840    sqlite3HashClear(pH);
20841  }
20842}
20843
20844/* Attempt to locate an element of the hash table pH with a key
20845** that matches pKey,nKey.  Return the data for this element if it is
20846** found, or NULL if there is no match.
20847*/
20848SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
20849  HashElem *elem;    /* The element that matches key */
20850  unsigned int h;    /* A hash on key */
20851
20852  assert( pH!=0 );
20853  assert( pKey!=0 );
20854  assert( nKey>=0 );
20855  if( pH->ht ){
20856    h = strHash(pKey, nKey) % pH->htsize;
20857  }else{
20858    h = 0;
20859  }
20860  elem = findElementGivenHash(pH, pKey, nKey, h);
20861  return elem ? elem->data : 0;
20862}
20863
20864/* Insert an element into the hash table pH.  The key is pKey,nKey
20865** and the data is "data".
20866**
20867** If no element exists with a matching key, then a new
20868** element is created and NULL is returned.
20869**
20870** If another element already exists with the same key, then the
20871** new data replaces the old data and the old data is returned.
20872** The key is not copied in this instance.  If a malloc fails, then
20873** the new data is returned and the hash table is unchanged.
20874**
20875** If the "data" parameter to this function is NULL, then the
20876** element corresponding to "key" is removed from the hash table.
20877*/
20878SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
20879  unsigned int h;       /* the hash of the key modulo hash table size */
20880  HashElem *elem;       /* Used to loop thru the element list */
20881  HashElem *new_elem;   /* New element added to the pH */
20882
20883  assert( pH!=0 );
20884  assert( pKey!=0 );
20885  assert( nKey>=0 );
20886  if( pH->htsize ){
20887    h = strHash(pKey, nKey) % pH->htsize;
20888  }else{
20889    h = 0;
20890  }
20891  elem = findElementGivenHash(pH,pKey,nKey,h);
20892  if( elem ){
20893    void *old_data = elem->data;
20894    if( data==0 ){
20895      removeElementGivenHash(pH,elem,h);
20896    }else{
20897      elem->data = data;
20898      elem->pKey = pKey;
20899      assert(nKey==elem->nKey);
20900    }
20901    return old_data;
20902  }
20903  if( data==0 ) return 0;
20904  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20905  if( new_elem==0 ) return data;
20906  new_elem->pKey = pKey;
20907  new_elem->nKey = nKey;
20908  new_elem->data = data;
20909  pH->count++;
20910  if( pH->count>=10 && pH->count > 2*pH->htsize ){
20911    if( rehash(pH, pH->count*2) ){
20912      assert( pH->htsize>0 );
20913      h = strHash(pKey, nKey) % pH->htsize;
20914    }
20915  }
20916  if( pH->ht ){
20917    insertElement(pH, &pH->ht[h], new_elem);
20918  }else{
20919    insertElement(pH, 0, new_elem);
20920  }
20921  return 0;
20922}
20923
20924/************** End of hash.c ************************************************/
20925/************** Begin file opcodes.c *****************************************/
20926/* Automatically generated.  Do not edit */
20927/* See the mkopcodec.awk script for details. */
20928#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20929SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20930 static const char *const azName[] = { "?",
20931     /*   1 */ "Goto",
20932     /*   2 */ "Gosub",
20933     /*   3 */ "Return",
20934     /*   4 */ "Yield",
20935     /*   5 */ "HaltIfNull",
20936     /*   6 */ "Halt",
20937     /*   7 */ "Integer",
20938     /*   8 */ "Int64",
20939     /*   9 */ "String",
20940     /*  10 */ "Null",
20941     /*  11 */ "Blob",
20942     /*  12 */ "Variable",
20943     /*  13 */ "Move",
20944     /*  14 */ "Copy",
20945     /*  15 */ "SCopy",
20946     /*  16 */ "ResultRow",
20947     /*  17 */ "CollSeq",
20948     /*  18 */ "Function",
20949     /*  19 */ "Not",
20950     /*  20 */ "AddImm",
20951     /*  21 */ "MustBeInt",
20952     /*  22 */ "RealAffinity",
20953     /*  23 */ "Permutation",
20954     /*  24 */ "Compare",
20955     /*  25 */ "Jump",
20956     /*  26 */ "If",
20957     /*  27 */ "IfNot",
20958     /*  28 */ "Column",
20959     /*  29 */ "Affinity",
20960     /*  30 */ "MakeRecord",
20961     /*  31 */ "Count",
20962     /*  32 */ "Savepoint",
20963     /*  33 */ "AutoCommit",
20964     /*  34 */ "Transaction",
20965     /*  35 */ "ReadCookie",
20966     /*  36 */ "SetCookie",
20967     /*  37 */ "VerifyCookie",
20968     /*  38 */ "OpenRead",
20969     /*  39 */ "OpenWrite",
20970     /*  40 */ "OpenAutoindex",
20971     /*  41 */ "OpenEphemeral",
20972     /*  42 */ "OpenPseudo",
20973     /*  43 */ "Close",
20974     /*  44 */ "SeekLt",
20975     /*  45 */ "SeekLe",
20976     /*  46 */ "SeekGe",
20977     /*  47 */ "SeekGt",
20978     /*  48 */ "Seek",
20979     /*  49 */ "NotFound",
20980     /*  50 */ "Found",
20981     /*  51 */ "IsUnique",
20982     /*  52 */ "NotExists",
20983     /*  53 */ "Sequence",
20984     /*  54 */ "NewRowid",
20985     /*  55 */ "Insert",
20986     /*  56 */ "InsertInt",
20987     /*  57 */ "Delete",
20988     /*  58 */ "ResetCount",
20989     /*  59 */ "RowKey",
20990     /*  60 */ "RowData",
20991     /*  61 */ "Rowid",
20992     /*  62 */ "NullRow",
20993     /*  63 */ "Last",
20994     /*  64 */ "Sort",
20995     /*  65 */ "Rewind",
20996     /*  66 */ "Prev",
20997     /*  67 */ "Next",
20998     /*  68 */ "Or",
20999     /*  69 */ "And",
21000     /*  70 */ "IdxInsert",
21001     /*  71 */ "IdxDelete",
21002     /*  72 */ "IdxRowid",
21003     /*  73 */ "IsNull",
21004     /*  74 */ "NotNull",
21005     /*  75 */ "Ne",
21006     /*  76 */ "Eq",
21007     /*  77 */ "Gt",
21008     /*  78 */ "Le",
21009     /*  79 */ "Lt",
21010     /*  80 */ "Ge",
21011     /*  81 */ "IdxLT",
21012     /*  82 */ "BitAnd",
21013     /*  83 */ "BitOr",
21014     /*  84 */ "ShiftLeft",
21015     /*  85 */ "ShiftRight",
21016     /*  86 */ "Add",
21017     /*  87 */ "Subtract",
21018     /*  88 */ "Multiply",
21019     /*  89 */ "Divide",
21020     /*  90 */ "Remainder",
21021     /*  91 */ "Concat",
21022     /*  92 */ "IdxGE",
21023     /*  93 */ "BitNot",
21024     /*  94 */ "String8",
21025     /*  95 */ "Destroy",
21026     /*  96 */ "Clear",
21027     /*  97 */ "CreateIndex",
21028     /*  98 */ "CreateTable",
21029     /*  99 */ "ParseSchema",
21030     /* 100 */ "LoadAnalysis",
21031     /* 101 */ "DropTable",
21032     /* 102 */ "DropIndex",
21033     /* 103 */ "DropTrigger",
21034     /* 104 */ "IntegrityCk",
21035     /* 105 */ "RowSetAdd",
21036     /* 106 */ "RowSetRead",
21037     /* 107 */ "RowSetTest",
21038     /* 108 */ "Program",
21039     /* 109 */ "Param",
21040     /* 110 */ "FkCounter",
21041     /* 111 */ "FkIfZero",
21042     /* 112 */ "MemMax",
21043     /* 113 */ "IfPos",
21044     /* 114 */ "IfNeg",
21045     /* 115 */ "IfZero",
21046     /* 116 */ "AggStep",
21047     /* 117 */ "AggFinal",
21048     /* 118 */ "Checkpoint",
21049     /* 119 */ "JournalMode",
21050     /* 120 */ "Vacuum",
21051     /* 121 */ "IncrVacuum",
21052     /* 122 */ "Expire",
21053     /* 123 */ "TableLock",
21054     /* 124 */ "VBegin",
21055     /* 125 */ "VCreate",
21056     /* 126 */ "VDestroy",
21057     /* 127 */ "VOpen",
21058     /* 128 */ "VFilter",
21059     /* 129 */ "VColumn",
21060     /* 130 */ "Real",
21061     /* 131 */ "VNext",
21062     /* 132 */ "VRename",
21063     /* 133 */ "VUpdate",
21064     /* 134 */ "Pagecount",
21065     /* 135 */ "Trace",
21066     /* 136 */ "Noop",
21067     /* 137 */ "Explain",
21068     /* 138 */ "NotUsed_138",
21069     /* 139 */ "NotUsed_139",
21070     /* 140 */ "NotUsed_140",
21071     /* 141 */ "ToText",
21072     /* 142 */ "ToBlob",
21073     /* 143 */ "ToNumeric",
21074     /* 144 */ "ToInt",
21075     /* 145 */ "ToReal",
21076  };
21077  return azName[i];
21078}
21079#endif
21080
21081/************** End of opcodes.c *********************************************/
21082/************** Begin file os_os2.c ******************************************/
21083/*
21084** 2006 Feb 14
21085**
21086** The author disclaims copyright to this source code.  In place of
21087** a legal notice, here is a blessing:
21088**
21089**    May you do good and not evil.
21090**    May you find forgiveness for yourself and forgive others.
21091**    May you share freely, never taking more than you give.
21092**
21093******************************************************************************
21094**
21095** This file contains code that is specific to OS/2.
21096*/
21097
21098
21099#if SQLITE_OS_OS2
21100
21101/*
21102** A Note About Memory Allocation:
21103**
21104** This driver uses malloc()/free() directly rather than going through
21105** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21106** are designed for use on embedded systems where memory is scarce and
21107** malloc failures happen frequently.  OS/2 does not typically run on
21108** embedded systems, and when it does the developers normally have bigger
21109** problems to worry about than running out of memory.  So there is not
21110** a compelling need to use the wrappers.
21111**
21112** But there is a good reason to not use the wrappers.  If we use the
21113** wrappers then we will get simulated malloc() failures within this
21114** driver.  And that causes all kinds of problems for our tests.  We
21115** could enhance SQLite to deal with simulated malloc failures within
21116** the OS driver, but the code to deal with those failure would not
21117** be exercised on Linux (which does not need to malloc() in the driver)
21118** and so we would have difficulty writing coverage tests for that
21119** code.  Better to leave the code out, we think.
21120**
21121** The point of this discussion is as follows:  When creating a new
21122** OS layer for an embedded system, if you use this file as an example,
21123** avoid the use of malloc()/free().  Those routines work ok on OS/2
21124** desktops but not so well in embedded systems.
21125*/
21126
21127/*
21128** Macros used to determine whether or not to use threads.
21129*/
21130#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21131# define SQLITE_OS2_THREADS 1
21132#endif
21133
21134/*
21135** Include code that is common to all os_*.c files
21136*/
21137/************** Include os_common.h in the middle of os_os2.c ****************/
21138/************** Begin file os_common.h ***************************************/
21139/*
21140** 2004 May 22
21141**
21142** The author disclaims copyright to this source code.  In place of
21143** a legal notice, here is a blessing:
21144**
21145**    May you do good and not evil.
21146**    May you find forgiveness for yourself and forgive others.
21147**    May you share freely, never taking more than you give.
21148**
21149******************************************************************************
21150**
21151** This file contains macros and a little bit of code that is common to
21152** all of the platform-specific files (os_*.c) and is #included into those
21153** files.
21154**
21155** This file should be #included by the os_*.c files only.  It is not a
21156** general purpose header file.
21157*/
21158#ifndef _OS_COMMON_H_
21159#define _OS_COMMON_H_
21160
21161/*
21162** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21163** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21164** switch.  The following code should catch this problem at compile-time.
21165*/
21166#ifdef MEMORY_DEBUG
21167# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21168#endif
21169
21170#ifdef SQLITE_DEBUG
21171SQLITE_PRIVATE int sqlite3OSTrace = 0;
21172#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21173#else
21174#define OSTRACE(X)
21175#endif
21176
21177/*
21178** Macros for performance tracing.  Normally turned off.  Only works
21179** on i486 hardware.
21180*/
21181#ifdef SQLITE_PERFORMANCE_TRACE
21182
21183/*
21184** hwtime.h contains inline assembler code for implementing
21185** high-performance timing routines.
21186*/
21187/************** Include hwtime.h in the middle of os_common.h ****************/
21188/************** Begin file hwtime.h ******************************************/
21189/*
21190** 2008 May 27
21191**
21192** The author disclaims copyright to this source code.  In place of
21193** a legal notice, here is a blessing:
21194**
21195**    May you do good and not evil.
21196**    May you find forgiveness for yourself and forgive others.
21197**    May you share freely, never taking more than you give.
21198**
21199******************************************************************************
21200**
21201** This file contains inline asm code for retrieving "high-performance"
21202** counters for x86 class CPUs.
21203*/
21204#ifndef _HWTIME_H_
21205#define _HWTIME_H_
21206
21207/*
21208** The following routine only works on pentium-class (or newer) processors.
21209** It uses the RDTSC opcode to read the cycle count value out of the
21210** processor and returns that value.  This can be used for high-res
21211** profiling.
21212*/
21213#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21214      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21215
21216  #if defined(__GNUC__)
21217
21218  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21219     unsigned int lo, hi;
21220     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21221     return (sqlite_uint64)hi << 32 | lo;
21222  }
21223
21224  #elif defined(_MSC_VER)
21225
21226  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21227     __asm {
21228        rdtsc
21229        ret       ; return value at EDX:EAX
21230     }
21231  }
21232
21233  #endif
21234
21235#elif (defined(__GNUC__) && defined(__x86_64__))
21236
21237  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21238      unsigned long val;
21239      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21240      return val;
21241  }
21242
21243#elif (defined(__GNUC__) && defined(__ppc__))
21244
21245  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21246      unsigned long long retval;
21247      unsigned long junk;
21248      __asm__ __volatile__ ("\n\
21249          1:      mftbu   %1\n\
21250                  mftb    %L0\n\
21251                  mftbu   %0\n\
21252                  cmpw    %0,%1\n\
21253                  bne     1b"
21254                  : "=r" (retval), "=r" (junk));
21255      return retval;
21256  }
21257
21258#else
21259
21260  #error Need implementation of sqlite3Hwtime() for your platform.
21261
21262  /*
21263  ** To compile without implementing sqlite3Hwtime() for your platform,
21264  ** you can remove the above #error and use the following
21265  ** stub function.  You will lose timing support for many
21266  ** of the debugging and testing utilities, but it should at
21267  ** least compile and run.
21268  */
21269SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21270
21271#endif
21272
21273#endif /* !defined(_HWTIME_H_) */
21274
21275/************** End of hwtime.h **********************************************/
21276/************** Continuing where we left off in os_common.h ******************/
21277
21278static sqlite_uint64 g_start;
21279static sqlite_uint64 g_elapsed;
21280#define TIMER_START       g_start=sqlite3Hwtime()
21281#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21282#define TIMER_ELAPSED     g_elapsed
21283#else
21284#define TIMER_START
21285#define TIMER_END
21286#define TIMER_ELAPSED     ((sqlite_uint64)0)
21287#endif
21288
21289/*
21290** If we compile with the SQLITE_TEST macro set, then the following block
21291** of code will give us the ability to simulate a disk I/O error.  This
21292** is used for testing the I/O recovery logic.
21293*/
21294#ifdef SQLITE_TEST
21295SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21296SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21297SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21298SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21299SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21300SQLITE_API int sqlite3_diskfull_pending = 0;
21301SQLITE_API int sqlite3_diskfull = 0;
21302#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21303#define SimulateIOError(CODE)  \
21304  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21305       || sqlite3_io_error_pending-- == 1 )  \
21306              { local_ioerr(); CODE; }
21307static void local_ioerr(){
21308  IOTRACE(("IOERR\n"));
21309  sqlite3_io_error_hit++;
21310  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21311}
21312#define SimulateDiskfullError(CODE) \
21313   if( sqlite3_diskfull_pending ){ \
21314     if( sqlite3_diskfull_pending == 1 ){ \
21315       local_ioerr(); \
21316       sqlite3_diskfull = 1; \
21317       sqlite3_io_error_hit = 1; \
21318       CODE; \
21319     }else{ \
21320       sqlite3_diskfull_pending--; \
21321     } \
21322   }
21323#else
21324#define SimulateIOErrorBenign(X)
21325#define SimulateIOError(A)
21326#define SimulateDiskfullError(A)
21327#endif
21328
21329/*
21330** When testing, keep a count of the number of open files.
21331*/
21332#ifdef SQLITE_TEST
21333SQLITE_API int sqlite3_open_file_count = 0;
21334#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21335#else
21336#define OpenCounter(X)
21337#endif
21338
21339#endif /* !defined(_OS_COMMON_H_) */
21340
21341/************** End of os_common.h *******************************************/
21342/************** Continuing where we left off in os_os2.c *********************/
21343
21344/*
21345** The os2File structure is subclass of sqlite3_file specific for the OS/2
21346** protability layer.
21347*/
21348typedef struct os2File os2File;
21349struct os2File {
21350  const sqlite3_io_methods *pMethod;  /* Always the first entry */
21351  HFILE h;                  /* Handle for accessing the file */
21352  char* pathToDel;          /* Name of file to delete on close, NULL if not */
21353  unsigned char locktype;   /* Type of lock currently held on this file */
21354};
21355
21356#define LOCK_TIMEOUT 10L /* the default locking timeout */
21357
21358/*****************************************************************************
21359** The next group of routines implement the I/O methods specified
21360** by the sqlite3_io_methods object.
21361******************************************************************************/
21362
21363/*
21364** Close a file.
21365*/
21366static int os2Close( sqlite3_file *id ){
21367  APIRET rc = NO_ERROR;
21368  os2File *pFile;
21369  if( id && (pFile = (os2File*)id) != 0 ){
21370    OSTRACE(( "CLOSE %d\n", pFile->h ));
21371    rc = DosClose( pFile->h );
21372    pFile->locktype = NO_LOCK;
21373    if( pFile->pathToDel != NULL ){
21374      rc = DosForceDelete( (PSZ)pFile->pathToDel );
21375      free( pFile->pathToDel );
21376      pFile->pathToDel = NULL;
21377    }
21378    id = 0;
21379    OpenCounter( -1 );
21380  }
21381
21382  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21383}
21384
21385/*
21386** Read data from a file into a buffer.  Return SQLITE_OK if all
21387** bytes were read successfully and SQLITE_IOERR if anything goes
21388** wrong.
21389*/
21390static int os2Read(
21391  sqlite3_file *id,               /* File to read from */
21392  void *pBuf,                     /* Write content into this buffer */
21393  int amt,                        /* Number of bytes to read */
21394  sqlite3_int64 offset            /* Begin reading at this offset */
21395){
21396  ULONG fileLocation = 0L;
21397  ULONG got;
21398  os2File *pFile = (os2File*)id;
21399  assert( id!=0 );
21400  SimulateIOError( return SQLITE_IOERR_READ );
21401  OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21402  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21403    return SQLITE_IOERR;
21404  }
21405  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21406    return SQLITE_IOERR_READ;
21407  }
21408  if( got == (ULONG)amt )
21409    return SQLITE_OK;
21410  else {
21411    /* Unread portions of the input buffer must be zero-filled */
21412    memset(&((char*)pBuf)[got], 0, amt-got);
21413    return SQLITE_IOERR_SHORT_READ;
21414  }
21415}
21416
21417/*
21418** Write data from a buffer into a file.  Return SQLITE_OK on success
21419** or some other error code on failure.
21420*/
21421static int os2Write(
21422  sqlite3_file *id,               /* File to write into */
21423  const void *pBuf,               /* The bytes to be written */
21424  int amt,                        /* Number of bytes to write */
21425  sqlite3_int64 offset            /* Offset into the file to begin writing at */
21426){
21427  ULONG fileLocation = 0L;
21428  APIRET rc = NO_ERROR;
21429  ULONG wrote;
21430  os2File *pFile = (os2File*)id;
21431  assert( id!=0 );
21432  SimulateIOError( return SQLITE_IOERR_WRITE );
21433  SimulateDiskfullError( return SQLITE_FULL );
21434  OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21435  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21436    return SQLITE_IOERR;
21437  }
21438  assert( amt>0 );
21439  while( amt > 0 &&
21440         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21441         wrote > 0
21442  ){
21443    amt -= wrote;
21444    pBuf = &((char*)pBuf)[wrote];
21445  }
21446
21447  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21448}
21449
21450/*
21451** Truncate an open file to a specified size
21452*/
21453static int os2Truncate( sqlite3_file *id, i64 nByte ){
21454  APIRET rc = NO_ERROR;
21455  os2File *pFile = (os2File*)id;
21456  OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21457  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21458  rc = DosSetFileSize( pFile->h, nByte );
21459  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21460}
21461
21462#ifdef SQLITE_TEST
21463/*
21464** Count the number of fullsyncs and normal syncs.  This is used to test
21465** that syncs and fullsyncs are occuring at the right times.
21466*/
21467SQLITE_API int sqlite3_sync_count = 0;
21468SQLITE_API int sqlite3_fullsync_count = 0;
21469#endif
21470
21471/*
21472** Make sure all writes to a particular file are committed to disk.
21473*/
21474static int os2Sync( sqlite3_file *id, int flags ){
21475  os2File *pFile = (os2File*)id;
21476  OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21477#ifdef SQLITE_TEST
21478  if( flags & SQLITE_SYNC_FULL){
21479    sqlite3_fullsync_count++;
21480  }
21481  sqlite3_sync_count++;
21482#endif
21483  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21484  ** no-op
21485  */
21486#ifdef SQLITE_NO_SYNC
21487  UNUSED_PARAMETER(pFile);
21488  return SQLITE_OK;
21489#else
21490  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21491#endif
21492}
21493
21494/*
21495** Determine the current size of a file in bytes
21496*/
21497static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21498  APIRET rc = NO_ERROR;
21499  FILESTATUS3 fsts3FileInfo;
21500  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21501  assert( id!=0 );
21502  SimulateIOError( return SQLITE_IOERR_FSTAT );
21503  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21504  if( rc == NO_ERROR ){
21505    *pSize = fsts3FileInfo.cbFile;
21506    return SQLITE_OK;
21507  }else{
21508    return SQLITE_IOERR_FSTAT;
21509  }
21510}
21511
21512/*
21513** Acquire a reader lock.
21514*/
21515static int getReadLock( os2File *pFile ){
21516  FILELOCK  LockArea,
21517            UnlockArea;
21518  APIRET res;
21519  memset(&LockArea, 0, sizeof(LockArea));
21520  memset(&UnlockArea, 0, sizeof(UnlockArea));
21521  LockArea.lOffset = SHARED_FIRST;
21522  LockArea.lRange = SHARED_SIZE;
21523  UnlockArea.lOffset = 0L;
21524  UnlockArea.lRange = 0L;
21525  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21526  OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21527  return res;
21528}
21529
21530/*
21531** Undo a readlock
21532*/
21533static int unlockReadLock( os2File *id ){
21534  FILELOCK  LockArea,
21535            UnlockArea;
21536  APIRET res;
21537  memset(&LockArea, 0, sizeof(LockArea));
21538  memset(&UnlockArea, 0, sizeof(UnlockArea));
21539  LockArea.lOffset = 0L;
21540  LockArea.lRange = 0L;
21541  UnlockArea.lOffset = SHARED_FIRST;
21542  UnlockArea.lRange = SHARED_SIZE;
21543  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21544  OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21545  return res;
21546}
21547
21548/*
21549** Lock the file with the lock specified by parameter locktype - one
21550** of the following:
21551**
21552**     (1) SHARED_LOCK
21553**     (2) RESERVED_LOCK
21554**     (3) PENDING_LOCK
21555**     (4) EXCLUSIVE_LOCK
21556**
21557** Sometimes when requesting one lock state, additional lock states
21558** are inserted in between.  The locking might fail on one of the later
21559** transitions leaving the lock state different from what it started but
21560** still short of its goal.  The following chart shows the allowed
21561** transitions and the inserted intermediate states:
21562**
21563**    UNLOCKED -> SHARED
21564**    SHARED -> RESERVED
21565**    SHARED -> (PENDING) -> EXCLUSIVE
21566**    RESERVED -> (PENDING) -> EXCLUSIVE
21567**    PENDING -> EXCLUSIVE
21568**
21569** This routine will only increase a lock.  The os2Unlock() routine
21570** erases all locks at once and returns us immediately to locking level 0.
21571** It is not possible to lower the locking level one step at a time.  You
21572** must go straight to locking level 0.
21573*/
21574static int os2Lock( sqlite3_file *id, int locktype ){
21575  int rc = SQLITE_OK;       /* Return code from subroutines */
21576  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21577  int newLocktype;       /* Set pFile->locktype to this value before exiting */
21578  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21579  FILELOCK  LockArea,
21580            UnlockArea;
21581  os2File *pFile = (os2File*)id;
21582  memset(&LockArea, 0, sizeof(LockArea));
21583  memset(&UnlockArea, 0, sizeof(UnlockArea));
21584  assert( pFile!=0 );
21585  OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
21586
21587  /* If there is already a lock of this type or more restrictive on the
21588  ** os2File, do nothing. Don't use the end_lock: exit path, as
21589  ** sqlite3_mutex_enter() hasn't been called yet.
21590  */
21591  if( pFile->locktype>=locktype ){
21592    OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
21593    return SQLITE_OK;
21594  }
21595
21596  /* Make sure the locking sequence is correct
21597  */
21598  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21599  assert( locktype!=PENDING_LOCK );
21600  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21601
21602  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21603  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21604  ** the PENDING_LOCK byte is temporary.
21605  */
21606  newLocktype = pFile->locktype;
21607  if( pFile->locktype==NO_LOCK
21608      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21609  ){
21610    LockArea.lOffset = PENDING_BYTE;
21611    LockArea.lRange = 1L;
21612    UnlockArea.lOffset = 0L;
21613    UnlockArea.lRange = 0L;
21614
21615    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21616    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21617    if( res == NO_ERROR ){
21618      gotPendingLock = 1;
21619      OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21620    }
21621  }
21622
21623  /* Acquire a shared lock
21624  */
21625  if( locktype==SHARED_LOCK && res == NO_ERROR ){
21626    assert( pFile->locktype==NO_LOCK );
21627    res = getReadLock(pFile);
21628    if( res == NO_ERROR ){
21629      newLocktype = SHARED_LOCK;
21630    }
21631    OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
21632  }
21633
21634  /* Acquire a RESERVED lock
21635  */
21636  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21637    assert( pFile->locktype==SHARED_LOCK );
21638    LockArea.lOffset = RESERVED_BYTE;
21639    LockArea.lRange = 1L;
21640    UnlockArea.lOffset = 0L;
21641    UnlockArea.lRange = 0L;
21642    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21643    if( res == NO_ERROR ){
21644      newLocktype = RESERVED_LOCK;
21645    }
21646    OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
21647  }
21648
21649  /* Acquire a PENDING lock
21650  */
21651  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21652    newLocktype = PENDING_LOCK;
21653    gotPendingLock = 0;
21654    OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
21655               pFile->h ));
21656  }
21657
21658  /* Acquire an EXCLUSIVE lock
21659  */
21660  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21661    assert( pFile->locktype>=SHARED_LOCK );
21662    res = unlockReadLock(pFile);
21663    OSTRACE(( "unreadlock = %d\n", res ));
21664    LockArea.lOffset = SHARED_FIRST;
21665    LockArea.lRange = SHARED_SIZE;
21666    UnlockArea.lOffset = 0L;
21667    UnlockArea.lRange = 0L;
21668    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21669    if( res == NO_ERROR ){
21670      newLocktype = EXCLUSIVE_LOCK;
21671    }else{
21672      OSTRACE(( "OS/2 error-code = %d\n", res ));
21673      getReadLock(pFile);
21674    }
21675    OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
21676  }
21677
21678  /* If we are holding a PENDING lock that ought to be released, then
21679  ** release it now.
21680  */
21681  if( gotPendingLock && locktype==SHARED_LOCK ){
21682    int r;
21683    LockArea.lOffset = 0L;
21684    LockArea.lRange = 0L;
21685    UnlockArea.lOffset = PENDING_BYTE;
21686    UnlockArea.lRange = 1L;
21687    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21688    OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
21689  }
21690
21691  /* Update the state of the lock has held in the file descriptor then
21692  ** return the appropriate result code.
21693  */
21694  if( res == NO_ERROR ){
21695    rc = SQLITE_OK;
21696  }else{
21697    OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21698              locktype, newLocktype ));
21699    rc = SQLITE_BUSY;
21700  }
21701  pFile->locktype = newLocktype;
21702  OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
21703  return rc;
21704}
21705
21706/*
21707** This routine checks if there is a RESERVED lock held on the specified
21708** file by this or any other process. If such a lock is held, return
21709** non-zero, otherwise zero.
21710*/
21711static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21712  int r = 0;
21713  os2File *pFile = (os2File*)id;
21714  assert( pFile!=0 );
21715  if( pFile->locktype>=RESERVED_LOCK ){
21716    r = 1;
21717    OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
21718  }else{
21719    FILELOCK  LockArea,
21720              UnlockArea;
21721    APIRET rc = NO_ERROR;
21722    memset(&LockArea, 0, sizeof(LockArea));
21723    memset(&UnlockArea, 0, sizeof(UnlockArea));
21724    LockArea.lOffset = RESERVED_BYTE;
21725    LockArea.lRange = 1L;
21726    UnlockArea.lOffset = 0L;
21727    UnlockArea.lRange = 0L;
21728    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21729    OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
21730    if( rc == NO_ERROR ){
21731      APIRET rcu = NO_ERROR; /* return code for unlocking */
21732      LockArea.lOffset = 0L;
21733      LockArea.lRange = 0L;
21734      UnlockArea.lOffset = RESERVED_BYTE;
21735      UnlockArea.lRange = 1L;
21736      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21737      OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
21738    }
21739    r = !(rc == NO_ERROR);
21740    OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
21741  }
21742  *pOut = r;
21743  return SQLITE_OK;
21744}
21745
21746/*
21747** Lower the locking level on file descriptor id to locktype.  locktype
21748** must be either NO_LOCK or SHARED_LOCK.
21749**
21750** If the locking level of the file descriptor is already at or below
21751** the requested locking level, this routine is a no-op.
21752**
21753** It is not possible for this routine to fail if the second argument
21754** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
21755** might return SQLITE_IOERR;
21756*/
21757static int os2Unlock( sqlite3_file *id, int locktype ){
21758  int type;
21759  os2File *pFile = (os2File*)id;
21760  APIRET rc = SQLITE_OK;
21761  APIRET res = NO_ERROR;
21762  FILELOCK  LockArea,
21763            UnlockArea;
21764  memset(&LockArea, 0, sizeof(LockArea));
21765  memset(&UnlockArea, 0, sizeof(UnlockArea));
21766  assert( pFile!=0 );
21767  assert( locktype<=SHARED_LOCK );
21768  OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
21769  type = pFile->locktype;
21770  if( type>=EXCLUSIVE_LOCK ){
21771    LockArea.lOffset = 0L;
21772    LockArea.lRange = 0L;
21773    UnlockArea.lOffset = SHARED_FIRST;
21774    UnlockArea.lRange = SHARED_SIZE;
21775    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21776    OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
21777    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21778      /* This should never happen.  We should always be able to
21779      ** reacquire the read lock */
21780      OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
21781      rc = SQLITE_IOERR_UNLOCK;
21782    }
21783  }
21784  if( type>=RESERVED_LOCK ){
21785    LockArea.lOffset = 0L;
21786    LockArea.lRange = 0L;
21787    UnlockArea.lOffset = RESERVED_BYTE;
21788    UnlockArea.lRange = 1L;
21789    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21790    OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
21791  }
21792  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21793    res = unlockReadLock(pFile);
21794    OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
21795              pFile->h, type, locktype, res ));
21796  }
21797  if( type>=PENDING_LOCK ){
21798    LockArea.lOffset = 0L;
21799    LockArea.lRange = 0L;
21800    UnlockArea.lOffset = PENDING_BYTE;
21801    UnlockArea.lRange = 1L;
21802    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21803    OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
21804  }
21805  pFile->locktype = locktype;
21806  OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
21807  return rc;
21808}
21809
21810/*
21811** Control and query of the open file handle.
21812*/
21813static int os2FileControl(sqlite3_file *id, int op, void *pArg){
21814  switch( op ){
21815    case SQLITE_FCNTL_LOCKSTATE: {
21816      *(int*)pArg = ((os2File*)id)->locktype;
21817      OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
21818                ((os2File*)id)->h, ((os2File*)id)->locktype ));
21819      return SQLITE_OK;
21820    }
21821  }
21822  return SQLITE_ERROR;
21823}
21824
21825/*
21826** Return the sector size in bytes of the underlying block device for
21827** the specified file. This is almost always 512 bytes, but may be
21828** larger for some devices.
21829**
21830** SQLite code assumes this function cannot fail. It also assumes that
21831** if two files are created in the same file-system directory (i.e.
21832** a database and its journal file) that the sector size will be the
21833** same for both.
21834*/
21835static int os2SectorSize(sqlite3_file *id){
21836  return SQLITE_DEFAULT_SECTOR_SIZE;
21837}
21838
21839/*
21840** Return a vector of device characteristics.
21841*/
21842static int os2DeviceCharacteristics(sqlite3_file *id){
21843  return 0;
21844}
21845
21846
21847/*
21848** Character set conversion objects used by conversion routines.
21849*/
21850static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21851static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21852
21853/*
21854** Helper function to initialize the conversion objects from and to UTF-8.
21855*/
21856static void initUconvObjects( void ){
21857  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21858    ucUtf8 = NULL;
21859  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21860    uclCp = NULL;
21861}
21862
21863/*
21864** Helper function to free the conversion objects from and to UTF-8.
21865*/
21866static void freeUconvObjects( void ){
21867  if ( ucUtf8 )
21868    UniFreeUconvObject( ucUtf8 );
21869  if ( uclCp )
21870    UniFreeUconvObject( uclCp );
21871  ucUtf8 = NULL;
21872  uclCp = NULL;
21873}
21874
21875/*
21876** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21877** The two-step process: first convert the incoming UTF-8 string
21878** into UCS-2 and then from UCS-2 to the current codepage.
21879** The returned char pointer has to be freed.
21880*/
21881static char *convertUtf8PathToCp( const char *in ){
21882  UniChar tempPath[CCHMAXPATH];
21883  char *out = (char *)calloc( CCHMAXPATH, 1 );
21884
21885  if( !out )
21886    return NULL;
21887
21888  if( !ucUtf8 || !uclCp )
21889    initUconvObjects();
21890
21891  /* determine string for the conversion of UTF-8 which is CP1208 */
21892  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21893    return out; /* if conversion fails, return the empty string */
21894
21895  /* conversion for current codepage which can be used for paths */
21896  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21897
21898  return out;
21899}
21900
21901/*
21902** Helper function to convert filenames from local codepage to UTF-8.
21903** The two-step process: first convert the incoming codepage-specific
21904** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21905** The returned char pointer has to be freed.
21906**
21907** This function is non-static to be able to use this in shell.c and
21908** similar applications that take command line arguments.
21909*/
21910char *convertCpPathToUtf8( const char *in ){
21911  UniChar tempPath[CCHMAXPATH];
21912  char *out = (char *)calloc( CCHMAXPATH, 1 );
21913
21914  if( !out )
21915    return NULL;
21916
21917  if( !ucUtf8 || !uclCp )
21918    initUconvObjects();
21919
21920  /* conversion for current codepage which can be used for paths */
21921  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21922    return out; /* if conversion fails, return the empty string */
21923
21924  /* determine string for the conversion of UTF-8 which is CP1208 */
21925  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21926
21927  return out;
21928}
21929
21930/*
21931** This vector defines all the methods that can operate on an
21932** sqlite3_file for os2.
21933*/
21934static const sqlite3_io_methods os2IoMethod = {
21935  1,                        /* iVersion */
21936  os2Close,
21937  os2Read,
21938  os2Write,
21939  os2Truncate,
21940  os2Sync,
21941  os2FileSize,
21942  os2Lock,
21943  os2Unlock,
21944  os2CheckReservedLock,
21945  os2FileControl,
21946  os2SectorSize,
21947  os2DeviceCharacteristics
21948};
21949
21950/***************************************************************************
21951** Here ends the I/O methods that form the sqlite3_io_methods object.
21952**
21953** The next block of code implements the VFS methods.
21954****************************************************************************/
21955
21956/*
21957** Create a temporary file name in zBuf.  zBuf must be big enough to
21958** hold at pVfs->mxPathname characters.
21959*/
21960static int getTempname(int nBuf, char *zBuf ){
21961  static const unsigned char zChars[] =
21962    "abcdefghijklmnopqrstuvwxyz"
21963    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21964    "0123456789";
21965  int i, j;
21966  char zTempPathBuf[3];
21967  PSZ zTempPath = (PSZ)&zTempPathBuf;
21968  if( sqlite3_temp_directory ){
21969    zTempPath = sqlite3_temp_directory;
21970  }else{
21971    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21972      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21973        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21974           ULONG ulDriveNum = 0, ulDriveMap = 0;
21975           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21976           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21977        }
21978      }
21979    }
21980  }
21981  /* Strip off a trailing slashes or backslashes, otherwise we would get *
21982   * multiple (back)slashes which causes DosOpen() to fail.              *
21983   * Trailing spaces are not allowed, either.                            */
21984  j = sqlite3Strlen30(zTempPath);
21985  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21986                    || zTempPath[j-1] == ' ' ) ){
21987    j--;
21988  }
21989  zTempPath[j] = '\0';
21990  if( !sqlite3_temp_directory ){
21991    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21992    sqlite3_snprintf( nBuf-30, zBuf,
21993                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21994    free( zTempPathUTF );
21995  }else{
21996    sqlite3_snprintf( nBuf-30, zBuf,
21997                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21998  }
21999  j = sqlite3Strlen30( zBuf );
22000  sqlite3_randomness( 20, &zBuf[j] );
22001  for( i = 0; i < 20; i++, j++ ){
22002    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
22003  }
22004  zBuf[j] = 0;
22005  OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
22006  return SQLITE_OK;
22007}
22008
22009
22010/*
22011** Turn a relative pathname into a full pathname.  Write the full
22012** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
22013** bytes in size.
22014*/
22015static int os2FullPathname(
22016  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
22017  const char *zRelative,      /* Possibly relative input path */
22018  int nFull,                  /* Size of output buffer in bytes */
22019  char *zFull                 /* Output buffer */
22020){
22021  char *zRelativeCp = convertUtf8PathToCp( zRelative );
22022  char zFullCp[CCHMAXPATH] = "\0";
22023  char *zFullUTF;
22024  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
22025                                CCHMAXPATH );
22026  free( zRelativeCp );
22027  zFullUTF = convertCpPathToUtf8( zFullCp );
22028  sqlite3_snprintf( nFull, zFull, zFullUTF );
22029  free( zFullUTF );
22030  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22031}
22032
22033
22034/*
22035** Open a file.
22036*/
22037static int os2Open(
22038  sqlite3_vfs *pVfs,            /* Not used */
22039  const char *zName,            /* Name of the file */
22040  sqlite3_file *id,             /* Write the SQLite file handle here */
22041  int flags,                    /* Open mode flags */
22042  int *pOutFlags                /* Status return flags */
22043){
22044  HFILE h;
22045  ULONG ulFileAttribute = FILE_NORMAL;
22046  ULONG ulOpenFlags = 0;
22047  ULONG ulOpenMode = 0;
22048  os2File *pFile = (os2File*)id;
22049  APIRET rc = NO_ERROR;
22050  ULONG ulAction;
22051  char *zNameCp;
22052  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
22053
22054  /* If the second argument to this function is NULL, generate a
22055  ** temporary file name to use
22056  */
22057  if( !zName ){
22058    int rc = getTempname(CCHMAXPATH+1, zTmpname);
22059    if( rc!=SQLITE_OK ){
22060      return rc;
22061    }
22062    zName = zTmpname;
22063  }
22064
22065
22066  memset( pFile, 0, sizeof(*pFile) );
22067
22068  OSTRACE(( "OPEN want %d\n", flags ));
22069
22070  if( flags & SQLITE_OPEN_READWRITE ){
22071    ulOpenMode |= OPEN_ACCESS_READWRITE;
22072    OSTRACE(( "OPEN read/write\n" ));
22073  }else{
22074    ulOpenMode |= OPEN_ACCESS_READONLY;
22075    OSTRACE(( "OPEN read only\n" ));
22076  }
22077
22078  if( flags & SQLITE_OPEN_CREATE ){
22079    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
22080    OSTRACE(( "OPEN open new/create\n" ));
22081  }else{
22082    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
22083    OSTRACE(( "OPEN open existing\n" ));
22084  }
22085
22086  if( flags & SQLITE_OPEN_MAIN_DB ){
22087    ulOpenMode |= OPEN_SHARE_DENYNONE;
22088    OSTRACE(( "OPEN share read/write\n" ));
22089  }else{
22090    ulOpenMode |= OPEN_SHARE_DENYWRITE;
22091    OSTRACE(( "OPEN share read only\n" ));
22092  }
22093
22094  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22095    char pathUtf8[CCHMAXPATH];
22096#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
22097    ulFileAttribute = FILE_HIDDEN;
22098#endif
22099    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
22100    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
22101    OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
22102  }else{
22103    pFile->pathToDel = NULL;
22104    OSTRACE(( "OPEN normal file attribute\n" ));
22105  }
22106
22107  /* always open in random access mode for possibly better speed */
22108  ulOpenMode |= OPEN_FLAGS_RANDOM;
22109  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
22110  ulOpenMode |= OPEN_FLAGS_NOINHERIT;
22111
22112  zNameCp = convertUtf8PathToCp( zName );
22113  rc = DosOpen( (PSZ)zNameCp,
22114                &h,
22115                &ulAction,
22116                0L,
22117                ulFileAttribute,
22118                ulOpenFlags,
22119                ulOpenMode,
22120                (PEAOP2)NULL );
22121  free( zNameCp );
22122  if( rc != NO_ERROR ){
22123    OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
22124              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
22125    if( pFile->pathToDel )
22126      free( pFile->pathToDel );
22127    pFile->pathToDel = NULL;
22128    if( flags & SQLITE_OPEN_READWRITE ){
22129      OSTRACE(( "OPEN %d Invalid handle\n",
22130                ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
22131      return os2Open( pVfs, zName, id,
22132                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
22133                      pOutFlags );
22134    }else{
22135      return SQLITE_CANTOPEN;
22136    }
22137  }
22138
22139  if( pOutFlags ){
22140    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
22141  }
22142
22143  pFile->pMethod = &os2IoMethod;
22144  pFile->h = h;
22145  OpenCounter(+1);
22146  OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
22147  return SQLITE_OK;
22148}
22149
22150/*
22151** Delete the named file.
22152*/
22153static int os2Delete(
22154  sqlite3_vfs *pVfs,                     /* Not used on os2 */
22155  const char *zFilename,                 /* Name of file to delete */
22156  int syncDir                            /* Not used on os2 */
22157){
22158  APIRET rc = NO_ERROR;
22159  char *zFilenameCp = convertUtf8PathToCp( zFilename );
22160  SimulateIOError( return SQLITE_IOERR_DELETE );
22161  rc = DosDelete( (PSZ)zFilenameCp );
22162  free( zFilenameCp );
22163  OSTRACE(( "DELETE \"%s\"\n", zFilename ));
22164  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
22165}
22166
22167/*
22168** Check the existance and status of a file.
22169*/
22170static int os2Access(
22171  sqlite3_vfs *pVfs,        /* Not used on os2 */
22172  const char *zFilename,    /* Name of file to check */
22173  int flags,                /* Type of test to make on this file */
22174  int *pOut                 /* Write results here */
22175){
22176  FILESTATUS3 fsts3ConfigInfo;
22177  APIRET rc = NO_ERROR;
22178  char *zFilenameCp = convertUtf8PathToCp( zFilename );
22179
22180  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
22181  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22182                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22183  free( zFilenameCp );
22184  OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22185            fsts3ConfigInfo.attrFile, flags, rc ));
22186  switch( flags ){
22187    case SQLITE_ACCESS_READ:
22188    case SQLITE_ACCESS_EXISTS:
22189      rc = (rc == NO_ERROR);
22190      OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
22191      break;
22192    case SQLITE_ACCESS_READWRITE:
22193      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22194      OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
22195      break;
22196    default:
22197      assert( !"Invalid flags argument" );
22198  }
22199  *pOut = rc;
22200  return SQLITE_OK;
22201}
22202
22203
22204#ifndef SQLITE_OMIT_LOAD_EXTENSION
22205/*
22206** Interfaces for opening a shared library, finding entry points
22207** within the shared library, and closing the shared library.
22208*/
22209/*
22210** Interfaces for opening a shared library, finding entry points
22211** within the shared library, and closing the shared library.
22212*/
22213static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22214  UCHAR loadErr[256];
22215  HMODULE hmod;
22216  APIRET rc;
22217  char *zFilenameCp = convertUtf8PathToCp(zFilename);
22218  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22219  free(zFilenameCp);
22220  return rc != NO_ERROR ? 0 : (void*)hmod;
22221}
22222/*
22223** A no-op since the error code is returned on the DosLoadModule call.
22224** os2Dlopen returns zero if DosLoadModule is not successful.
22225*/
22226static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22227/* no-op */
22228}
22229static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22230  PFN pfn;
22231  APIRET rc;
22232  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22233  if( rc != NO_ERROR ){
22234    /* if the symbol itself was not found, search again for the same
22235     * symbol with an extra underscore, that might be needed depending
22236     * on the calling convention */
22237    char _zSymbol[256] = "_";
22238    strncat(_zSymbol, zSymbol, 255);
22239    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22240  }
22241  return rc != NO_ERROR ? 0 : (void*)pfn;
22242}
22243static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22244  DosFreeModule((HMODULE)pHandle);
22245}
22246#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22247  #define os2DlOpen 0
22248  #define os2DlError 0
22249  #define os2DlSym 0
22250  #define os2DlClose 0
22251#endif
22252
22253
22254/*
22255** Write up to nBuf bytes of randomness into zBuf.
22256*/
22257static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22258  int n = 0;
22259#if defined(SQLITE_TEST)
22260  n = nBuf;
22261  memset(zBuf, 0, nBuf);
22262#else
22263  int sizeofULong = sizeof(ULONG);
22264  if( (int)sizeof(DATETIME) <= nBuf - n ){
22265    DATETIME x;
22266    DosGetDateTime(&x);
22267    memcpy(&zBuf[n], &x, sizeof(x));
22268    n += sizeof(x);
22269  }
22270
22271  if( sizeofULong <= nBuf - n ){
22272    PPIB ppib;
22273    DosGetInfoBlocks(NULL, &ppib);
22274    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22275    n += sizeofULong;
22276  }
22277
22278  if( sizeofULong <= nBuf - n ){
22279    PTIB ptib;
22280    DosGetInfoBlocks(&ptib, NULL);
22281    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22282    n += sizeofULong;
22283  }
22284
22285  /* if we still haven't filled the buffer yet the following will */
22286  /* grab everything once instead of making several calls for a single item */
22287  if( sizeofULong <= nBuf - n ){
22288    ULONG ulSysInfo[QSV_MAX];
22289    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22290
22291    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22292    n += sizeofULong;
22293
22294    if( sizeofULong <= nBuf - n ){
22295      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22296      n += sizeofULong;
22297    }
22298    if( sizeofULong <= nBuf - n ){
22299      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22300      n += sizeofULong;
22301    }
22302    if( sizeofULong <= nBuf - n ){
22303      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22304      n += sizeofULong;
22305    }
22306    if( sizeofULong <= nBuf - n ){
22307      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22308      n += sizeofULong;
22309    }
22310  }
22311#endif
22312
22313  return n;
22314}
22315
22316/*
22317** Sleep for a little while.  Return the amount of time slept.
22318** The argument is the number of microseconds we want to sleep.
22319** The return value is the number of microseconds of sleep actually
22320** requested from the underlying operating system, a number which
22321** might be greater than or equal to the argument, but not less
22322** than the argument.
22323*/
22324static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22325  DosSleep( (microsec/1000) );
22326  return microsec;
22327}
22328
22329/*
22330** The following variable, if set to a non-zero value, becomes the result
22331** returned from sqlite3OsCurrentTime().  This is used for testing.
22332*/
22333#ifdef SQLITE_TEST
22334SQLITE_API int sqlite3_current_time = 0;
22335#endif
22336
22337/*
22338** Find the current time (in Universal Coordinated Time).  Write the
22339** current time and date as a Julian Day number into *prNow and
22340** return 0.  Return 1 if the time and date cannot be found.
22341*/
22342int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22343  double now;
22344  SHORT minute; /* needs to be able to cope with negative timezone offset */
22345  USHORT second, hour,
22346         day, month, year;
22347  DATETIME dt;
22348  DosGetDateTime( &dt );
22349  second = (USHORT)dt.seconds;
22350  minute = (SHORT)dt.minutes + dt.timezone;
22351  hour = (USHORT)dt.hours;
22352  day = (USHORT)dt.day;
22353  month = (USHORT)dt.month;
22354  year = (USHORT)dt.year;
22355
22356  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22357     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22358  /* Calculate the Julian days */
22359  now = day - 32076 +
22360    1461*(year + 4800 + (month - 14)/12)/4 +
22361    367*(month - 2 - (month - 14)/12*12)/12 -
22362    3*((year + 4900 + (month - 14)/12)/100)/4;
22363
22364  /* Add the fractional hours, mins and seconds */
22365  now += (hour + 12.0)/24.0;
22366  now += minute/1440.0;
22367  now += second/86400.0;
22368  *prNow = now;
22369#ifdef SQLITE_TEST
22370  if( sqlite3_current_time ){
22371    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22372  }
22373#endif
22374  return 0;
22375}
22376
22377static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22378  return 0;
22379}
22380
22381/*
22382** Initialize and deinitialize the operating system interface.
22383*/
22384SQLITE_API int sqlite3_os_init(void){
22385  static sqlite3_vfs os2Vfs = {
22386    1,                 /* iVersion */
22387    sizeof(os2File),   /* szOsFile */
22388    CCHMAXPATH,        /* mxPathname */
22389    0,                 /* pNext */
22390    "os2",             /* zName */
22391    0,                 /* pAppData */
22392
22393    os2Open,           /* xOpen */
22394    os2Delete,         /* xDelete */
22395    os2Access,         /* xAccess */
22396    os2FullPathname,   /* xFullPathname */
22397    os2DlOpen,         /* xDlOpen */
22398    os2DlError,        /* xDlError */
22399    os2DlSym,          /* xDlSym */
22400    os2DlClose,        /* xDlClose */
22401    os2Randomness,     /* xRandomness */
22402    os2Sleep,          /* xSleep */
22403    os2CurrentTime,    /* xCurrentTime */
22404    os2GetLastError,   /* xGetLastError */
22405  };
22406  sqlite3_vfs_register(&os2Vfs, 1);
22407  initUconvObjects();
22408  return SQLITE_OK;
22409}
22410SQLITE_API int sqlite3_os_end(void){
22411  freeUconvObjects();
22412  return SQLITE_OK;
22413}
22414
22415#endif /* SQLITE_OS_OS2 */
22416
22417/************** End of os_os2.c **********************************************/
22418/************** Begin file os_unix.c *****************************************/
22419/*
22420** 2004 May 22
22421**
22422** The author disclaims copyright to this source code.  In place of
22423** a legal notice, here is a blessing:
22424**
22425**    May you do good and not evil.
22426**    May you find forgiveness for yourself and forgive others.
22427**    May you share freely, never taking more than you give.
22428**
22429******************************************************************************
22430**
22431** This file contains the VFS implementation for unix-like operating systems
22432** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22433**
22434** There are actually several different VFS implementations in this file.
22435** The differences are in the way that file locking is done.  The default
22436** implementation uses Posix Advisory Locks.  Alternative implementations
22437** use flock(), dot-files, various proprietary locking schemas, or simply
22438** skip locking all together.
22439**
22440** This source file is organized into divisions where the logic for various
22441** subfunctions is contained within the appropriate division.  PLEASE
22442** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22443** in the correct division and should be clearly labeled.
22444**
22445** The layout of divisions is as follows:
22446**
22447**   *  General-purpose declarations and utility functions.
22448**   *  Unique file ID logic used by VxWorks.
22449**   *  Various locking primitive implementations (all except proxy locking):
22450**      + for Posix Advisory Locks
22451**      + for no-op locks
22452**      + for dot-file locks
22453**      + for flock() locking
22454**      + for named semaphore locks (VxWorks only)
22455**      + for AFP filesystem locks (MacOSX only)
22456**   *  sqlite3_file methods not associated with locking.
22457**   *  Definitions of sqlite3_io_methods objects for all locking
22458**      methods plus "finder" functions for each locking method.
22459**   *  sqlite3_vfs method implementations.
22460**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22461**   *  Definitions of sqlite3_vfs objects for all locking methods
22462**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22463*/
22464#if SQLITE_OS_UNIX              /* This file is used on unix only */
22465
22466/*
22467** There are various methods for file locking used for concurrency
22468** control:
22469**
22470**   1. POSIX locking (the default),
22471**   2. No locking,
22472**   3. Dot-file locking,
22473**   4. flock() locking,
22474**   5. AFP locking (OSX only),
22475**   6. Named POSIX semaphores (VXWorks only),
22476**   7. proxy locking. (OSX only)
22477**
22478** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22479** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22480** selection of the appropriate locking style based on the filesystem
22481** where the database is located.
22482*/
22483#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22484#  if defined(__APPLE__)
22485#    define SQLITE_ENABLE_LOCKING_STYLE 1
22486#  else
22487#    define SQLITE_ENABLE_LOCKING_STYLE 0
22488#  endif
22489#endif
22490
22491/*
22492** Define the OS_VXWORKS pre-processor macro to 1 if building on
22493** vxworks, or 0 otherwise.
22494*/
22495#ifndef OS_VXWORKS
22496#  if defined(__RTP__) || defined(_WRS_KERNEL)
22497#    define OS_VXWORKS 1
22498#  else
22499#    define OS_VXWORKS 0
22500#  endif
22501#endif
22502
22503/*
22504** These #defines should enable >2GB file support on Posix if the
22505** underlying operating system supports it.  If the OS lacks
22506** large file support, these should be no-ops.
22507**
22508** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22509** on the compiler command line.  This is necessary if you are compiling
22510** on a recent machine (ex: RedHat 7.2) but you want your code to work
22511** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22512** without this option, LFS is enable.  But LFS does not exist in the kernel
22513** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22514** portability you should omit LFS.
22515**
22516** The previous paragraph was written in 2005.  (This paragraph is written
22517** on 2008-11-28.) These days, all Linux kernels support large files, so
22518** you should probably leave LFS enabled.  But some embedded platforms might
22519** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22520*/
22521#ifndef SQLITE_DISABLE_LFS
22522# define _LARGE_FILE       1
22523# ifndef _FILE_OFFSET_BITS
22524#   define _FILE_OFFSET_BITS 64
22525# endif
22526# define _LARGEFILE_SOURCE 1
22527#endif
22528
22529/*
22530** standard include files.
22531*/
22532#include <sys/types.h>
22533#include <sys/stat.h>
22534#include <fcntl.h>
22535#include <unistd.h>
22536#include <sys/time.h>
22537#include <errno.h>
22538#include <sys/mman.h>
22539
22540#if SQLITE_ENABLE_LOCKING_STYLE
22541# include <sys/ioctl.h>
22542# if OS_VXWORKS
22543#  include <semaphore.h>
22544#  include <limits.h>
22545# else
22546#  include <sys/file.h>
22547#  include <sys/param.h>
22548# endif
22549#endif /* SQLITE_ENABLE_LOCKING_STYLE */
22550
22551#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22552# include <sys/mount.h>
22553#endif
22554
22555/*
22556** Allowed values of unixFile.fsFlags
22557*/
22558#define SQLITE_FSFLAGS_IS_MSDOS     0x1
22559
22560/*
22561** If we are to be thread-safe, include the pthreads header and define
22562** the SQLITE_UNIX_THREADS macro.
22563*/
22564#if SQLITE_THREADSAFE
22565# define SQLITE_UNIX_THREADS 1
22566#endif
22567
22568/*
22569** Default permissions when creating a new file
22570*/
22571#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22572# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22573#endif
22574
22575/*
22576 ** Default permissions when creating auto proxy dir
22577 */
22578#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22579# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22580#endif
22581
22582/*
22583** Maximum supported path-length.
22584*/
22585#define MAX_PATHNAME 512
22586
22587/*
22588** Only set the lastErrno if the error code is a real error and not
22589** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22590*/
22591#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22592
22593/* Forward references */
22594typedef struct unixShm unixShm;               /* Connection shared memory */
22595typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22596typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22597typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22598
22599/*
22600** Sometimes, after a file handle is closed by SQLite, the file descriptor
22601** cannot be closed immediately. In these cases, instances of the following
22602** structure are used to store the file descriptor while waiting for an
22603** opportunity to either close or reuse it.
22604*/
22605struct UnixUnusedFd {
22606  int fd;                   /* File descriptor to close */
22607  int flags;                /* Flags this file descriptor was opened with */
22608  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22609};
22610
22611/*
22612** The unixFile structure is subclass of sqlite3_file specific to the unix
22613** VFS implementations.
22614*/
22615typedef struct unixFile unixFile;
22616struct unixFile {
22617  sqlite3_io_methods const *pMethod;  /* Always the first entry */
22618  unixInodeInfo *pInode;              /* Info about locks on this inode */
22619  int h;                              /* The file descriptor */
22620  int dirfd;                          /* File descriptor for the directory */
22621  unsigned char eFileLock;            /* The type of lock held on this fd */
22622  int lastErrno;                      /* The unix errno from last I/O error */
22623  void *lockingContext;               /* Locking style specific state */
22624  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22625  int fileFlags;                      /* Miscellanous flags */
22626  const char *zPath;                  /* Name of the file */
22627  unixShm *pShm;                      /* Shared memory segment information */
22628  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22629#if SQLITE_ENABLE_LOCKING_STYLE
22630  int openFlags;                      /* The flags specified at open() */
22631#endif
22632#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22633  unsigned fsFlags;                   /* cached details from statfs() */
22634#endif
22635#if OS_VXWORKS
22636  int isDelete;                       /* Delete on close if true */
22637  struct vxworksFileId *pId;          /* Unique file ID */
22638#endif
22639#ifndef NDEBUG
22640  /* The next group of variables are used to track whether or not the
22641  ** transaction counter in bytes 24-27 of database files are updated
22642  ** whenever any part of the database changes.  An assertion fault will
22643  ** occur if a file is updated without also updating the transaction
22644  ** counter.  This test is made to avoid new problems similar to the
22645  ** one described by ticket #3584.
22646  */
22647  unsigned char transCntrChng;   /* True if the transaction counter changed */
22648  unsigned char dbUpdate;        /* True if any part of database file changed */
22649  unsigned char inNormalWrite;   /* True if in a normal write operation */
22650#endif
22651#ifdef SQLITE_TEST
22652  /* In test mode, increase the size of this structure a bit so that
22653  ** it is larger than the struct CrashFile defined in test6.c.
22654  */
22655  char aPadding[32];
22656#endif
22657};
22658
22659/*
22660** The following macros define bits in unixFile.fileFlags
22661*/
22662#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
22663
22664/*
22665** Include code that is common to all os_*.c files
22666*/
22667/************** Include os_common.h in the middle of os_unix.c ***************/
22668/************** Begin file os_common.h ***************************************/
22669/*
22670** 2004 May 22
22671**
22672** The author disclaims copyright to this source code.  In place of
22673** a legal notice, here is a blessing:
22674**
22675**    May you do good and not evil.
22676**    May you find forgiveness for yourself and forgive others.
22677**    May you share freely, never taking more than you give.
22678**
22679******************************************************************************
22680**
22681** This file contains macros and a little bit of code that is common to
22682** all of the platform-specific files (os_*.c) and is #included into those
22683** files.
22684**
22685** This file should be #included by the os_*.c files only.  It is not a
22686** general purpose header file.
22687*/
22688#ifndef _OS_COMMON_H_
22689#define _OS_COMMON_H_
22690
22691/*
22692** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22693** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22694** switch.  The following code should catch this problem at compile-time.
22695*/
22696#ifdef MEMORY_DEBUG
22697# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22698#endif
22699
22700#ifdef SQLITE_DEBUG
22701SQLITE_PRIVATE int sqlite3OSTrace = 0;
22702#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22703#else
22704#define OSTRACE(X)
22705#endif
22706
22707/*
22708** Macros for performance tracing.  Normally turned off.  Only works
22709** on i486 hardware.
22710*/
22711#ifdef SQLITE_PERFORMANCE_TRACE
22712
22713/*
22714** hwtime.h contains inline assembler code for implementing
22715** high-performance timing routines.
22716*/
22717/************** Include hwtime.h in the middle of os_common.h ****************/
22718/************** Begin file hwtime.h ******************************************/
22719/*
22720** 2008 May 27
22721**
22722** The author disclaims copyright to this source code.  In place of
22723** a legal notice, here is a blessing:
22724**
22725**    May you do good and not evil.
22726**    May you find forgiveness for yourself and forgive others.
22727**    May you share freely, never taking more than you give.
22728**
22729******************************************************************************
22730**
22731** This file contains inline asm code for retrieving "high-performance"
22732** counters for x86 class CPUs.
22733*/
22734#ifndef _HWTIME_H_
22735#define _HWTIME_H_
22736
22737/*
22738** The following routine only works on pentium-class (or newer) processors.
22739** It uses the RDTSC opcode to read the cycle count value out of the
22740** processor and returns that value.  This can be used for high-res
22741** profiling.
22742*/
22743#if (defined(__GNUC__) || defined(_MSC_VER)) && \
22744      (defined(i386) || defined(__i386__) || defined(_M_IX86))
22745
22746  #if defined(__GNUC__)
22747
22748  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22749     unsigned int lo, hi;
22750     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22751     return (sqlite_uint64)hi << 32 | lo;
22752  }
22753
22754  #elif defined(_MSC_VER)
22755
22756  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22757     __asm {
22758        rdtsc
22759        ret       ; return value at EDX:EAX
22760     }
22761  }
22762
22763  #endif
22764
22765#elif (defined(__GNUC__) && defined(__x86_64__))
22766
22767  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22768      unsigned long val;
22769      __asm__ __volatile__ ("rdtsc" : "=A" (val));
22770      return val;
22771  }
22772
22773#elif (defined(__GNUC__) && defined(__ppc__))
22774
22775  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22776      unsigned long long retval;
22777      unsigned long junk;
22778      __asm__ __volatile__ ("\n\
22779          1:      mftbu   %1\n\
22780                  mftb    %L0\n\
22781                  mftbu   %0\n\
22782                  cmpw    %0,%1\n\
22783                  bne     1b"
22784                  : "=r" (retval), "=r" (junk));
22785      return retval;
22786  }
22787
22788#else
22789
22790  #error Need implementation of sqlite3Hwtime() for your platform.
22791
22792  /*
22793  ** To compile without implementing sqlite3Hwtime() for your platform,
22794  ** you can remove the above #error and use the following
22795  ** stub function.  You will lose timing support for many
22796  ** of the debugging and testing utilities, but it should at
22797  ** least compile and run.
22798  */
22799SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22800
22801#endif
22802
22803#endif /* !defined(_HWTIME_H_) */
22804
22805/************** End of hwtime.h **********************************************/
22806/************** Continuing where we left off in os_common.h ******************/
22807
22808static sqlite_uint64 g_start;
22809static sqlite_uint64 g_elapsed;
22810#define TIMER_START       g_start=sqlite3Hwtime()
22811#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22812#define TIMER_ELAPSED     g_elapsed
22813#else
22814#define TIMER_START
22815#define TIMER_END
22816#define TIMER_ELAPSED     ((sqlite_uint64)0)
22817#endif
22818
22819/*
22820** If we compile with the SQLITE_TEST macro set, then the following block
22821** of code will give us the ability to simulate a disk I/O error.  This
22822** is used for testing the I/O recovery logic.
22823*/
22824#ifdef SQLITE_TEST
22825SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22826SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22827SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22828SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22829SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22830SQLITE_API int sqlite3_diskfull_pending = 0;
22831SQLITE_API int sqlite3_diskfull = 0;
22832#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22833#define SimulateIOError(CODE)  \
22834  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22835       || sqlite3_io_error_pending-- == 1 )  \
22836              { local_ioerr(); CODE; }
22837static void local_ioerr(){
22838  IOTRACE(("IOERR\n"));
22839  sqlite3_io_error_hit++;
22840  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22841}
22842#define SimulateDiskfullError(CODE) \
22843   if( sqlite3_diskfull_pending ){ \
22844     if( sqlite3_diskfull_pending == 1 ){ \
22845       local_ioerr(); \
22846       sqlite3_diskfull = 1; \
22847       sqlite3_io_error_hit = 1; \
22848       CODE; \
22849     }else{ \
22850       sqlite3_diskfull_pending--; \
22851     } \
22852   }
22853#else
22854#define SimulateIOErrorBenign(X)
22855#define SimulateIOError(A)
22856#define SimulateDiskfullError(A)
22857#endif
22858
22859/*
22860** When testing, keep a count of the number of open files.
22861*/
22862#ifdef SQLITE_TEST
22863SQLITE_API int sqlite3_open_file_count = 0;
22864#define OpenCounter(X)  sqlite3_open_file_count+=(X)
22865#else
22866#define OpenCounter(X)
22867#endif
22868
22869#endif /* !defined(_OS_COMMON_H_) */
22870
22871/************** End of os_common.h *******************************************/
22872/************** Continuing where we left off in os_unix.c ********************/
22873
22874/*
22875** Define various macros that are missing from some systems.
22876*/
22877#ifndef O_LARGEFILE
22878# define O_LARGEFILE 0
22879#endif
22880#ifdef SQLITE_DISABLE_LFS
22881# undef O_LARGEFILE
22882# define O_LARGEFILE 0
22883#endif
22884#ifndef O_NOFOLLOW
22885# define O_NOFOLLOW 0
22886#endif
22887#ifndef O_BINARY
22888# define O_BINARY 0
22889#endif
22890
22891/*
22892** The DJGPP compiler environment looks mostly like Unix, but it
22893** lacks the fcntl() system call.  So redefine fcntl() to be something
22894** that always succeeds.  This means that locking does not occur under
22895** DJGPP.  But it is DOS - what did you expect?
22896*/
22897#ifdef __DJGPP__
22898# define fcntl(A,B,C) 0
22899#endif
22900
22901/*
22902** The threadid macro resolves to the thread-id or to 0.  Used for
22903** testing and debugging only.
22904*/
22905#if SQLITE_THREADSAFE
22906#define threadid pthread_self()
22907#else
22908#define threadid 0
22909#endif
22910
22911
22912/*
22913** Helper functions to obtain and relinquish the global mutex. The
22914** global mutex is used to protect the unixInodeInfo and
22915** vxworksFileId objects used by this file, all of which may be
22916** shared by multiple threads.
22917**
22918** Function unixMutexHeld() is used to assert() that the global mutex
22919** is held when required. This function is only used as part of assert()
22920** statements. e.g.
22921**
22922**   unixEnterMutex()
22923**     assert( unixMutexHeld() );
22924**   unixEnterLeave()
22925*/
22926static void unixEnterMutex(void){
22927  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22928}
22929static void unixLeaveMutex(void){
22930  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22931}
22932#ifdef SQLITE_DEBUG
22933static int unixMutexHeld(void) {
22934  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22935}
22936#endif
22937
22938
22939#ifdef SQLITE_DEBUG
22940/*
22941** Helper function for printing out trace information from debugging
22942** binaries. This returns the string represetation of the supplied
22943** integer lock-type.
22944*/
22945static const char *azFileLock(int eFileLock){
22946  switch( eFileLock ){
22947    case NO_LOCK: return "NONE";
22948    case SHARED_LOCK: return "SHARED";
22949    case RESERVED_LOCK: return "RESERVED";
22950    case PENDING_LOCK: return "PENDING";
22951    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22952  }
22953  return "ERROR";
22954}
22955#endif
22956
22957#ifdef SQLITE_LOCK_TRACE
22958/*
22959** Print out information about all locking operations.
22960**
22961** This routine is used for troubleshooting locks on multithreaded
22962** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22963** command-line option on the compiler.  This code is normally
22964** turned off.
22965*/
22966static int lockTrace(int fd, int op, struct flock *p){
22967  char *zOpName, *zType;
22968  int s;
22969  int savedErrno;
22970  if( op==F_GETLK ){
22971    zOpName = "GETLK";
22972  }else if( op==F_SETLK ){
22973    zOpName = "SETLK";
22974  }else{
22975    s = fcntl(fd, op, p);
22976    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22977    return s;
22978  }
22979  if( p->l_type==F_RDLCK ){
22980    zType = "RDLCK";
22981  }else if( p->l_type==F_WRLCK ){
22982    zType = "WRLCK";
22983  }else if( p->l_type==F_UNLCK ){
22984    zType = "UNLCK";
22985  }else{
22986    assert( 0 );
22987  }
22988  assert( p->l_whence==SEEK_SET );
22989  s = fcntl(fd, op, p);
22990  savedErrno = errno;
22991  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22992     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22993     (int)p->l_pid, s);
22994  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22995    struct flock l2;
22996    l2 = *p;
22997    fcntl(fd, F_GETLK, &l2);
22998    if( l2.l_type==F_RDLCK ){
22999      zType = "RDLCK";
23000    }else if( l2.l_type==F_WRLCK ){
23001      zType = "WRLCK";
23002    }else if( l2.l_type==F_UNLCK ){
23003      zType = "UNLCK";
23004    }else{
23005      assert( 0 );
23006    }
23007    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23008       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23009  }
23010  errno = savedErrno;
23011  return s;
23012}
23013#define fcntl lockTrace
23014#endif /* SQLITE_LOCK_TRACE */
23015
23016
23017
23018/*
23019** This routine translates a standard POSIX errno code into something
23020** useful to the clients of the sqlite3 functions.  Specifically, it is
23021** intended to translate a variety of "try again" errors into SQLITE_BUSY
23022** and a variety of "please close the file descriptor NOW" errors into
23023** SQLITE_IOERR
23024**
23025** Errors during initialization of locks, or file system support for locks,
23026** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23027*/
23028static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23029  switch (posixError) {
23030  case 0:
23031    return SQLITE_OK;
23032
23033  case EAGAIN:
23034  case ETIMEDOUT:
23035  case EBUSY:
23036  case EINTR:
23037  case ENOLCK:
23038    /* random NFS retry error, unless during file system support
23039     * introspection, in which it actually means what it says */
23040    return SQLITE_BUSY;
23041
23042  case EACCES:
23043    /* EACCES is like EAGAIN during locking operations, but not any other time*/
23044    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
23045	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
23046	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23047	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23048      return SQLITE_BUSY;
23049    }
23050    /* else fall through */
23051  case EPERM:
23052    return SQLITE_PERM;
23053
23054  case EDEADLK:
23055    return SQLITE_IOERR_BLOCKED;
23056
23057#if EOPNOTSUPP!=ENOTSUP
23058  case EOPNOTSUPP:
23059    /* something went terribly awry, unless during file system support
23060     * introspection, in which it actually means what it says */
23061#endif
23062#ifdef ENOTSUP
23063  case ENOTSUP:
23064    /* invalid fd, unless during file system support introspection, in which
23065     * it actually means what it says */
23066#endif
23067  case EIO:
23068  case EBADF:
23069  case EINVAL:
23070  case ENOTCONN:
23071  case ENODEV:
23072  case ENXIO:
23073  case ENOENT:
23074  case ESTALE:
23075  case ENOSYS:
23076    /* these should force the client to close the file and reconnect */
23077
23078  default:
23079    return sqliteIOErr;
23080  }
23081}
23082
23083
23084
23085/******************************************************************************
23086****************** Begin Unique File ID Utility Used By VxWorks ***************
23087**
23088** On most versions of unix, we can get a unique ID for a file by concatenating
23089** the device number and the inode number.  But this does not work on VxWorks.
23090** On VxWorks, a unique file id must be based on the canonical filename.
23091**
23092** A pointer to an instance of the following structure can be used as a
23093** unique file ID in VxWorks.  Each instance of this structure contains
23094** a copy of the canonical filename.  There is also a reference count.
23095** The structure is reclaimed when the number of pointers to it drops to
23096** zero.
23097**
23098** There are never very many files open at one time and lookups are not
23099** a performance-critical path, so it is sufficient to put these
23100** structures on a linked list.
23101*/
23102struct vxworksFileId {
23103  struct vxworksFileId *pNext;  /* Next in a list of them all */
23104  int nRef;                     /* Number of references to this one */
23105  int nName;                    /* Length of the zCanonicalName[] string */
23106  char *zCanonicalName;         /* Canonical filename */
23107};
23108
23109#if OS_VXWORKS
23110/*
23111** All unique filenames are held on a linked list headed by this
23112** variable:
23113*/
23114static struct vxworksFileId *vxworksFileList = 0;
23115
23116/*
23117** Simplify a filename into its canonical form
23118** by making the following changes:
23119**
23120**  * removing any trailing and duplicate /
23121**  * convert /./ into just /
23122**  * convert /A/../ where A is any simple name into just /
23123**
23124** Changes are made in-place.  Return the new name length.
23125**
23126** The original filename is in z[0..n-1].  Return the number of
23127** characters in the simplified name.
23128*/
23129static int vxworksSimplifyName(char *z, int n){
23130  int i, j;
23131  while( n>1 && z[n-1]=='/' ){ n--; }
23132  for(i=j=0; i<n; i++){
23133    if( z[i]=='/' ){
23134      if( z[i+1]=='/' ) continue;
23135      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23136        i += 1;
23137        continue;
23138      }
23139      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23140        while( j>0 && z[j-1]!='/' ){ j--; }
23141        if( j>0 ){ j--; }
23142        i += 2;
23143        continue;
23144      }
23145    }
23146    z[j++] = z[i];
23147  }
23148  z[j] = 0;
23149  return j;
23150}
23151
23152/*
23153** Find a unique file ID for the given absolute pathname.  Return
23154** a pointer to the vxworksFileId object.  This pointer is the unique
23155** file ID.
23156**
23157** The nRef field of the vxworksFileId object is incremented before
23158** the object is returned.  A new vxworksFileId object is created
23159** and added to the global list if necessary.
23160**
23161** If a memory allocation error occurs, return NULL.
23162*/
23163static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23164  struct vxworksFileId *pNew;         /* search key and new file ID */
23165  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23166  int n;                              /* Length of zAbsoluteName string */
23167
23168  assert( zAbsoluteName[0]=='/' );
23169  n = (int)strlen(zAbsoluteName);
23170  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23171  if( pNew==0 ) return 0;
23172  pNew->zCanonicalName = (char*)&pNew[1];
23173  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23174  n = vxworksSimplifyName(pNew->zCanonicalName, n);
23175
23176  /* Search for an existing entry that matching the canonical name.
23177  ** If found, increment the reference count and return a pointer to
23178  ** the existing file ID.
23179  */
23180  unixEnterMutex();
23181  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23182    if( pCandidate->nName==n
23183     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23184    ){
23185       sqlite3_free(pNew);
23186       pCandidate->nRef++;
23187       unixLeaveMutex();
23188       return pCandidate;
23189    }
23190  }
23191
23192  /* No match was found.  We will make a new file ID */
23193  pNew->nRef = 1;
23194  pNew->nName = n;
23195  pNew->pNext = vxworksFileList;
23196  vxworksFileList = pNew;
23197  unixLeaveMutex();
23198  return pNew;
23199}
23200
23201/*
23202** Decrement the reference count on a vxworksFileId object.  Free
23203** the object when the reference count reaches zero.
23204*/
23205static void vxworksReleaseFileId(struct vxworksFileId *pId){
23206  unixEnterMutex();
23207  assert( pId->nRef>0 );
23208  pId->nRef--;
23209  if( pId->nRef==0 ){
23210    struct vxworksFileId **pp;
23211    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23212    assert( *pp==pId );
23213    *pp = pId->pNext;
23214    sqlite3_free(pId);
23215  }
23216  unixLeaveMutex();
23217}
23218#endif /* OS_VXWORKS */
23219/*************** End of Unique File ID Utility Used By VxWorks ****************
23220******************************************************************************/
23221
23222
23223/******************************************************************************
23224*************************** Posix Advisory Locking ****************************
23225**
23226** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23227** section 6.5.2.2 lines 483 through 490 specify that when a process
23228** sets or clears a lock, that operation overrides any prior locks set
23229** by the same process.  It does not explicitly say so, but this implies
23230** that it overrides locks set by the same process using a different
23231** file descriptor.  Consider this test case:
23232**
23233**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23234**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23235**
23236** Suppose ./file1 and ./file2 are really the same file (because
23237** one is a hard or symbolic link to the other) then if you set
23238** an exclusive lock on fd1, then try to get an exclusive lock
23239** on fd2, it works.  I would have expected the second lock to
23240** fail since there was already a lock on the file due to fd1.
23241** But not so.  Since both locks came from the same process, the
23242** second overrides the first, even though they were on different
23243** file descriptors opened on different file names.
23244**
23245** This means that we cannot use POSIX locks to synchronize file access
23246** among competing threads of the same process.  POSIX locks will work fine
23247** to synchronize access for threads in separate processes, but not
23248** threads within the same process.
23249**
23250** To work around the problem, SQLite has to manage file locks internally
23251** on its own.  Whenever a new database is opened, we have to find the
23252** specific inode of the database file (the inode is determined by the
23253** st_dev and st_ino fields of the stat structure that fstat() fills in)
23254** and check for locks already existing on that inode.  When locks are
23255** created or removed, we have to look at our own internal record of the
23256** locks to see if another thread has previously set a lock on that same
23257** inode.
23258**
23259** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23260** For VxWorks, we have to use the alternative unique ID system based on
23261** canonical filename and implemented in the previous division.)
23262**
23263** The sqlite3_file structure for POSIX is no longer just an integer file
23264** descriptor.  It is now a structure that holds the integer file
23265** descriptor and a pointer to a structure that describes the internal
23266** locks on the corresponding inode.  There is one locking structure
23267** per inode, so if the same inode is opened twice, both unixFile structures
23268** point to the same locking structure.  The locking structure keeps
23269** a reference count (so we will know when to delete it) and a "cnt"
23270** field that tells us its internal lock status.  cnt==0 means the
23271** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23272** cnt>0 means there are cnt shared locks on the file.
23273**
23274** Any attempt to lock or unlock a file first checks the locking
23275** structure.  The fcntl() system call is only invoked to set a
23276** POSIX lock if the internal lock structure transitions between
23277** a locked and an unlocked state.
23278**
23279** But wait:  there are yet more problems with POSIX advisory locks.
23280**
23281** If you close a file descriptor that points to a file that has locks,
23282** all locks on that file that are owned by the current process are
23283** released.  To work around this problem, each unixInodeInfo object
23284** maintains a count of the number of pending locks on tha inode.
23285** When an attempt is made to close an unixFile, if there are
23286** other unixFile open on the same inode that are holding locks, the call
23287** to close() the file descriptor is deferred until all of the locks clear.
23288** The unixInodeInfo structure keeps a list of file descriptors that need to
23289** be closed and that list is walked (and cleared) when the last lock
23290** clears.
23291**
23292** Yet another problem:  LinuxThreads do not play well with posix locks.
23293**
23294** Many older versions of linux use the LinuxThreads library which is
23295** not posix compliant.  Under LinuxThreads, a lock created by thread
23296** A cannot be modified or overridden by a different thread B.
23297** Only thread A can modify the lock.  Locking behavior is correct
23298** if the appliation uses the newer Native Posix Thread Library (NPTL)
23299** on linux - with NPTL a lock created by thread A can override locks
23300** in thread B.  But there is no way to know at compile-time which
23301** threading library is being used.  So there is no way to know at
23302** compile-time whether or not thread A can override locks on thread B.
23303** One has to do a run-time check to discover the behavior of the
23304** current process.
23305**
23306** SQLite used to support LinuxThreads.  But support for LinuxThreads
23307** was dropped beginning with version 3.7.0.  SQLite will still work with
23308** LinuxThreads provided that (1) there is no more than one connection
23309** per database file in the same process and (2) database connections
23310** do not move across threads.
23311*/
23312
23313/*
23314** An instance of the following structure serves as the key used
23315** to locate a particular unixInodeInfo object.
23316*/
23317struct unixFileId {
23318  dev_t dev;                  /* Device number */
23319#if OS_VXWORKS
23320  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23321#else
23322  ino_t ino;                  /* Inode number */
23323#endif
23324};
23325
23326/*
23327** An instance of the following structure is allocated for each open
23328** inode.  Or, on LinuxThreads, there is one of these structures for
23329** each inode opened by each thread.
23330**
23331** A single inode can have multiple file descriptors, so each unixFile
23332** structure contains a pointer to an instance of this object and this
23333** object keeps a count of the number of unixFile pointing to it.
23334*/
23335struct unixInodeInfo {
23336  struct unixFileId fileId;       /* The lookup key */
23337  int nShared;                    /* Number of SHARED locks held */
23338  int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23339  int nRef;                       /* Number of pointers to this structure */
23340  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23341  int nLock;                      /* Number of outstanding file locks */
23342  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23343  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23344  unixInodeInfo *pPrev;           /*    .... doubly linked */
23345#if defined(SQLITE_ENABLE_LOCKING_STYLE)
23346  unsigned long long sharedByte;  /* for AFP simulated shared lock */
23347#endif
23348#if OS_VXWORKS
23349  sem_t *pSem;                    /* Named POSIX semaphore */
23350  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23351#endif
23352};
23353
23354/*
23355** A lists of all unixInodeInfo objects.
23356*/
23357static unixInodeInfo *inodeList = 0;
23358
23359/*
23360** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23361** If all such file descriptors are closed without error, the list is
23362** cleared and SQLITE_OK returned.
23363**
23364** Otherwise, if an error occurs, then successfully closed file descriptor
23365** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
23366** not deleted and SQLITE_IOERR_CLOSE returned.
23367*/
23368static int closePendingFds(unixFile *pFile){
23369  int rc = SQLITE_OK;
23370  unixInodeInfo *pInode = pFile->pInode;
23371  UnixUnusedFd *pError = 0;
23372  UnixUnusedFd *p;
23373  UnixUnusedFd *pNext;
23374  for(p=pInode->pUnused; p; p=pNext){
23375    pNext = p->pNext;
23376    if( close(p->fd) ){
23377      pFile->lastErrno = errno;
23378      rc = SQLITE_IOERR_CLOSE;
23379      p->pNext = pError;
23380      pError = p;
23381    }else{
23382      sqlite3_free(p);
23383    }
23384  }
23385  pInode->pUnused = pError;
23386  return rc;
23387}
23388
23389/*
23390** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23391**
23392** The mutex entered using the unixEnterMutex() function must be held
23393** when this function is called.
23394*/
23395static void releaseInodeInfo(unixFile *pFile){
23396  unixInodeInfo *pInode = pFile->pInode;
23397  assert( unixMutexHeld() );
23398  if( pInode ){
23399    pInode->nRef--;
23400    if( pInode->nRef==0 ){
23401      assert( pInode->pShmNode==0 );
23402      closePendingFds(pFile);
23403      if( pInode->pPrev ){
23404        assert( pInode->pPrev->pNext==pInode );
23405        pInode->pPrev->pNext = pInode->pNext;
23406      }else{
23407        assert( inodeList==pInode );
23408        inodeList = pInode->pNext;
23409      }
23410      if( pInode->pNext ){
23411        assert( pInode->pNext->pPrev==pInode );
23412        pInode->pNext->pPrev = pInode->pPrev;
23413      }
23414      sqlite3_free(pInode);
23415    }
23416  }
23417}
23418
23419/*
23420** Given a file descriptor, locate the unixInodeInfo object that
23421** describes that file descriptor.  Create a new one if necessary.  The
23422** return value might be uninitialized if an error occurs.
23423**
23424** The mutex entered using the unixEnterMutex() function must be held
23425** when this function is called.
23426**
23427** Return an appropriate error code.
23428*/
23429static int findInodeInfo(
23430  unixFile *pFile,               /* Unix file with file desc used in the key */
23431  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23432){
23433  int rc;                        /* System call return code */
23434  int fd;                        /* The file descriptor for pFile */
23435  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23436  struct stat statbuf;           /* Low-level file information */
23437  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23438
23439  assert( unixMutexHeld() );
23440
23441  /* Get low-level information about the file that we can used to
23442  ** create a unique name for the file.
23443  */
23444  fd = pFile->h;
23445  rc = fstat(fd, &statbuf);
23446  if( rc!=0 ){
23447    pFile->lastErrno = errno;
23448#ifdef EOVERFLOW
23449    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23450#endif
23451    return SQLITE_IOERR;
23452  }
23453
23454#ifdef __APPLE__
23455  /* On OS X on an msdos filesystem, the inode number is reported
23456  ** incorrectly for zero-size files.  See ticket #3260.  To work
23457  ** around this problem (we consider it a bug in OS X, not SQLite)
23458  ** we always increase the file size to 1 by writing a single byte
23459  ** prior to accessing the inode number.  The one byte written is
23460  ** an ASCII 'S' character which also happens to be the first byte
23461  ** in the header of every SQLite database.  In this way, if there
23462  ** is a race condition such that another thread has already populated
23463  ** the first page of the database, no damage is done.
23464  */
23465  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23466    rc = write(fd, "S", 1);
23467    if( rc!=1 ){
23468      pFile->lastErrno = errno;
23469      return SQLITE_IOERR;
23470    }
23471    rc = fstat(fd, &statbuf);
23472    if( rc!=0 ){
23473      pFile->lastErrno = errno;
23474      return SQLITE_IOERR;
23475    }
23476  }
23477#endif
23478
23479  memset(&fileId, 0, sizeof(fileId));
23480  fileId.dev = statbuf.st_dev;
23481#if OS_VXWORKS
23482  fileId.pId = pFile->pId;
23483#else
23484  fileId.ino = statbuf.st_ino;
23485#endif
23486  pInode = inodeList;
23487  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23488    pInode = pInode->pNext;
23489  }
23490  if( pInode==0 ){
23491    pInode = sqlite3_malloc( sizeof(*pInode) );
23492    if( pInode==0 ){
23493      return SQLITE_NOMEM;
23494    }
23495    memset(pInode, 0, sizeof(*pInode));
23496    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23497    pInode->nRef = 1;
23498    pInode->pNext = inodeList;
23499    pInode->pPrev = 0;
23500    if( inodeList ) inodeList->pPrev = pInode;
23501    inodeList = pInode;
23502  }else{
23503    pInode->nRef++;
23504  }
23505  *ppInode = pInode;
23506  return SQLITE_OK;
23507}
23508
23509
23510/*
23511** This routine checks if there is a RESERVED lock held on the specified
23512** file by this or any other process. If such a lock is held, set *pResOut
23513** to a non-zero value otherwise *pResOut is set to zero.  The return value
23514** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23515*/
23516static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23517  int rc = SQLITE_OK;
23518  int reserved = 0;
23519  unixFile *pFile = (unixFile*)id;
23520
23521  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23522
23523  assert( pFile );
23524  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23525
23526  /* Check if a thread in this process holds such a lock */
23527  if( pFile->pInode->eFileLock>SHARED_LOCK ){
23528    reserved = 1;
23529  }
23530
23531  /* Otherwise see if some other process holds it.
23532  */
23533#ifndef __DJGPP__
23534  if( !reserved ){
23535    struct flock lock;
23536    lock.l_whence = SEEK_SET;
23537    lock.l_start = RESERVED_BYTE;
23538    lock.l_len = 1;
23539    lock.l_type = F_WRLCK;
23540    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23541      int tErrno = errno;
23542      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23543      pFile->lastErrno = tErrno;
23544    } else if( lock.l_type!=F_UNLCK ){
23545      reserved = 1;
23546    }
23547  }
23548#endif
23549
23550  unixLeaveMutex();
23551  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23552
23553  *pResOut = reserved;
23554  return rc;
23555}
23556
23557/*
23558** Lock the file with the lock specified by parameter eFileLock - one
23559** of the following:
23560**
23561**     (1) SHARED_LOCK
23562**     (2) RESERVED_LOCK
23563**     (3) PENDING_LOCK
23564**     (4) EXCLUSIVE_LOCK
23565**
23566** Sometimes when requesting one lock state, additional lock states
23567** are inserted in between.  The locking might fail on one of the later
23568** transitions leaving the lock state different from what it started but
23569** still short of its goal.  The following chart shows the allowed
23570** transitions and the inserted intermediate states:
23571**
23572**    UNLOCKED -> SHARED
23573**    SHARED -> RESERVED
23574**    SHARED -> (PENDING) -> EXCLUSIVE
23575**    RESERVED -> (PENDING) -> EXCLUSIVE
23576**    PENDING -> EXCLUSIVE
23577**
23578** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23579** routine to lower a locking level.
23580*/
23581static int unixLock(sqlite3_file *id, int eFileLock){
23582  /* The following describes the implementation of the various locks and
23583  ** lock transitions in terms of the POSIX advisory shared and exclusive
23584  ** lock primitives (called read-locks and write-locks below, to avoid
23585  ** confusion with SQLite lock names). The algorithms are complicated
23586  ** slightly in order to be compatible with windows systems simultaneously
23587  ** accessing the same database file, in case that is ever required.
23588  **
23589  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23590  ** byte', each single bytes at well known offsets, and the 'shared byte
23591  ** range', a range of 510 bytes at a well known offset.
23592  **
23593  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23594  ** byte'.  If this is successful, a random byte from the 'shared byte
23595  ** range' is read-locked and the lock on the 'pending byte' released.
23596  **
23597  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23598  ** A RESERVED lock is implemented by grabbing a write-lock on the
23599  ** 'reserved byte'.
23600  **
23601  ** A process may only obtain a PENDING lock after it has obtained a
23602  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23603  ** on the 'pending byte'. This ensures that no new SHARED locks can be
23604  ** obtained, but existing SHARED locks are allowed to persist. A process
23605  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23606  ** This property is used by the algorithm for rolling back a journal file
23607  ** after a crash.
23608  **
23609  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23610  ** implemented by obtaining a write-lock on the entire 'shared byte
23611  ** range'. Since all other locks require a read-lock on one of the bytes
23612  ** within this range, this ensures that no other locks are held on the
23613  ** database.
23614  **
23615  ** The reason a single byte cannot be used instead of the 'shared byte
23616  ** range' is that some versions of windows do not support read-locks. By
23617  ** locking a random byte from a range, concurrent SHARED locks may exist
23618  ** even if the locking primitive used is always a write-lock.
23619  */
23620  int rc = SQLITE_OK;
23621  unixFile *pFile = (unixFile*)id;
23622  unixInodeInfo *pInode = pFile->pInode;
23623  struct flock lock;
23624  int s = 0;
23625  int tErrno = 0;
23626
23627  assert( pFile );
23628  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23629      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
23630      azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
23631
23632  /* If there is already a lock of this type or more restrictive on the
23633  ** unixFile, do nothing. Don't use the end_lock: exit path, as
23634  ** unixEnterMutex() hasn't been called yet.
23635  */
23636  if( pFile->eFileLock>=eFileLock ){
23637    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23638            azFileLock(eFileLock)));
23639    return SQLITE_OK;
23640  }
23641
23642  /* Make sure the locking sequence is correct.
23643  **  (1) We never move from unlocked to anything higher than shared lock.
23644  **  (2) SQLite never explicitly requests a pendig lock.
23645  **  (3) A shared lock is always held when a reserve lock is requested.
23646  */
23647  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
23648  assert( eFileLock!=PENDING_LOCK );
23649  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
23650
23651  /* This mutex is needed because pFile->pInode is shared across threads
23652  */
23653  unixEnterMutex();
23654  pInode = pFile->pInode;
23655
23656  /* If some thread using this PID has a lock via a different unixFile*
23657  ** handle that precludes the requested lock, return BUSY.
23658  */
23659  if( (pFile->eFileLock!=pInode->eFileLock &&
23660          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
23661  ){
23662    rc = SQLITE_BUSY;
23663    goto end_lock;
23664  }
23665
23666  /* If a SHARED lock is requested, and some thread using this PID already
23667  ** has a SHARED or RESERVED lock, then increment reference counts and
23668  ** return SQLITE_OK.
23669  */
23670  if( eFileLock==SHARED_LOCK &&
23671      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
23672    assert( eFileLock==SHARED_LOCK );
23673    assert( pFile->eFileLock==0 );
23674    assert( pInode->nShared>0 );
23675    pFile->eFileLock = SHARED_LOCK;
23676    pInode->nShared++;
23677    pInode->nLock++;
23678    goto end_lock;
23679  }
23680
23681
23682  /* A PENDING lock is needed before acquiring a SHARED lock and before
23683  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23684  ** be released.
23685  */
23686  lock.l_len = 1L;
23687  lock.l_whence = SEEK_SET;
23688  if( eFileLock==SHARED_LOCK
23689      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
23690  ){
23691    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
23692    lock.l_start = PENDING_BYTE;
23693    s = fcntl(pFile->h, F_SETLK, &lock);
23694    if( s==(-1) ){
23695      tErrno = errno;
23696      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23697      if( IS_LOCK_ERROR(rc) ){
23698        pFile->lastErrno = tErrno;
23699      }
23700      goto end_lock;
23701    }
23702  }
23703
23704
23705  /* If control gets to this point, then actually go ahead and make
23706  ** operating system calls for the specified lock.
23707  */
23708  if( eFileLock==SHARED_LOCK ){
23709    assert( pInode->nShared==0 );
23710    assert( pInode->eFileLock==0 );
23711
23712    /* Now get the read-lock */
23713    lock.l_start = SHARED_FIRST;
23714    lock.l_len = SHARED_SIZE;
23715    if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23716      tErrno = errno;
23717    }
23718    /* Drop the temporary PENDING lock */
23719    lock.l_start = PENDING_BYTE;
23720    lock.l_len = 1L;
23721    lock.l_type = F_UNLCK;
23722    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23723      if( s != -1 ){
23724        /* This could happen with a network mount */
23725        tErrno = errno;
23726        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23727        if( IS_LOCK_ERROR(rc) ){
23728          pFile->lastErrno = tErrno;
23729        }
23730        goto end_lock;
23731      }
23732    }
23733    if( s==(-1) ){
23734      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23735      if( IS_LOCK_ERROR(rc) ){
23736        pFile->lastErrno = tErrno;
23737      }
23738    }else{
23739      pFile->eFileLock = SHARED_LOCK;
23740      pInode->nLock++;
23741      pInode->nShared = 1;
23742    }
23743  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
23744    /* We are trying for an exclusive lock but another thread in this
23745    ** same process is still holding a shared lock. */
23746    rc = SQLITE_BUSY;
23747  }else{
23748    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23749    ** assumed that there is a SHARED or greater lock on the file
23750    ** already.
23751    */
23752    assert( 0!=pFile->eFileLock );
23753    lock.l_type = F_WRLCK;
23754    switch( eFileLock ){
23755      case RESERVED_LOCK:
23756        lock.l_start = RESERVED_BYTE;
23757        break;
23758      case EXCLUSIVE_LOCK:
23759        lock.l_start = SHARED_FIRST;
23760        lock.l_len = SHARED_SIZE;
23761        break;
23762      default:
23763        assert(0);
23764    }
23765    s = fcntl(pFile->h, F_SETLK, &lock);
23766    if( s==(-1) ){
23767      tErrno = errno;
23768      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23769      if( IS_LOCK_ERROR(rc) ){
23770        pFile->lastErrno = tErrno;
23771      }
23772    }
23773  }
23774
23775
23776#ifndef NDEBUG
23777  /* Set up the transaction-counter change checking flags when
23778  ** transitioning from a SHARED to a RESERVED lock.  The change
23779  ** from SHARED to RESERVED marks the beginning of a normal
23780  ** write operation (not a hot journal rollback).
23781  */
23782  if( rc==SQLITE_OK
23783   && pFile->eFileLock<=SHARED_LOCK
23784   && eFileLock==RESERVED_LOCK
23785  ){
23786    pFile->transCntrChng = 0;
23787    pFile->dbUpdate = 0;
23788    pFile->inNormalWrite = 1;
23789  }
23790#endif
23791
23792
23793  if( rc==SQLITE_OK ){
23794    pFile->eFileLock = eFileLock;
23795    pInode->eFileLock = eFileLock;
23796  }else if( eFileLock==EXCLUSIVE_LOCK ){
23797    pFile->eFileLock = PENDING_LOCK;
23798    pInode->eFileLock = PENDING_LOCK;
23799  }
23800
23801end_lock:
23802  unixLeaveMutex();
23803  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
23804      rc==SQLITE_OK ? "ok" : "failed"));
23805  return rc;
23806}
23807
23808/*
23809** Add the file descriptor used by file handle pFile to the corresponding
23810** pUnused list.
23811*/
23812static void setPendingFd(unixFile *pFile){
23813  unixInodeInfo *pInode = pFile->pInode;
23814  UnixUnusedFd *p = pFile->pUnused;
23815  p->pNext = pInode->pUnused;
23816  pInode->pUnused = p;
23817  pFile->h = -1;
23818  pFile->pUnused = 0;
23819}
23820
23821/*
23822** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
23823** must be either NO_LOCK or SHARED_LOCK.
23824**
23825** If the locking level of the file descriptor is already at or below
23826** the requested locking level, this routine is a no-op.
23827**
23828** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
23829** the byte range is divided into 2 parts and the first part is unlocked then
23830** set to a read lock, then the other part is simply unlocked.  This works
23831** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
23832** remove the write lock on a region when a read lock is set.
23833*/
23834static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
23835  unixFile *pFile = (unixFile*)id;
23836  unixInodeInfo *pInode;
23837  struct flock lock;
23838  int rc = SQLITE_OK;
23839  int h;
23840  int tErrno;                      /* Error code from system call errors */
23841
23842  assert( pFile );
23843  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
23844      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
23845      getpid()));
23846
23847  assert( eFileLock<=SHARED_LOCK );
23848  if( pFile->eFileLock<=eFileLock ){
23849    return SQLITE_OK;
23850  }
23851  unixEnterMutex();
23852  h = pFile->h;
23853  pInode = pFile->pInode;
23854  assert( pInode->nShared!=0 );
23855  if( pFile->eFileLock>SHARED_LOCK ){
23856    assert( pInode->eFileLock==pFile->eFileLock );
23857    SimulateIOErrorBenign(1);
23858    SimulateIOError( h=(-1) )
23859    SimulateIOErrorBenign(0);
23860
23861#ifndef NDEBUG
23862    /* When reducing a lock such that other processes can start
23863    ** reading the database file again, make sure that the
23864    ** transaction counter was updated if any part of the database
23865    ** file changed.  If the transaction counter is not updated,
23866    ** other connections to the same file might not realize that
23867    ** the file has changed and hence might not know to flush their
23868    ** cache.  The use of a stale cache can lead to database corruption.
23869    */
23870#if 0
23871    assert( pFile->inNormalWrite==0
23872         || pFile->dbUpdate==0
23873         || pFile->transCntrChng==1 );
23874#endif
23875    pFile->inNormalWrite = 0;
23876#endif
23877
23878    /* downgrading to a shared lock on NFS involves clearing the write lock
23879    ** before establishing the readlock - to avoid a race condition we downgrade
23880    ** the lock in 2 blocks, so that part of the range will be covered by a
23881    ** write lock until the rest is covered by a read lock:
23882    **  1:   [WWWWW]
23883    **  2:   [....W]
23884    **  3:   [RRRRW]
23885    **  4:   [RRRR.]
23886    */
23887    if( eFileLock==SHARED_LOCK ){
23888      if( handleNFSUnlock ){
23889        off_t divSize = SHARED_SIZE - 1;
23890
23891        lock.l_type = F_UNLCK;
23892        lock.l_whence = SEEK_SET;
23893        lock.l_start = SHARED_FIRST;
23894        lock.l_len = divSize;
23895        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23896          tErrno = errno;
23897          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23898          if( IS_LOCK_ERROR(rc) ){
23899            pFile->lastErrno = tErrno;
23900          }
23901          goto end_unlock;
23902        }
23903        lock.l_type = F_RDLCK;
23904        lock.l_whence = SEEK_SET;
23905        lock.l_start = SHARED_FIRST;
23906        lock.l_len = divSize;
23907        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23908          tErrno = errno;
23909          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23910          if( IS_LOCK_ERROR(rc) ){
23911            pFile->lastErrno = tErrno;
23912          }
23913          goto end_unlock;
23914        }
23915        lock.l_type = F_UNLCK;
23916        lock.l_whence = SEEK_SET;
23917        lock.l_start = SHARED_FIRST+divSize;
23918        lock.l_len = SHARED_SIZE-divSize;
23919        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23920          tErrno = errno;
23921          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23922          if( IS_LOCK_ERROR(rc) ){
23923            pFile->lastErrno = tErrno;
23924          }
23925          goto end_unlock;
23926        }
23927      }else{
23928        lock.l_type = F_RDLCK;
23929        lock.l_whence = SEEK_SET;
23930        lock.l_start = SHARED_FIRST;
23931        lock.l_len = SHARED_SIZE;
23932        if( fcntl(h, F_SETLK, &lock)==(-1) ){
23933          tErrno = errno;
23934          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23935          if( IS_LOCK_ERROR(rc) ){
23936            pFile->lastErrno = tErrno;
23937          }
23938          goto end_unlock;
23939        }
23940      }
23941    }
23942    lock.l_type = F_UNLCK;
23943    lock.l_whence = SEEK_SET;
23944    lock.l_start = PENDING_BYTE;
23945    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23946    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23947      pInode->eFileLock = SHARED_LOCK;
23948    }else{
23949      tErrno = errno;
23950      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23951      if( IS_LOCK_ERROR(rc) ){
23952        pFile->lastErrno = tErrno;
23953      }
23954      goto end_unlock;
23955    }
23956  }
23957  if( eFileLock==NO_LOCK ){
23958    /* Decrement the shared lock counter.  Release the lock using an
23959    ** OS call only when all threads in this same process have released
23960    ** the lock.
23961    */
23962    pInode->nShared--;
23963    if( pInode->nShared==0 ){
23964      lock.l_type = F_UNLCK;
23965      lock.l_whence = SEEK_SET;
23966      lock.l_start = lock.l_len = 0L;
23967      SimulateIOErrorBenign(1);
23968      SimulateIOError( h=(-1) )
23969      SimulateIOErrorBenign(0);
23970      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23971        pInode->eFileLock = NO_LOCK;
23972      }else{
23973        tErrno = errno;
23974        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23975        if( IS_LOCK_ERROR(rc) ){
23976          pFile->lastErrno = tErrno;
23977        }
23978        pInode->eFileLock = NO_LOCK;
23979        pFile->eFileLock = NO_LOCK;
23980      }
23981    }
23982
23983    /* Decrement the count of locks against this same file.  When the
23984    ** count reaches zero, close any other file descriptors whose close
23985    ** was deferred because of outstanding locks.
23986    */
23987    pInode->nLock--;
23988    assert( pInode->nLock>=0 );
23989    if( pInode->nLock==0 ){
23990      int rc2 = closePendingFds(pFile);
23991      if( rc==SQLITE_OK ){
23992        rc = rc2;
23993      }
23994    }
23995  }
23996
23997end_unlock:
23998  unixLeaveMutex();
23999  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24000  return rc;
24001}
24002
24003/*
24004** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24005** must be either NO_LOCK or SHARED_LOCK.
24006**
24007** If the locking level of the file descriptor is already at or below
24008** the requested locking level, this routine is a no-op.
24009*/
24010static int unixUnlock(sqlite3_file *id, int eFileLock){
24011  return _posixUnlock(id, eFileLock, 0);
24012}
24013
24014/*
24015** This function performs the parts of the "close file" operation
24016** common to all locking schemes. It closes the directory and file
24017** handles, if they are valid, and sets all fields of the unixFile
24018** structure to 0.
24019**
24020** It is *not* necessary to hold the mutex when this routine is called,
24021** even on VxWorks.  A mutex will be acquired on VxWorks by the
24022** vxworksReleaseFileId() routine.
24023*/
24024static int closeUnixFile(sqlite3_file *id){
24025  unixFile *pFile = (unixFile*)id;
24026  if( pFile ){
24027    if( pFile->dirfd>=0 ){
24028      int err = close(pFile->dirfd);
24029      if( err ){
24030        pFile->lastErrno = errno;
24031        return SQLITE_IOERR_DIR_CLOSE;
24032      }else{
24033        pFile->dirfd=-1;
24034      }
24035    }
24036    if( pFile->h>=0 ){
24037      int err = close(pFile->h);
24038      if( err ){
24039        pFile->lastErrno = errno;
24040        return SQLITE_IOERR_CLOSE;
24041      }
24042    }
24043#if OS_VXWORKS
24044    if( pFile->pId ){
24045      if( pFile->isDelete ){
24046        unlink(pFile->pId->zCanonicalName);
24047      }
24048      vxworksReleaseFileId(pFile->pId);
24049      pFile->pId = 0;
24050    }
24051#endif
24052    OSTRACE(("CLOSE   %-3d\n", pFile->h));
24053    OpenCounter(-1);
24054    sqlite3_free(pFile->pUnused);
24055    memset(pFile, 0, sizeof(unixFile));
24056  }
24057  return SQLITE_OK;
24058}
24059
24060/*
24061** Close a file.
24062*/
24063static int unixClose(sqlite3_file *id){
24064  int rc = SQLITE_OK;
24065  if( id ){
24066    unixFile *pFile = (unixFile *)id;
24067    unixUnlock(id, NO_LOCK);
24068    unixEnterMutex();
24069    if( pFile->pInode && pFile->pInode->nLock ){
24070      /* If there are outstanding locks, do not actually close the file just
24071      ** yet because that would clear those locks.  Instead, add the file
24072      ** descriptor to pInode->pUnused list.  It will be automatically closed
24073      ** when the last lock is cleared.
24074      */
24075      setPendingFd(pFile);
24076    }
24077    releaseInodeInfo(pFile);
24078    rc = closeUnixFile(id);
24079    unixLeaveMutex();
24080  }
24081  return rc;
24082}
24083
24084/************** End of the posix advisory lock implementation *****************
24085******************************************************************************/
24086
24087/******************************************************************************
24088****************************** No-op Locking **********************************
24089**
24090** Of the various locking implementations available, this is by far the
24091** simplest:  locking is ignored.  No attempt is made to lock the database
24092** file for reading or writing.
24093**
24094** This locking mode is appropriate for use on read-only databases
24095** (ex: databases that are burned into CD-ROM, for example.)  It can
24096** also be used if the application employs some external mechanism to
24097** prevent simultaneous access of the same database by two or more
24098** database connections.  But there is a serious risk of database
24099** corruption if this locking mode is used in situations where multiple
24100** database connections are accessing the same database file at the same
24101** time and one or more of those connections are writing.
24102*/
24103
24104static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24105  UNUSED_PARAMETER(NotUsed);
24106  *pResOut = 0;
24107  return SQLITE_OK;
24108}
24109static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24110  UNUSED_PARAMETER2(NotUsed, NotUsed2);
24111  return SQLITE_OK;
24112}
24113static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24114  UNUSED_PARAMETER2(NotUsed, NotUsed2);
24115  return SQLITE_OK;
24116}
24117
24118/*
24119** Close the file.
24120*/
24121static int nolockClose(sqlite3_file *id) {
24122  return closeUnixFile(id);
24123}
24124
24125/******************* End of the no-op lock implementation *********************
24126******************************************************************************/
24127
24128/******************************************************************************
24129************************* Begin dot-file Locking ******************************
24130**
24131** The dotfile locking implementation uses the existance of separate lock
24132** files in order to control access to the database.  This works on just
24133** about every filesystem imaginable.  But there are serious downsides:
24134**
24135**    (1)  There is zero concurrency.  A single reader blocks all other
24136**         connections from reading or writing the database.
24137**
24138**    (2)  An application crash or power loss can leave stale lock files
24139**         sitting around that need to be cleared manually.
24140**
24141** Nevertheless, a dotlock is an appropriate locking mode for use if no
24142** other locking strategy is available.
24143**
24144** Dotfile locking works by creating a file in the same directory as the
24145** database and with the same name but with a ".lock" extension added.
24146** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
24147** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24148*/
24149
24150/*
24151** The file suffix added to the data base filename in order to create the
24152** lock file.
24153*/
24154#define DOTLOCK_SUFFIX ".lock"
24155
24156/*
24157** This routine checks if there is a RESERVED lock held on the specified
24158** file by this or any other process. If such a lock is held, set *pResOut
24159** to a non-zero value otherwise *pResOut is set to zero.  The return value
24160** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24161**
24162** In dotfile locking, either a lock exists or it does not.  So in this
24163** variation of CheckReservedLock(), *pResOut is set to true if any lock
24164** is held on the file and false if the file is unlocked.
24165*/
24166static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24167  int rc = SQLITE_OK;
24168  int reserved = 0;
24169  unixFile *pFile = (unixFile*)id;
24170
24171  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24172
24173  assert( pFile );
24174
24175  /* Check if a thread in this process holds such a lock */
24176  if( pFile->eFileLock>SHARED_LOCK ){
24177    /* Either this connection or some other connection in the same process
24178    ** holds a lock on the file.  No need to check further. */
24179    reserved = 1;
24180  }else{
24181    /* The lock is held if and only if the lockfile exists */
24182    const char *zLockFile = (const char*)pFile->lockingContext;
24183    reserved = access(zLockFile, 0)==0;
24184  }
24185  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24186  *pResOut = reserved;
24187  return rc;
24188}
24189
24190/*
24191** Lock the file with the lock specified by parameter eFileLock - one
24192** of the following:
24193**
24194**     (1) SHARED_LOCK
24195**     (2) RESERVED_LOCK
24196**     (3) PENDING_LOCK
24197**     (4) EXCLUSIVE_LOCK
24198**
24199** Sometimes when requesting one lock state, additional lock states
24200** are inserted in between.  The locking might fail on one of the later
24201** transitions leaving the lock state different from what it started but
24202** still short of its goal.  The following chart shows the allowed
24203** transitions and the inserted intermediate states:
24204**
24205**    UNLOCKED -> SHARED
24206**    SHARED -> RESERVED
24207**    SHARED -> (PENDING) -> EXCLUSIVE
24208**    RESERVED -> (PENDING) -> EXCLUSIVE
24209**    PENDING -> EXCLUSIVE
24210**
24211** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24212** routine to lower a locking level.
24213**
24214** With dotfile locking, we really only support state (4): EXCLUSIVE.
24215** But we track the other locking levels internally.
24216*/
24217static int dotlockLock(sqlite3_file *id, int eFileLock) {
24218  unixFile *pFile = (unixFile*)id;
24219  int fd;
24220  char *zLockFile = (char *)pFile->lockingContext;
24221  int rc = SQLITE_OK;
24222
24223
24224  /* If we have any lock, then the lock file already exists.  All we have
24225  ** to do is adjust our internal record of the lock level.
24226  */
24227  if( pFile->eFileLock > NO_LOCK ){
24228    pFile->eFileLock = eFileLock;
24229#if !OS_VXWORKS
24230    /* Always update the timestamp on the old file */
24231    utimes(zLockFile, NULL);
24232#endif
24233    return SQLITE_OK;
24234  }
24235
24236  /* grab an exclusive lock */
24237  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24238  if( fd<0 ){
24239    /* failed to open/create the file, someone else may have stolen the lock */
24240    int tErrno = errno;
24241    if( EEXIST == tErrno ){
24242      rc = SQLITE_BUSY;
24243    } else {
24244      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24245      if( IS_LOCK_ERROR(rc) ){
24246        pFile->lastErrno = tErrno;
24247      }
24248    }
24249    return rc;
24250  }
24251  if( close(fd) ){
24252    pFile->lastErrno = errno;
24253    rc = SQLITE_IOERR_CLOSE;
24254  }
24255
24256  /* got it, set the type and return ok */
24257  pFile->eFileLock = eFileLock;
24258  return rc;
24259}
24260
24261/*
24262** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24263** must be either NO_LOCK or SHARED_LOCK.
24264**
24265** If the locking level of the file descriptor is already at or below
24266** the requested locking level, this routine is a no-op.
24267**
24268** When the locking level reaches NO_LOCK, delete the lock file.
24269*/
24270static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24271  unixFile *pFile = (unixFile*)id;
24272  char *zLockFile = (char *)pFile->lockingContext;
24273
24274  assert( pFile );
24275  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24276	   pFile->eFileLock, getpid()));
24277  assert( eFileLock<=SHARED_LOCK );
24278
24279  /* no-op if possible */
24280  if( pFile->eFileLock==eFileLock ){
24281    return SQLITE_OK;
24282  }
24283
24284  /* To downgrade to shared, simply update our internal notion of the
24285  ** lock state.  No need to mess with the file on disk.
24286  */
24287  if( eFileLock==SHARED_LOCK ){
24288    pFile->eFileLock = SHARED_LOCK;
24289    return SQLITE_OK;
24290  }
24291
24292  /* To fully unlock the database, delete the lock file */
24293  assert( eFileLock==NO_LOCK );
24294  if( unlink(zLockFile) ){
24295    int rc = 0;
24296    int tErrno = errno;
24297    if( ENOENT != tErrno ){
24298      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24299    }
24300    if( IS_LOCK_ERROR(rc) ){
24301      pFile->lastErrno = tErrno;
24302    }
24303    return rc;
24304  }
24305  pFile->eFileLock = NO_LOCK;
24306  return SQLITE_OK;
24307}
24308
24309/*
24310** Close a file.  Make sure the lock has been released before closing.
24311*/
24312static int dotlockClose(sqlite3_file *id) {
24313  int rc;
24314  if( id ){
24315    unixFile *pFile = (unixFile*)id;
24316    dotlockUnlock(id, NO_LOCK);
24317    sqlite3_free(pFile->lockingContext);
24318  }
24319  rc = closeUnixFile(id);
24320  return rc;
24321}
24322/****************** End of the dot-file lock implementation *******************
24323******************************************************************************/
24324
24325/******************************************************************************
24326************************** Begin flock Locking ********************************
24327**
24328** Use the flock() system call to do file locking.
24329**
24330** flock() locking is like dot-file locking in that the various
24331** fine-grain locking levels supported by SQLite are collapsed into
24332** a single exclusive lock.  In other words, SHARED, RESERVED, and
24333** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24334** still works when you do this, but concurrency is reduced since
24335** only a single process can be reading the database at a time.
24336**
24337** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24338** compiling for VXWORKS.
24339*/
24340#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24341
24342/*
24343** This routine checks if there is a RESERVED lock held on the specified
24344** file by this or any other process. If such a lock is held, set *pResOut
24345** to a non-zero value otherwise *pResOut is set to zero.  The return value
24346** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24347*/
24348static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24349  int rc = SQLITE_OK;
24350  int reserved = 0;
24351  unixFile *pFile = (unixFile*)id;
24352
24353  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24354
24355  assert( pFile );
24356
24357  /* Check if a thread in this process holds such a lock */
24358  if( pFile->eFileLock>SHARED_LOCK ){
24359    reserved = 1;
24360  }
24361
24362  /* Otherwise see if some other process holds it. */
24363  if( !reserved ){
24364    /* attempt to get the lock */
24365    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24366    if( !lrc ){
24367      /* got the lock, unlock it */
24368      lrc = flock(pFile->h, LOCK_UN);
24369      if ( lrc ) {
24370        int tErrno = errno;
24371        /* unlock failed with an error */
24372        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24373        if( IS_LOCK_ERROR(lrc) ){
24374          pFile->lastErrno = tErrno;
24375          rc = lrc;
24376        }
24377      }
24378    } else {
24379      int tErrno = errno;
24380      reserved = 1;
24381      /* someone else might have it reserved */
24382      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24383      if( IS_LOCK_ERROR(lrc) ){
24384        pFile->lastErrno = tErrno;
24385        rc = lrc;
24386      }
24387    }
24388  }
24389  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24390
24391#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24392  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24393    rc = SQLITE_OK;
24394    reserved=1;
24395  }
24396#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24397  *pResOut = reserved;
24398  return rc;
24399}
24400
24401/*
24402** Lock the file with the lock specified by parameter eFileLock - one
24403** of the following:
24404**
24405**     (1) SHARED_LOCK
24406**     (2) RESERVED_LOCK
24407**     (3) PENDING_LOCK
24408**     (4) EXCLUSIVE_LOCK
24409**
24410** Sometimes when requesting one lock state, additional lock states
24411** are inserted in between.  The locking might fail on one of the later
24412** transitions leaving the lock state different from what it started but
24413** still short of its goal.  The following chart shows the allowed
24414** transitions and the inserted intermediate states:
24415**
24416**    UNLOCKED -> SHARED
24417**    SHARED -> RESERVED
24418**    SHARED -> (PENDING) -> EXCLUSIVE
24419**    RESERVED -> (PENDING) -> EXCLUSIVE
24420**    PENDING -> EXCLUSIVE
24421**
24422** flock() only really support EXCLUSIVE locks.  We track intermediate
24423** lock states in the sqlite3_file structure, but all locks SHARED or
24424** above are really EXCLUSIVE locks and exclude all other processes from
24425** access the file.
24426**
24427** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24428** routine to lower a locking level.
24429*/
24430static int flockLock(sqlite3_file *id, int eFileLock) {
24431  int rc = SQLITE_OK;
24432  unixFile *pFile = (unixFile*)id;
24433
24434  assert( pFile );
24435
24436  /* if we already have a lock, it is exclusive.
24437  ** Just adjust level and punt on outta here. */
24438  if (pFile->eFileLock > NO_LOCK) {
24439    pFile->eFileLock = eFileLock;
24440    return SQLITE_OK;
24441  }
24442
24443  /* grab an exclusive lock */
24444
24445  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24446    int tErrno = errno;
24447    /* didn't get, must be busy */
24448    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24449    if( IS_LOCK_ERROR(rc) ){
24450      pFile->lastErrno = tErrno;
24451    }
24452  } else {
24453    /* got it, set the type and return ok */
24454    pFile->eFileLock = eFileLock;
24455  }
24456  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
24457           rc==SQLITE_OK ? "ok" : "failed"));
24458#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24459  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24460    rc = SQLITE_BUSY;
24461  }
24462#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24463  return rc;
24464}
24465
24466
24467/*
24468** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24469** must be either NO_LOCK or SHARED_LOCK.
24470**
24471** If the locking level of the file descriptor is already at or below
24472** the requested locking level, this routine is a no-op.
24473*/
24474static int flockUnlock(sqlite3_file *id, int eFileLock) {
24475  unixFile *pFile = (unixFile*)id;
24476
24477  assert( pFile );
24478  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24479           pFile->eFileLock, getpid()));
24480  assert( eFileLock<=SHARED_LOCK );
24481
24482  /* no-op if possible */
24483  if( pFile->eFileLock==eFileLock ){
24484    return SQLITE_OK;
24485  }
24486
24487  /* shared can just be set because we always have an exclusive */
24488  if (eFileLock==SHARED_LOCK) {
24489    pFile->eFileLock = eFileLock;
24490    return SQLITE_OK;
24491  }
24492
24493  /* no, really, unlock. */
24494  int rc = flock(pFile->h, LOCK_UN);
24495  if (rc) {
24496    int r, tErrno = errno;
24497    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24498    if( IS_LOCK_ERROR(r) ){
24499      pFile->lastErrno = tErrno;
24500    }
24501#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24502    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24503      r = SQLITE_BUSY;
24504    }
24505#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24506
24507    return r;
24508  } else {
24509    pFile->eFileLock = NO_LOCK;
24510    return SQLITE_OK;
24511  }
24512}
24513
24514/*
24515** Close a file.
24516*/
24517static int flockClose(sqlite3_file *id) {
24518  if( id ){
24519    flockUnlock(id, NO_LOCK);
24520  }
24521  return closeUnixFile(id);
24522}
24523
24524#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24525
24526/******************* End of the flock lock implementation *********************
24527******************************************************************************/
24528
24529/******************************************************************************
24530************************ Begin Named Semaphore Locking ************************
24531**
24532** Named semaphore locking is only supported on VxWorks.
24533**
24534** Semaphore locking is like dot-lock and flock in that it really only
24535** supports EXCLUSIVE locking.  Only a single process can read or write
24536** the database file at a time.  This reduces potential concurrency, but
24537** makes the lock implementation much easier.
24538*/
24539#if OS_VXWORKS
24540
24541/*
24542** This routine checks if there is a RESERVED lock held on the specified
24543** file by this or any other process. If such a lock is held, set *pResOut
24544** to a non-zero value otherwise *pResOut is set to zero.  The return value
24545** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24546*/
24547static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24548  int rc = SQLITE_OK;
24549  int reserved = 0;
24550  unixFile *pFile = (unixFile*)id;
24551
24552  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24553
24554  assert( pFile );
24555
24556  /* Check if a thread in this process holds such a lock */
24557  if( pFile->eFileLock>SHARED_LOCK ){
24558    reserved = 1;
24559  }
24560
24561  /* Otherwise see if some other process holds it. */
24562  if( !reserved ){
24563    sem_t *pSem = pFile->pInode->pSem;
24564    struct stat statBuf;
24565
24566    if( sem_trywait(pSem)==-1 ){
24567      int tErrno = errno;
24568      if( EAGAIN != tErrno ){
24569        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24570        pFile->lastErrno = tErrno;
24571      } else {
24572        /* someone else has the lock when we are in NO_LOCK */
24573        reserved = (pFile->eFileLock < SHARED_LOCK);
24574      }
24575    }else{
24576      /* we could have it if we want it */
24577      sem_post(pSem);
24578    }
24579  }
24580  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24581
24582  *pResOut = reserved;
24583  return rc;
24584}
24585
24586/*
24587** Lock the file with the lock specified by parameter eFileLock - one
24588** of the following:
24589**
24590**     (1) SHARED_LOCK
24591**     (2) RESERVED_LOCK
24592**     (3) PENDING_LOCK
24593**     (4) EXCLUSIVE_LOCK
24594**
24595** Sometimes when requesting one lock state, additional lock states
24596** are inserted in between.  The locking might fail on one of the later
24597** transitions leaving the lock state different from what it started but
24598** still short of its goal.  The following chart shows the allowed
24599** transitions and the inserted intermediate states:
24600**
24601**    UNLOCKED -> SHARED
24602**    SHARED -> RESERVED
24603**    SHARED -> (PENDING) -> EXCLUSIVE
24604**    RESERVED -> (PENDING) -> EXCLUSIVE
24605**    PENDING -> EXCLUSIVE
24606**
24607** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24608** lock states in the sqlite3_file structure, but all locks SHARED or
24609** above are really EXCLUSIVE locks and exclude all other processes from
24610** access the file.
24611**
24612** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24613** routine to lower a locking level.
24614*/
24615static int semLock(sqlite3_file *id, int eFileLock) {
24616  unixFile *pFile = (unixFile*)id;
24617  int fd;
24618  sem_t *pSem = pFile->pInode->pSem;
24619  int rc = SQLITE_OK;
24620
24621  /* if we already have a lock, it is exclusive.
24622  ** Just adjust level and punt on outta here. */
24623  if (pFile->eFileLock > NO_LOCK) {
24624    pFile->eFileLock = eFileLock;
24625    rc = SQLITE_OK;
24626    goto sem_end_lock;
24627  }
24628
24629  /* lock semaphore now but bail out when already locked. */
24630  if( sem_trywait(pSem)==-1 ){
24631    rc = SQLITE_BUSY;
24632    goto sem_end_lock;
24633  }
24634
24635  /* got it, set the type and return ok */
24636  pFile->eFileLock = eFileLock;
24637
24638 sem_end_lock:
24639  return rc;
24640}
24641
24642/*
24643** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24644** must be either NO_LOCK or SHARED_LOCK.
24645**
24646** If the locking level of the file descriptor is already at or below
24647** the requested locking level, this routine is a no-op.
24648*/
24649static int semUnlock(sqlite3_file *id, int eFileLock) {
24650  unixFile *pFile = (unixFile*)id;
24651  sem_t *pSem = pFile->pInode->pSem;
24652
24653  assert( pFile );
24654  assert( pSem );
24655  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
24656	   pFile->eFileLock, getpid()));
24657  assert( eFileLock<=SHARED_LOCK );
24658
24659  /* no-op if possible */
24660  if( pFile->eFileLock==eFileLock ){
24661    return SQLITE_OK;
24662  }
24663
24664  /* shared can just be set because we always have an exclusive */
24665  if (eFileLock==SHARED_LOCK) {
24666    pFile->eFileLock = eFileLock;
24667    return SQLITE_OK;
24668  }
24669
24670  /* no, really unlock. */
24671  if ( sem_post(pSem)==-1 ) {
24672    int rc, tErrno = errno;
24673    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24674    if( IS_LOCK_ERROR(rc) ){
24675      pFile->lastErrno = tErrno;
24676    }
24677    return rc;
24678  }
24679  pFile->eFileLock = NO_LOCK;
24680  return SQLITE_OK;
24681}
24682
24683/*
24684 ** Close a file.
24685 */
24686static int semClose(sqlite3_file *id) {
24687  if( id ){
24688    unixFile *pFile = (unixFile*)id;
24689    semUnlock(id, NO_LOCK);
24690    assert( pFile );
24691    unixEnterMutex();
24692    releaseInodeInfo(pFile);
24693    unixLeaveMutex();
24694    closeUnixFile(id);
24695  }
24696  return SQLITE_OK;
24697}
24698
24699#endif /* OS_VXWORKS */
24700/*
24701** Named semaphore locking is only available on VxWorks.
24702**
24703*************** End of the named semaphore lock implementation ****************
24704******************************************************************************/
24705
24706
24707/******************************************************************************
24708*************************** Begin AFP Locking *********************************
24709**
24710** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24711** on Apple Macintosh computers - both OS9 and OSX.
24712**
24713** Third-party implementations of AFP are available.  But this code here
24714** only works on OSX.
24715*/
24716
24717#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24718/*
24719** The afpLockingContext structure contains all afp lock specific state
24720*/
24721typedef struct afpLockingContext afpLockingContext;
24722struct afpLockingContext {
24723  int reserved;
24724  const char *dbPath;             /* Name of the open file */
24725};
24726
24727struct ByteRangeLockPB2
24728{
24729  unsigned long long offset;        /* offset to first byte to lock */
24730  unsigned long long length;        /* nbr of bytes to lock */
24731  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24732  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24733  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24734  int fd;                           /* file desc to assoc this lock with */
24735};
24736
24737#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
24738
24739/*
24740** This is a utility for setting or clearing a bit-range lock on an
24741** AFP filesystem.
24742**
24743** Return SQLITE_OK on success, SQLITE_BUSY on failure.
24744*/
24745static int afpSetLock(
24746  const char *path,              /* Name of the file to be locked or unlocked */
24747  unixFile *pFile,               /* Open file descriptor on path */
24748  unsigned long long offset,     /* First byte to be locked */
24749  unsigned long long length,     /* Number of bytes to lock */
24750  int setLockFlag                /* True to set lock.  False to clear lock */
24751){
24752  struct ByteRangeLockPB2 pb;
24753  int err;
24754
24755  pb.unLockFlag = setLockFlag ? 0 : 1;
24756  pb.startEndFlag = 0;
24757  pb.offset = offset;
24758  pb.length = length;
24759  pb.fd = pFile->h;
24760
24761  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
24762    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24763    offset, length));
24764  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24765  if ( err==-1 ) {
24766    int rc;
24767    int tErrno = errno;
24768    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24769             path, tErrno, strerror(tErrno)));
24770#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24771    rc = SQLITE_BUSY;
24772#else
24773    rc = sqliteErrorFromPosixError(tErrno,
24774                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
24775#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
24776    if( IS_LOCK_ERROR(rc) ){
24777      pFile->lastErrno = tErrno;
24778    }
24779    return rc;
24780  } else {
24781    return SQLITE_OK;
24782  }
24783}
24784
24785/*
24786** This routine checks if there is a RESERVED lock held on the specified
24787** file by this or any other process. If such a lock is held, set *pResOut
24788** to a non-zero value otherwise *pResOut is set to zero.  The return value
24789** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24790*/
24791static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
24792  int rc = SQLITE_OK;
24793  int reserved = 0;
24794  unixFile *pFile = (unixFile*)id;
24795
24796  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24797
24798  assert( pFile );
24799  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24800  if( context->reserved ){
24801    *pResOut = 1;
24802    return SQLITE_OK;
24803  }
24804  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24805
24806  /* Check if a thread in this process holds such a lock */
24807  if( pFile->pInode->eFileLock>SHARED_LOCK ){
24808    reserved = 1;
24809  }
24810
24811  /* Otherwise see if some other process holds it.
24812   */
24813  if( !reserved ){
24814    /* lock the RESERVED byte */
24815    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24816    if( SQLITE_OK==lrc ){
24817      /* if we succeeded in taking the reserved lock, unlock it to restore
24818      ** the original state */
24819      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24820    } else {
24821      /* if we failed to get the lock then someone else must have it */
24822      reserved = 1;
24823    }
24824    if( IS_LOCK_ERROR(lrc) ){
24825      rc=lrc;
24826    }
24827  }
24828
24829  unixLeaveMutex();
24830  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
24831
24832  *pResOut = reserved;
24833  return rc;
24834}
24835
24836/*
24837** Lock the file with the lock specified by parameter eFileLock - one
24838** of the following:
24839**
24840**     (1) SHARED_LOCK
24841**     (2) RESERVED_LOCK
24842**     (3) PENDING_LOCK
24843**     (4) EXCLUSIVE_LOCK
24844**
24845** Sometimes when requesting one lock state, additional lock states
24846** are inserted in between.  The locking might fail on one of the later
24847** transitions leaving the lock state different from what it started but
24848** still short of its goal.  The following chart shows the allowed
24849** transitions and the inserted intermediate states:
24850**
24851**    UNLOCKED -> SHARED
24852**    SHARED -> RESERVED
24853**    SHARED -> (PENDING) -> EXCLUSIVE
24854**    RESERVED -> (PENDING) -> EXCLUSIVE
24855**    PENDING -> EXCLUSIVE
24856**
24857** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24858** routine to lower a locking level.
24859*/
24860static int afpLock(sqlite3_file *id, int eFileLock){
24861  int rc = SQLITE_OK;
24862  unixFile *pFile = (unixFile*)id;
24863  unixInodeInfo *pInode = pFile->pInode;
24864  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24865
24866  assert( pFile );
24867  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24868           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24869           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24870
24871  /* If there is already a lock of this type or more restrictive on the
24872  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24873  ** unixEnterMutex() hasn't been called yet.
24874  */
24875  if( pFile->eFileLock>=eFileLock ){
24876    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24877           azFileLock(eFileLock)));
24878    return SQLITE_OK;
24879  }
24880
24881  /* Make sure the locking sequence is correct
24882  **  (1) We never move from unlocked to anything higher than shared lock.
24883  **  (2) SQLite never explicitly requests a pendig lock.
24884  **  (3) A shared lock is always held when a reserve lock is requested.
24885  */
24886  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24887  assert( eFileLock!=PENDING_LOCK );
24888  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24889
24890  /* This mutex is needed because pFile->pInode is shared across threads
24891  */
24892  unixEnterMutex();
24893  pInode = pFile->pInode;
24894
24895  /* If some thread using this PID has a lock via a different unixFile*
24896  ** handle that precludes the requested lock, return BUSY.
24897  */
24898  if( (pFile->eFileLock!=pInode->eFileLock &&
24899       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24900     ){
24901    rc = SQLITE_BUSY;
24902    goto afp_end_lock;
24903  }
24904
24905  /* If a SHARED lock is requested, and some thread using this PID already
24906  ** has a SHARED or RESERVED lock, then increment reference counts and
24907  ** return SQLITE_OK.
24908  */
24909  if( eFileLock==SHARED_LOCK &&
24910     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24911    assert( eFileLock==SHARED_LOCK );
24912    assert( pFile->eFileLock==0 );
24913    assert( pInode->nShared>0 );
24914    pFile->eFileLock = SHARED_LOCK;
24915    pInode->nShared++;
24916    pInode->nLock++;
24917    goto afp_end_lock;
24918  }
24919
24920  /* A PENDING lock is needed before acquiring a SHARED lock and before
24921  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24922  ** be released.
24923  */
24924  if( eFileLock==SHARED_LOCK
24925      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24926  ){
24927    int failed;
24928    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24929    if (failed) {
24930      rc = failed;
24931      goto afp_end_lock;
24932    }
24933  }
24934
24935  /* If control gets to this point, then actually go ahead and make
24936  ** operating system calls for the specified lock.
24937  */
24938  if( eFileLock==SHARED_LOCK ){
24939    int lrc1, lrc2, lrc1Errno;
24940    long lk, mask;
24941
24942    assert( pInode->nShared==0 );
24943    assert( pInode->eFileLock==0 );
24944
24945    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24946    /* Now get the read-lock SHARED_LOCK */
24947    /* note that the quality of the randomness doesn't matter that much */
24948    lk = random();
24949    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24950    lrc1 = afpSetLock(context->dbPath, pFile,
24951          SHARED_FIRST+pInode->sharedByte, 1, 1);
24952    if( IS_LOCK_ERROR(lrc1) ){
24953      lrc1Errno = pFile->lastErrno;
24954    }
24955    /* Drop the temporary PENDING lock */
24956    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24957
24958    if( IS_LOCK_ERROR(lrc1) ) {
24959      pFile->lastErrno = lrc1Errno;
24960      rc = lrc1;
24961      goto afp_end_lock;
24962    } else if( IS_LOCK_ERROR(lrc2) ){
24963      rc = lrc2;
24964      goto afp_end_lock;
24965    } else if( lrc1 != SQLITE_OK ) {
24966      rc = lrc1;
24967    } else {
24968      pFile->eFileLock = SHARED_LOCK;
24969      pInode->nLock++;
24970      pInode->nShared = 1;
24971    }
24972  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24973    /* We are trying for an exclusive lock but another thread in this
24974     ** same process is still holding a shared lock. */
24975    rc = SQLITE_BUSY;
24976  }else{
24977    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24978    ** assumed that there is a SHARED or greater lock on the file
24979    ** already.
24980    */
24981    int failed = 0;
24982    assert( 0!=pFile->eFileLock );
24983    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
24984        /* Acquire a RESERVED lock */
24985        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24986      if( !failed ){
24987        context->reserved = 1;
24988      }
24989    }
24990    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
24991      /* Acquire an EXCLUSIVE lock */
24992
24993      /* Remove the shared lock before trying the range.  we'll need to
24994      ** reestablish the shared lock if we can't get the  afpUnlock
24995      */
24996      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24997                         pInode->sharedByte, 1, 0)) ){
24998        int failed2 = SQLITE_OK;
24999        /* now attemmpt to get the exclusive lock range */
25000        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
25001                               SHARED_SIZE, 1);
25002        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
25003                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25004          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25005          ** a critical I/O error
25006          */
25007          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
25008               SQLITE_IOERR_LOCK;
25009          goto afp_end_lock;
25010        }
25011      }else{
25012        rc = failed;
25013      }
25014    }
25015    if( failed ){
25016      rc = failed;
25017    }
25018  }
25019
25020  if( rc==SQLITE_OK ){
25021    pFile->eFileLock = eFileLock;
25022    pInode->eFileLock = eFileLock;
25023  }else if( eFileLock==EXCLUSIVE_LOCK ){
25024    pFile->eFileLock = PENDING_LOCK;
25025    pInode->eFileLock = PENDING_LOCK;
25026  }
25027
25028afp_end_lock:
25029  unixLeaveMutex();
25030  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
25031         rc==SQLITE_OK ? "ok" : "failed"));
25032  return rc;
25033}
25034
25035/*
25036** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25037** must be either NO_LOCK or SHARED_LOCK.
25038**
25039** If the locking level of the file descriptor is already at or below
25040** the requested locking level, this routine is a no-op.
25041*/
25042static int afpUnlock(sqlite3_file *id, int eFileLock) {
25043  int rc = SQLITE_OK;
25044  unixFile *pFile = (unixFile*)id;
25045  unixInodeInfo *pInode;
25046  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25047  int skipShared = 0;
25048#ifdef SQLITE_TEST
25049  int h = pFile->h;
25050#endif
25051
25052  assert( pFile );
25053  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25054           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25055           getpid()));
25056
25057  assert( eFileLock<=SHARED_LOCK );
25058  if( pFile->eFileLock<=eFileLock ){
25059    return SQLITE_OK;
25060  }
25061  unixEnterMutex();
25062  pInode = pFile->pInode;
25063  assert( pInode->nShared!=0 );
25064  if( pFile->eFileLock>SHARED_LOCK ){
25065    assert( pInode->eFileLock==pFile->eFileLock );
25066    SimulateIOErrorBenign(1);
25067    SimulateIOError( h=(-1) )
25068    SimulateIOErrorBenign(0);
25069
25070#ifndef NDEBUG
25071    /* When reducing a lock such that other processes can start
25072    ** reading the database file again, make sure that the
25073    ** transaction counter was updated if any part of the database
25074    ** file changed.  If the transaction counter is not updated,
25075    ** other connections to the same file might not realize that
25076    ** the file has changed and hence might not know to flush their
25077    ** cache.  The use of a stale cache can lead to database corruption.
25078    */
25079    assert( pFile->inNormalWrite==0
25080           || pFile->dbUpdate==0
25081           || pFile->transCntrChng==1 );
25082    pFile->inNormalWrite = 0;
25083#endif
25084
25085    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25086      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25087      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25088        /* only re-establish the shared lock if necessary */
25089        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25090        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25091      } else {
25092        skipShared = 1;
25093      }
25094    }
25095    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25096      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25097    }
25098    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25099      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25100      if( !rc ){
25101        context->reserved = 0;
25102      }
25103    }
25104    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25105      pInode->eFileLock = SHARED_LOCK;
25106    }
25107  }
25108  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25109
25110    /* Decrement the shared lock counter.  Release the lock using an
25111    ** OS call only when all threads in this same process have released
25112    ** the lock.
25113    */
25114    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25115    pInode->nShared--;
25116    if( pInode->nShared==0 ){
25117      SimulateIOErrorBenign(1);
25118      SimulateIOError( h=(-1) )
25119      SimulateIOErrorBenign(0);
25120      if( !skipShared ){
25121        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25122      }
25123      if( !rc ){
25124        pInode->eFileLock = NO_LOCK;
25125        pFile->eFileLock = NO_LOCK;
25126      }
25127    }
25128    if( rc==SQLITE_OK ){
25129      pInode->nLock--;
25130      assert( pInode->nLock>=0 );
25131      if( pInode->nLock==0 ){
25132        rc = closePendingFds(pFile);
25133      }
25134    }
25135  }
25136
25137  unixLeaveMutex();
25138  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25139  return rc;
25140}
25141
25142/*
25143** Close a file & cleanup AFP specific locking context
25144*/
25145static int afpClose(sqlite3_file *id) {
25146  int rc = SQLITE_OK;
25147  if( id ){
25148    unixFile *pFile = (unixFile*)id;
25149    afpUnlock(id, NO_LOCK);
25150    unixEnterMutex();
25151    if( pFile->pInode && pFile->pInode->nLock ){
25152      /* If there are outstanding locks, do not actually close the file just
25153      ** yet because that would clear those locks.  Instead, add the file
25154      ** descriptor to pInode->aPending.  It will be automatically closed when
25155      ** the last lock is cleared.
25156      */
25157      setPendingFd(pFile);
25158    }
25159    releaseInodeInfo(pFile);
25160    sqlite3_free(pFile->lockingContext);
25161    rc = closeUnixFile(id);
25162    unixLeaveMutex();
25163  }
25164  return rc;
25165}
25166
25167#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25168/*
25169** The code above is the AFP lock implementation.  The code is specific
25170** to MacOSX and does not work on other unix platforms.  No alternative
25171** is available.  If you don't compile for a mac, then the "unix-afp"
25172** VFS is not available.
25173**
25174********************* End of the AFP lock implementation **********************
25175******************************************************************************/
25176
25177/******************************************************************************
25178*************************** Begin NFS Locking ********************************/
25179
25180#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25181/*
25182 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25183 ** must be either NO_LOCK or SHARED_LOCK.
25184 **
25185 ** If the locking level of the file descriptor is already at or below
25186 ** the requested locking level, this routine is a no-op.
25187 */
25188static int nfsUnlock(sqlite3_file *id, int eFileLock){
25189  return _posixUnlock(id, eFileLock, 1);
25190}
25191
25192#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25193/*
25194** The code above is the NFS lock implementation.  The code is specific
25195** to MacOSX and does not work on other unix platforms.  No alternative
25196** is available.
25197**
25198********************* End of the NFS lock implementation **********************
25199******************************************************************************/
25200
25201/******************************************************************************
25202**************** Non-locking sqlite3_file methods *****************************
25203**
25204** The next division contains implementations for all methods of the
25205** sqlite3_file object other than the locking methods.  The locking
25206** methods were defined in divisions above (one locking method per
25207** division).  Those methods that are common to all locking modes
25208** are gather together into this division.
25209*/
25210
25211/*
25212** Seek to the offset passed as the second argument, then read cnt
25213** bytes into pBuf. Return the number of bytes actually read.
25214**
25215** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25216** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25217** one system to another.  Since SQLite does not define USE_PREAD
25218** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25219** See tickets #2741 and #2681.
25220**
25221** To avoid stomping the errno value on a failed read the lastErrno value
25222** is set before returning.
25223*/
25224static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25225  int got;
25226#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25227  i64 newOffset;
25228#endif
25229  TIMER_START;
25230#if defined(USE_PREAD)
25231  got = pread(id->h, pBuf, cnt, offset);
25232  SimulateIOError( got = -1 );
25233#elif defined(USE_PREAD64)
25234  got = pread64(id->h, pBuf, cnt, offset);
25235  SimulateIOError( got = -1 );
25236#else
25237  newOffset = lseek(id->h, offset, SEEK_SET);
25238  SimulateIOError( newOffset-- );
25239  if( newOffset!=offset ){
25240    if( newOffset == -1 ){
25241      ((unixFile*)id)->lastErrno = errno;
25242    }else{
25243      ((unixFile*)id)->lastErrno = 0;
25244    }
25245    return -1;
25246  }
25247  got = read(id->h, pBuf, cnt);
25248#endif
25249  TIMER_END;
25250  if( got<0 ){
25251    ((unixFile*)id)->lastErrno = errno;
25252  }
25253  OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25254  return got;
25255}
25256
25257/*
25258** Read data from a file into a buffer.  Return SQLITE_OK if all
25259** bytes were read successfully and SQLITE_IOERR if anything goes
25260** wrong.
25261*/
25262static int unixRead(
25263  sqlite3_file *id,
25264  void *pBuf,
25265  int amt,
25266  sqlite3_int64 offset
25267){
25268  unixFile *pFile = (unixFile *)id;
25269  int got;
25270  assert( id );
25271
25272  /* If this is a database file (not a journal, master-journal or temp
25273  ** file), the bytes in the locking range should never be read or written. */
25274#if 0
25275  assert( pFile->pUnused==0
25276       || offset>=PENDING_BYTE+512
25277       || offset+amt<=PENDING_BYTE
25278  );
25279#endif
25280
25281  got = seekAndRead(pFile, offset, pBuf, amt);
25282  if( got==amt ){
25283    return SQLITE_OK;
25284  }else if( got<0 ){
25285    /* lastErrno set by seekAndRead */
25286    return SQLITE_IOERR_READ;
25287  }else{
25288    pFile->lastErrno = 0; /* not a system error */
25289    /* Unread parts of the buffer must be zero-filled */
25290    memset(&((char*)pBuf)[got], 0, amt-got);
25291    return SQLITE_IOERR_SHORT_READ;
25292  }
25293}
25294
25295/*
25296** Seek to the offset in id->offset then read cnt bytes into pBuf.
25297** Return the number of bytes actually read.  Update the offset.
25298**
25299** To avoid stomping the errno value on a failed write the lastErrno value
25300** is set before returning.
25301*/
25302static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25303  int got;
25304#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25305  i64 newOffset;
25306#endif
25307  TIMER_START;
25308#if defined(USE_PREAD)
25309  got = pwrite(id->h, pBuf, cnt, offset);
25310#elif defined(USE_PREAD64)
25311  got = pwrite64(id->h, pBuf, cnt, offset);
25312#else
25313  newOffset = lseek(id->h, offset, SEEK_SET);
25314  if( newOffset!=offset ){
25315    if( newOffset == -1 ){
25316      ((unixFile*)id)->lastErrno = errno;
25317    }else{
25318      ((unixFile*)id)->lastErrno = 0;
25319    }
25320    return -1;
25321  }
25322  got = write(id->h, pBuf, cnt);
25323#endif
25324  TIMER_END;
25325  if( got<0 ){
25326    ((unixFile*)id)->lastErrno = errno;
25327  }
25328
25329  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25330  return got;
25331}
25332
25333
25334/*
25335** Write data from a buffer into a file.  Return SQLITE_OK on success
25336** or some other error code on failure.
25337*/
25338static int unixWrite(
25339  sqlite3_file *id,
25340  const void *pBuf,
25341  int amt,
25342  sqlite3_int64 offset
25343){
25344  unixFile *pFile = (unixFile*)id;
25345  int wrote = 0;
25346  assert( id );
25347  assert( amt>0 );
25348
25349  /* If this is a database file (not a journal, master-journal or temp
25350  ** file), the bytes in the locking range should never be read or written. */
25351#if 0
25352  assert( pFile->pUnused==0
25353       || offset>=PENDING_BYTE+512
25354       || offset+amt<=PENDING_BYTE
25355  );
25356#endif
25357
25358#ifndef NDEBUG
25359  /* If we are doing a normal write to a database file (as opposed to
25360  ** doing a hot-journal rollback or a write to some file other than a
25361  ** normal database file) then record the fact that the database
25362  ** has changed.  If the transaction counter is modified, record that
25363  ** fact too.
25364  */
25365  if( pFile->inNormalWrite ){
25366    pFile->dbUpdate = 1;  /* The database has been modified */
25367    if( offset<=24 && offset+amt>=27 ){
25368      int rc;
25369      char oldCntr[4];
25370      SimulateIOErrorBenign(1);
25371      rc = seekAndRead(pFile, 24, oldCntr, 4);
25372      SimulateIOErrorBenign(0);
25373      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25374        pFile->transCntrChng = 1;  /* The transaction counter has changed */
25375      }
25376    }
25377  }
25378#endif
25379
25380  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25381    amt -= wrote;
25382    offset += wrote;
25383    pBuf = &((char*)pBuf)[wrote];
25384  }
25385  SimulateIOError(( wrote=(-1), amt=1 ));
25386  SimulateDiskfullError(( wrote=0, amt=1 ));
25387
25388  if( amt>0 ){
25389    if( wrote<0 ){
25390      /* lastErrno set by seekAndWrite */
25391      return SQLITE_IOERR_WRITE;
25392    }else{
25393      pFile->lastErrno = 0; /* not a system error */
25394      return SQLITE_FULL;
25395    }
25396  }
25397
25398  return SQLITE_OK;
25399}
25400
25401#ifdef SQLITE_TEST
25402/*
25403** Count the number of fullsyncs and normal syncs.  This is used to test
25404** that syncs and fullsyncs are occurring at the right times.
25405*/
25406SQLITE_API int sqlite3_sync_count = 0;
25407SQLITE_API int sqlite3_fullsync_count = 0;
25408#endif
25409
25410/*
25411** We do not trust systems to provide a working fdatasync().  Some do.
25412** Others do no.  To be safe, we will stick with the (slower) fsync().
25413** If you know that your system does support fdatasync() correctly,
25414** then simply compile with -Dfdatasync=fdatasync
25415*/
25416#if !defined(fdatasync) && !defined(__linux__)
25417# define fdatasync fsync
25418#endif
25419
25420/*
25421** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25422** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25423** only available on Mac OS X.  But that could change.
25424*/
25425#ifdef F_FULLFSYNC
25426# define HAVE_FULLFSYNC 1
25427#else
25428# define HAVE_FULLFSYNC 0
25429#endif
25430
25431
25432/*
25433** The fsync() system call does not work as advertised on many
25434** unix systems.  The following procedure is an attempt to make
25435** it work better.
25436**
25437** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25438** for testing when we want to run through the test suite quickly.
25439** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25440** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25441** or power failure will likely corrupt the database file.
25442**
25443** SQLite sets the dataOnly flag if the size of the file is unchanged.
25444** The idea behind dataOnly is that it should only write the file content
25445** to disk, not the inode.  We only set dataOnly if the file size is
25446** unchanged since the file size is part of the inode.  However,
25447** Ted Ts'o tells us that fdatasync() will also write the inode if the
25448** file size has changed.  The only real difference between fdatasync()
25449** and fsync(), Ted tells us, is that fdatasync() will not flush the
25450** inode if the mtime or owner or other inode attributes have changed.
25451** We only care about the file size, not the other file attributes, so
25452** as far as SQLite is concerned, an fdatasync() is always adequate.
25453** So, we always use fdatasync() if it is available, regardless of
25454** the value of the dataOnly flag.
25455*/
25456static int full_fsync(int fd, int fullSync, int dataOnly){
25457  int rc;
25458
25459  /* The following "ifdef/elif/else/" block has the same structure as
25460  ** the one below. It is replicated here solely to avoid cluttering
25461  ** up the real code with the UNUSED_PARAMETER() macros.
25462  */
25463#ifdef SQLITE_NO_SYNC
25464  UNUSED_PARAMETER(fd);
25465  UNUSED_PARAMETER(fullSync);
25466  UNUSED_PARAMETER(dataOnly);
25467#elif HAVE_FULLFSYNC
25468  UNUSED_PARAMETER(dataOnly);
25469#else
25470  UNUSED_PARAMETER(fullSync);
25471  UNUSED_PARAMETER(dataOnly);
25472#endif
25473
25474  /* Record the number of times that we do a normal fsync() and
25475  ** FULLSYNC.  This is used during testing to verify that this procedure
25476  ** gets called with the correct arguments.
25477  */
25478#ifdef SQLITE_TEST
25479  if( fullSync ) sqlite3_fullsync_count++;
25480  sqlite3_sync_count++;
25481#endif
25482
25483  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25484  ** no-op
25485  */
25486#ifdef SQLITE_NO_SYNC
25487  rc = SQLITE_OK;
25488#elif HAVE_FULLFSYNC
25489  if( fullSync ){
25490    rc = fcntl(fd, F_FULLFSYNC, 0);
25491  }else{
25492    rc = 1;
25493  }
25494  /* If the FULLFSYNC failed, fall back to attempting an fsync().
25495  ** It shouldn't be possible for fullfsync to fail on the local
25496  ** file system (on OSX), so failure indicates that FULLFSYNC
25497  ** isn't supported for this file system. So, attempt an fsync
25498  ** and (for now) ignore the overhead of a superfluous fcntl call.
25499  ** It'd be better to detect fullfsync support once and avoid
25500  ** the fcntl call every time sync is called.
25501  */
25502  if( rc ) rc = fsync(fd);
25503
25504#elif defined(__APPLE__)
25505  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25506  ** so currently we default to the macro that redefines fdatasync to fsync
25507  */
25508  rc = fsync(fd);
25509#else
25510  rc = fdatasync(fd);
25511#if OS_VXWORKS
25512  if( rc==-1 && errno==ENOTSUP ){
25513    rc = fsync(fd);
25514  }
25515#endif /* OS_VXWORKS */
25516#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25517
25518  if( OS_VXWORKS && rc!= -1 ){
25519    rc = 0;
25520  }
25521  return rc;
25522}
25523
25524/*
25525** Make sure all writes to a particular file are committed to disk.
25526**
25527** If dataOnly==0 then both the file itself and its metadata (file
25528** size, access time, etc) are synced.  If dataOnly!=0 then only the
25529** file data is synced.
25530**
25531** Under Unix, also make sure that the directory entry for the file
25532** has been created by fsync-ing the directory that contains the file.
25533** If we do not do this and we encounter a power failure, the directory
25534** entry for the journal might not exist after we reboot.  The next
25535** SQLite to access the file will not know that the journal exists (because
25536** the directory entry for the journal was never created) and the transaction
25537** will not roll back - possibly leading to database corruption.
25538*/
25539static int unixSync(sqlite3_file *id, int flags){
25540  int rc;
25541  unixFile *pFile = (unixFile*)id;
25542
25543  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25544  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25545
25546  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25547  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25548      || (flags&0x0F)==SQLITE_SYNC_FULL
25549  );
25550
25551  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25552  ** line is to test that doing so does not cause any problems.
25553  */
25554  SimulateDiskfullError( return SQLITE_FULL );
25555
25556  assert( pFile );
25557  OSTRACE(("SYNC    %-3d\n", pFile->h));
25558  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25559  SimulateIOError( rc=1 );
25560  if( rc ){
25561    pFile->lastErrno = errno;
25562    return SQLITE_IOERR_FSYNC;
25563  }
25564  if( pFile->dirfd>=0 ){
25565    int err;
25566    OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25567            HAVE_FULLFSYNC, isFullsync));
25568#ifndef SQLITE_DISABLE_DIRSYNC
25569    /* The directory sync is only attempted if full_fsync is
25570    ** turned off or unavailable.  If a full_fsync occurred above,
25571    ** then the directory sync is superfluous.
25572    */
25573    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25574       /*
25575       ** We have received multiple reports of fsync() returning
25576       ** errors when applied to directories on certain file systems.
25577       ** A failed directory sync is not a big deal.  So it seems
25578       ** better to ignore the error.  Ticket #1657
25579       */
25580       /* pFile->lastErrno = errno; */
25581       /* return SQLITE_IOERR; */
25582    }
25583#endif
25584    err = close(pFile->dirfd); /* Only need to sync once, so close the */
25585    if( err==0 ){              /* directory when we are done */
25586      pFile->dirfd = -1;
25587    }else{
25588      pFile->lastErrno = errno;
25589      rc = SQLITE_IOERR_DIR_CLOSE;
25590    }
25591  }
25592  return rc;
25593}
25594
25595/*
25596** Truncate an open file to a specified size
25597*/
25598static int unixTruncate(sqlite3_file *id, i64 nByte){
25599  unixFile *pFile = (unixFile *)id;
25600  int rc;
25601  assert( pFile );
25602  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25603
25604  /* If the user has configured a chunk-size for this file, truncate the
25605  ** file so that it consists of an integer number of chunks (i.e. the
25606  ** actual file size after the operation may be larger than the requested
25607  ** size).
25608  */
25609  if( pFile->szChunk ){
25610    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
25611  }
25612
25613  rc = ftruncate(pFile->h, (off_t)nByte);
25614  if( rc ){
25615    pFile->lastErrno = errno;
25616    return SQLITE_IOERR_TRUNCATE;
25617  }else{
25618#ifndef NDEBUG
25619    /* If we are doing a normal write to a database file (as opposed to
25620    ** doing a hot-journal rollback or a write to some file other than a
25621    ** normal database file) and we truncate the file to zero length,
25622    ** that effectively updates the change counter.  This might happen
25623    ** when restoring a database using the backup API from a zero-length
25624    ** source.
25625    */
25626    if( pFile->inNormalWrite && nByte==0 ){
25627      pFile->transCntrChng = 1;
25628    }
25629#endif
25630
25631    return SQLITE_OK;
25632  }
25633}
25634
25635/*
25636** Determine the current size of a file in bytes
25637*/
25638static int unixFileSize(sqlite3_file *id, i64 *pSize){
25639  int rc;
25640  struct stat buf;
25641  assert( id );
25642  rc = fstat(((unixFile*)id)->h, &buf);
25643  SimulateIOError( rc=1 );
25644  if( rc!=0 ){
25645    ((unixFile*)id)->lastErrno = errno;
25646    return SQLITE_IOERR_FSTAT;
25647  }
25648  *pSize = buf.st_size;
25649
25650  /* When opening a zero-size database, the findInodeInfo() procedure
25651  ** writes a single byte into that file in order to work around a bug
25652  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25653  ** layers, we need to report this file size as zero even though it is
25654  ** really 1.   Ticket #3260.
25655  */
25656  if( *pSize==1 ) *pSize = 0;
25657
25658
25659  return SQLITE_OK;
25660}
25661
25662#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25663/*
25664** Handler for proxy-locking file-control verbs.  Defined below in the
25665** proxying locking division.
25666*/
25667static int proxyFileControl(sqlite3_file*,int,void*);
25668#endif
25669
25670/*
25671** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
25672** file-control operation.
25673**
25674** If the user has configured a chunk-size for this file, it could be
25675** that the file needs to be extended at this point. Otherwise, the
25676** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
25677*/
25678static int fcntlSizeHint(unixFile *pFile, i64 nByte){
25679  if( pFile->szChunk ){
25680    i64 nSize;                    /* Required file size */
25681    struct stat buf;              /* Used to hold return values of fstat() */
25682
25683    if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
25684
25685    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
25686    if( nSize>(i64)buf.st_size ){
25687#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25688      if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
25689        return SQLITE_IOERR_WRITE;
25690      }
25691#else
25692      /* If the OS does not have posix_fallocate(), fake it. First use
25693      ** ftruncate() to set the file size, then write a single byte to
25694      ** the last byte in each block within the extended region. This
25695      ** is the same technique used by glibc to implement posix_fallocate()
25696      ** on systems that do not have a real fallocate() system call.
25697      */
25698      int nBlk = buf.st_blksize;  /* File-system block size */
25699      i64 iWrite;                 /* Next offset to write to */
25700      int nWrite;                 /* Return value from seekAndWrite() */
25701
25702      if( ftruncate(pFile->h, nSize) ){
25703        pFile->lastErrno = errno;
25704        return SQLITE_IOERR_TRUNCATE;
25705      }
25706      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
25707      do {
25708        nWrite = seekAndWrite(pFile, iWrite, "", 1);
25709        iWrite += nBlk;
25710      } while( nWrite==1 && iWrite<nSize );
25711      if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
25712#endif
25713    }
25714  }
25715
25716  return SQLITE_OK;
25717}
25718
25719/*
25720** Information and control of an open file handle.
25721*/
25722static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25723  switch( op ){
25724    case SQLITE_FCNTL_LOCKSTATE: {
25725      *(int*)pArg = ((unixFile*)id)->eFileLock;
25726      return SQLITE_OK;
25727    }
25728    case SQLITE_LAST_ERRNO: {
25729      *(int*)pArg = ((unixFile*)id)->lastErrno;
25730      return SQLITE_OK;
25731    }
25732    case SQLITE_FCNTL_CHUNK_SIZE: {
25733      ((unixFile*)id)->szChunk = *(int *)pArg;
25734      return SQLITE_OK;
25735    }
25736    case SQLITE_FCNTL_SIZE_HINT: {
25737      return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
25738    }
25739#ifndef NDEBUG
25740    /* The pager calls this method to signal that it has done
25741    ** a rollback and that the database is therefore unchanged and
25742    ** it hence it is OK for the transaction change counter to be
25743    ** unchanged.
25744    */
25745    case SQLITE_FCNTL_DB_UNCHANGED: {
25746      ((unixFile*)id)->dbUpdate = 0;
25747      return SQLITE_OK;
25748    }
25749#endif
25750#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25751    case SQLITE_SET_LOCKPROXYFILE:
25752    case SQLITE_GET_LOCKPROXYFILE: {
25753      return proxyFileControl(id,op,pArg);
25754    }
25755#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
25756  }
25757  return SQLITE_ERROR;
25758}
25759
25760/*
25761** Return the sector size in bytes of the underlying block device for
25762** the specified file. This is almost always 512 bytes, but may be
25763** larger for some devices.
25764**
25765** SQLite code assumes this function cannot fail. It also assumes that
25766** if two files are created in the same file-system directory (i.e.
25767** a database and its journal file) that the sector size will be the
25768** same for both.
25769*/
25770static int unixSectorSize(sqlite3_file *NotUsed){
25771  UNUSED_PARAMETER(NotUsed);
25772  return SQLITE_DEFAULT_SECTOR_SIZE;
25773}
25774
25775/*
25776** Return the device characteristics for the file. This is always 0 for unix.
25777*/
25778static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
25779  UNUSED_PARAMETER(NotUsed);
25780  return 0;
25781}
25782
25783#ifndef SQLITE_OMIT_WAL
25784
25785
25786/*
25787** Object used to represent an shared memory buffer.
25788**
25789** When multiple threads all reference the same wal-index, each thread
25790** has its own unixShm object, but they all point to a single instance
25791** of this unixShmNode object.  In other words, each wal-index is opened
25792** only once per process.
25793**
25794** Each unixShmNode object is connected to a single unixInodeInfo object.
25795** We could coalesce this object into unixInodeInfo, but that would mean
25796** every open file that does not use shared memory (in other words, most
25797** open files) would have to carry around this extra information.  So
25798** the unixInodeInfo object contains a pointer to this unixShmNode object
25799** and the unixShmNode object is created only when needed.
25800**
25801** unixMutexHeld() must be true when creating or destroying
25802** this object or while reading or writing the following fields:
25803**
25804**      nRef
25805**
25806** The following fields are read-only after the object is created:
25807**
25808**      fid
25809**      zFilename
25810**
25811** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
25812** unixMutexHeld() is true when reading or writing any other field
25813** in this structure.
25814*/
25815struct unixShmNode {
25816  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
25817  sqlite3_mutex *mutex;      /* Mutex to access this object */
25818  char *zFilename;           /* Name of the mmapped file */
25819  int h;                     /* Open file descriptor */
25820  int szRegion;              /* Size of shared-memory regions */
25821  int nRegion;               /* Size of array apRegion */
25822  char **apRegion;           /* Array of mapped shared-memory regions */
25823  int nRef;                  /* Number of unixShm objects pointing to this */
25824  unixShm *pFirst;           /* All unixShm objects pointing to this */
25825#ifdef SQLITE_DEBUG
25826  u8 exclMask;               /* Mask of exclusive locks held */
25827  u8 sharedMask;             /* Mask of shared locks held */
25828  u8 nextShmId;              /* Next available unixShm.id value */
25829#endif
25830};
25831
25832/*
25833** Structure used internally by this VFS to record the state of an
25834** open shared memory connection.
25835**
25836** The following fields are initialized when this object is created and
25837** are read-only thereafter:
25838**
25839**    unixShm.pFile
25840**    unixShm.id
25841**
25842** All other fields are read/write.  The unixShm.pFile->mutex must be held
25843** while accessing any read/write fields.
25844*/
25845struct unixShm {
25846  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
25847  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
25848  u8 hasMutex;               /* True if holding the unixShmNode mutex */
25849  u16 sharedMask;            /* Mask of shared locks held */
25850  u16 exclMask;              /* Mask of exclusive locks held */
25851#ifdef SQLITE_DEBUG
25852  u8 id;                     /* Id of this connection within its unixShmNode */
25853#endif
25854};
25855
25856/*
25857** Constants used for locking
25858*/
25859#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
25860#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
25861
25862/*
25863** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
25864**
25865** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
25866** otherwise.
25867*/
25868static int unixShmSystemLock(
25869  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
25870  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
25871  int ofst,              /* First byte of the locking range */
25872  int n                  /* Number of bytes to lock */
25873){
25874  struct flock f;       /* The posix advisory locking structure */
25875  int rc = SQLITE_OK;   /* Result code form fcntl() */
25876
25877  /* Access to the unixShmNode object is serialized by the caller */
25878  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
25879
25880  /* Shared locks never span more than one byte */
25881  assert( n==1 || lockType!=F_RDLCK );
25882
25883  /* Locks are within range */
25884  assert( n>=1 && n<SQLITE_SHM_NLOCK );
25885
25886  /* Initialize the locking parameters */
25887  memset(&f, 0, sizeof(f));
25888  f.l_type = lockType;
25889  f.l_whence = SEEK_SET;
25890  f.l_start = ofst;
25891  f.l_len = n;
25892
25893  rc = fcntl(pShmNode->h, F_SETLK, &f);
25894  rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
25895
25896  /* Update the global lock state and do debug tracing */
25897#ifdef SQLITE_DEBUG
25898  { u16 mask;
25899  OSTRACE(("SHM-LOCK "));
25900  mask = (1<<(ofst+n)) - (1<<ofst);
25901  if( rc==SQLITE_OK ){
25902    if( lockType==F_UNLCK ){
25903      OSTRACE(("unlock %d ok", ofst));
25904      pShmNode->exclMask &= ~mask;
25905      pShmNode->sharedMask &= ~mask;
25906    }else if( lockType==F_RDLCK ){
25907      OSTRACE(("read-lock %d ok", ofst));
25908      pShmNode->exclMask &= ~mask;
25909      pShmNode->sharedMask |= mask;
25910    }else{
25911      assert( lockType==F_WRLCK );
25912      OSTRACE(("write-lock %d ok", ofst));
25913      pShmNode->exclMask |= mask;
25914      pShmNode->sharedMask &= ~mask;
25915    }
25916  }else{
25917    if( lockType==F_UNLCK ){
25918      OSTRACE(("unlock %d failed", ofst));
25919    }else if( lockType==F_RDLCK ){
25920      OSTRACE(("read-lock failed"));
25921    }else{
25922      assert( lockType==F_WRLCK );
25923      OSTRACE(("write-lock %d failed", ofst));
25924    }
25925  }
25926  OSTRACE((" - afterwards %03x,%03x\n",
25927           pShmNode->sharedMask, pShmNode->exclMask));
25928  }
25929#endif
25930
25931  return rc;
25932}
25933
25934
25935/*
25936** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
25937**
25938** This is not a VFS shared-memory method; it is a utility function called
25939** by VFS shared-memory methods.
25940*/
25941static void unixShmPurge(unixFile *pFd){
25942  unixShmNode *p = pFd->pInode->pShmNode;
25943  assert( unixMutexHeld() );
25944  if( p && p->nRef==0 ){
25945    int i;
25946    assert( p->pInode==pFd->pInode );
25947    if( p->mutex ) sqlite3_mutex_free(p->mutex);
25948    for(i=0; i<p->nRegion; i++){
25949      munmap(p->apRegion[i], p->szRegion);
25950    }
25951    sqlite3_free(p->apRegion);
25952    if( p->h>=0 ) close(p->h);
25953    p->pInode->pShmNode = 0;
25954    sqlite3_free(p);
25955  }
25956}
25957
25958/*
25959** Open a shared-memory area associated with open database file pDbFd.
25960** This particular implementation uses mmapped files.
25961**
25962** The file used to implement shared-memory is in the same directory
25963** as the open database file and has the same name as the open database
25964** file with the "-shm" suffix added.  For example, if the database file
25965** is "/home/user1/config.db" then the file that is created and mmapped
25966** for shared memory will be called "/home/user1/config.db-shm".
25967**
25968** Another approach to is to use files in /dev/shm or /dev/tmp or an
25969** some other tmpfs mount. But if a file in a different directory
25970** from the database file is used, then differing access permissions
25971** or a chroot() might cause two different processes on the same
25972** database to end up using different files for shared memory -
25973** meaning that their memory would not really be shared - resulting
25974** in database corruption.  Nevertheless, this tmpfs file usage
25975** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
25976** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
25977** option results in an incompatible build of SQLite;  builds of SQLite
25978** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
25979** same database file at the same time, database corruption will likely
25980** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
25981** "unsupported" and may go away in a future SQLite release.
25982**
25983** When opening a new shared-memory file, if no other instances of that
25984** file are currently open, in this process or in other processes, then
25985** the file must be truncated to zero length or have its header cleared.
25986*/
25987static int unixOpenSharedMemory(unixFile *pDbFd){
25988  struct unixShm *p = 0;          /* The connection to be opened */
25989  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
25990  int rc;                         /* Result code */
25991  unixInodeInfo *pInode;          /* The inode of fd */
25992  char *zShmFilename;             /* Name of the file used for SHM */
25993  int nShmFilename;               /* Size of the SHM filename in bytes */
25994
25995  /* Allocate space for the new unixShm object. */
25996  p = sqlite3_malloc( sizeof(*p) );
25997  if( p==0 ) return SQLITE_NOMEM;
25998  memset(p, 0, sizeof(*p));
25999  assert( pDbFd->pShm==0 );
26000
26001  /* Check to see if a unixShmNode object already exists. Reuse an existing
26002  ** one if present. Create a new one if necessary.
26003  */
26004  unixEnterMutex();
26005  pInode = pDbFd->pInode;
26006  pShmNode = pInode->pShmNode;
26007  if( pShmNode==0 ){
26008    struct stat sStat;                 /* fstat() info for database file */
26009
26010    /* Call fstat() to figure out the permissions on the database file. If
26011    ** a new *-shm file is created, an attempt will be made to create it
26012    ** with the same permissions. The actual permissions the file is created
26013    ** with are subject to the current umask setting.
26014    */
26015    if( fstat(pDbFd->h, &sStat) ){
26016      rc = SQLITE_IOERR_FSTAT;
26017      goto shm_open_err;
26018    }
26019
26020#ifdef SQLITE_SHM_DIRECTORY
26021    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
26022#else
26023    nShmFilename = 5 + (int)strlen(pDbFd->zPath);
26024#endif
26025    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26026    if( pShmNode==0 ){
26027      rc = SQLITE_NOMEM;
26028      goto shm_open_err;
26029    }
26030    memset(pShmNode, 0, sizeof(*pShmNode));
26031    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26032#ifdef SQLITE_SHM_DIRECTORY
26033    sqlite3_snprintf(nShmFilename, zShmFilename,
26034                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26035                     (u32)sStat.st_ino, (u32)sStat.st_dev);
26036#else
26037    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26038#endif
26039    pShmNode->h = -1;
26040    pDbFd->pInode->pShmNode = pShmNode;
26041    pShmNode->pInode = pDbFd->pInode;
26042    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26043    if( pShmNode->mutex==0 ){
26044      rc = SQLITE_NOMEM;
26045      goto shm_open_err;
26046    }
26047
26048    pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
26049    if( pShmNode->h<0 ){
26050      rc = SQLITE_CANTOPEN_BKPT;
26051      goto shm_open_err;
26052    }
26053
26054    /* Check to see if another process is holding the dead-man switch.
26055    ** If not, truncate the file to zero length.
26056    */
26057    rc = SQLITE_OK;
26058    if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26059      if( ftruncate(pShmNode->h, 0) ){
26060        rc = SQLITE_IOERR_SHMOPEN;
26061      }
26062    }
26063    if( rc==SQLITE_OK ){
26064      rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26065    }
26066    if( rc ) goto shm_open_err;
26067  }
26068
26069  /* Make the new connection a child of the unixShmNode */
26070  p->pShmNode = pShmNode;
26071#ifdef SQLITE_DEBUG
26072  p->id = pShmNode->nextShmId++;
26073#endif
26074  pShmNode->nRef++;
26075  pDbFd->pShm = p;
26076  unixLeaveMutex();
26077
26078  /* The reference count on pShmNode has already been incremented under
26079  ** the cover of the unixEnterMutex() mutex and the pointer from the
26080  ** new (struct unixShm) object to the pShmNode has been set. All that is
26081  ** left to do is to link the new object into the linked list starting
26082  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
26083  ** mutex.
26084  */
26085  sqlite3_mutex_enter(pShmNode->mutex);
26086  p->pNext = pShmNode->pFirst;
26087  pShmNode->pFirst = p;
26088  sqlite3_mutex_leave(pShmNode->mutex);
26089  return SQLITE_OK;
26090
26091  /* Jump here on any error */
26092shm_open_err:
26093  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26094  sqlite3_free(p);
26095  unixLeaveMutex();
26096  return rc;
26097}
26098
26099/*
26100** This function is called to obtain a pointer to region iRegion of the
26101** shared-memory associated with the database file fd. Shared-memory regions
26102** are numbered starting from zero. Each shared-memory region is szRegion
26103** bytes in size.
26104**
26105** If an error occurs, an error code is returned and *pp is set to NULL.
26106**
26107** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
26108** region has not been allocated (by any client, including one running in a
26109** separate process), then *pp is set to NULL and SQLITE_OK returned. If
26110** bExtend is non-zero and the requested shared-memory region has not yet
26111** been allocated, it is allocated by this function.
26112**
26113** If the shared-memory region has already been allocated or is allocated by
26114** this call as described above, then it is mapped into this processes
26115** address space (if it is not already), *pp is set to point to the mapped
26116** memory and SQLITE_OK returned.
26117*/
26118static int unixShmMap(
26119  sqlite3_file *fd,               /* Handle open on database file */
26120  int iRegion,                    /* Region to retrieve */
26121  int szRegion,                   /* Size of regions */
26122  int bExtend,                    /* True to extend file if necessary */
26123  void volatile **pp              /* OUT: Mapped memory */
26124){
26125  unixFile *pDbFd = (unixFile*)fd;
26126  unixShm *p;
26127  unixShmNode *pShmNode;
26128  int rc = SQLITE_OK;
26129
26130  /* If the shared-memory file has not yet been opened, open it now. */
26131  if( pDbFd->pShm==0 ){
26132    rc = unixOpenSharedMemory(pDbFd);
26133    if( rc!=SQLITE_OK ) return rc;
26134  }
26135
26136  p = pDbFd->pShm;
26137  pShmNode = p->pShmNode;
26138  sqlite3_mutex_enter(pShmNode->mutex);
26139  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26140
26141  if( pShmNode->nRegion<=iRegion ){
26142    char **apNew;                      /* New apRegion[] array */
26143    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26144    struct stat sStat;                 /* Used by fstat() */
26145
26146    pShmNode->szRegion = szRegion;
26147
26148    /* The requested region is not mapped into this processes address space.
26149    ** Check to see if it has been allocated (i.e. if the wal-index file is
26150    ** large enough to contain the requested region).
26151    */
26152    if( fstat(pShmNode->h, &sStat) ){
26153      rc = SQLITE_IOERR_SHMSIZE;
26154      goto shmpage_out;
26155    }
26156
26157    if( sStat.st_size<nByte ){
26158      /* The requested memory region does not exist. If bExtend is set to
26159      ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
26160      **
26161      ** Alternatively, if bExtend is true, use ftruncate() to allocate
26162      ** the requested memory region.
26163      */
26164      if( !bExtend ) goto shmpage_out;
26165      if( ftruncate(pShmNode->h, nByte) ){
26166        rc = SQLITE_IOERR_SHMSIZE;
26167        goto shmpage_out;
26168      }
26169    }
26170
26171    /* Map the requested memory region into this processes address space. */
26172    apNew = (char **)sqlite3_realloc(
26173        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26174    );
26175    if( !apNew ){
26176      rc = SQLITE_IOERR_NOMEM;
26177      goto shmpage_out;
26178    }
26179    pShmNode->apRegion = apNew;
26180    while(pShmNode->nRegion<=iRegion){
26181      void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
26182          MAP_SHARED, pShmNode->h, iRegion*szRegion
26183      );
26184      if( pMem==MAP_FAILED ){
26185        rc = SQLITE_IOERR;
26186        goto shmpage_out;
26187      }
26188      pShmNode->apRegion[pShmNode->nRegion] = pMem;
26189      pShmNode->nRegion++;
26190    }
26191  }
26192
26193shmpage_out:
26194  if( pShmNode->nRegion>iRegion ){
26195    *pp = pShmNode->apRegion[iRegion];
26196  }else{
26197    *pp = 0;
26198  }
26199  sqlite3_mutex_leave(pShmNode->mutex);
26200  return rc;
26201}
26202
26203/*
26204** Change the lock state for a shared-memory segment.
26205**
26206** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
26207** different here than in posix.  In xShmLock(), one can go from unlocked
26208** to shared and back or from unlocked to exclusive and back.  But one may
26209** not go from shared to exclusive or from exclusive to shared.
26210*/
26211static int unixShmLock(
26212  sqlite3_file *fd,          /* Database file holding the shared memory */
26213  int ofst,                  /* First lock to acquire or release */
26214  int n,                     /* Number of locks to acquire or release */
26215  int flags                  /* What to do with the lock */
26216){
26217  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
26218  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
26219  unixShm *pX;                          /* For looping over all siblings */
26220  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
26221  int rc = SQLITE_OK;                   /* Result code */
26222  u16 mask;                             /* Mask of locks to take or release */
26223
26224  assert( pShmNode==pDbFd->pInode->pShmNode );
26225  assert( pShmNode->pInode==pDbFd->pInode );
26226  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
26227  assert( n>=1 );
26228  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
26229       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
26230       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
26231       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
26232  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26233
26234  mask = (1<<(ofst+n)) - (1<<ofst);
26235  assert( n>1 || mask==(1<<ofst) );
26236  sqlite3_mutex_enter(pShmNode->mutex);
26237  if( flags & SQLITE_SHM_UNLOCK ){
26238    u16 allMask = 0; /* Mask of locks held by siblings */
26239
26240    /* See if any siblings hold this same lock */
26241    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26242      if( pX==p ) continue;
26243      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26244      allMask |= pX->sharedMask;
26245    }
26246
26247    /* Unlock the system-level locks */
26248    if( (mask & allMask)==0 ){
26249      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26250    }else{
26251      rc = SQLITE_OK;
26252    }
26253
26254    /* Undo the local locks */
26255    if( rc==SQLITE_OK ){
26256      p->exclMask &= ~mask;
26257      p->sharedMask &= ~mask;
26258    }
26259  }else if( flags & SQLITE_SHM_SHARED ){
26260    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26261
26262    /* Find out which shared locks are already held by sibling connections.
26263    ** If any sibling already holds an exclusive lock, go ahead and return
26264    ** SQLITE_BUSY.
26265    */
26266    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26267      if( (pX->exclMask & mask)!=0 ){
26268        rc = SQLITE_BUSY;
26269        break;
26270      }
26271      allShared |= pX->sharedMask;
26272    }
26273
26274    /* Get shared locks at the system level, if necessary */
26275    if( rc==SQLITE_OK ){
26276      if( (allShared & mask)==0 ){
26277        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26278      }else{
26279        rc = SQLITE_OK;
26280      }
26281    }
26282
26283    /* Get the local shared locks */
26284    if( rc==SQLITE_OK ){
26285      p->sharedMask |= mask;
26286    }
26287  }else{
26288    /* Make sure no sibling connections hold locks that will block this
26289    ** lock.  If any do, return SQLITE_BUSY right away.
26290    */
26291    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26292      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26293        rc = SQLITE_BUSY;
26294        break;
26295      }
26296    }
26297
26298    /* Get the exclusive locks at the system level.  Then if successful
26299    ** also mark the local connection as being locked.
26300    */
26301    if( rc==SQLITE_OK ){
26302      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26303      if( rc==SQLITE_OK ){
26304        assert( (p->sharedMask & mask)==0 );
26305        p->exclMask |= mask;
26306      }
26307    }
26308  }
26309  sqlite3_mutex_leave(pShmNode->mutex);
26310  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26311           p->id, getpid(), p->sharedMask, p->exclMask));
26312  return rc;
26313}
26314
26315/*
26316** Implement a memory barrier or memory fence on shared memory.
26317**
26318** All loads and stores begun before the barrier must complete before
26319** any load or store begun after the barrier.
26320*/
26321static void unixShmBarrier(
26322  sqlite3_file *fd                /* Database file holding the shared memory */
26323){
26324  UNUSED_PARAMETER(fd);
26325  unixEnterMutex();
26326  unixLeaveMutex();
26327}
26328
26329/*
26330** Close a connection to shared-memory.  Delete the underlying
26331** storage if deleteFlag is true.
26332**
26333** If there is no shared memory associated with the connection then this
26334** routine is a harmless no-op.
26335*/
26336static int unixShmUnmap(
26337  sqlite3_file *fd,               /* The underlying database file */
26338  int deleteFlag                  /* Delete shared-memory if true */
26339){
26340  unixShm *p;                     /* The connection to be closed */
26341  unixShmNode *pShmNode;          /* The underlying shared-memory file */
26342  unixShm **pp;                   /* For looping over sibling connections */
26343  unixFile *pDbFd;                /* The underlying database file */
26344
26345  pDbFd = (unixFile*)fd;
26346  p = pDbFd->pShm;
26347  if( p==0 ) return SQLITE_OK;
26348  pShmNode = p->pShmNode;
26349
26350  assert( pShmNode==pDbFd->pInode->pShmNode );
26351  assert( pShmNode->pInode==pDbFd->pInode );
26352
26353  /* Remove connection p from the set of connections associated
26354  ** with pShmNode */
26355  sqlite3_mutex_enter(pShmNode->mutex);
26356  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26357  *pp = p->pNext;
26358
26359  /* Free the connection p */
26360  sqlite3_free(p);
26361  pDbFd->pShm = 0;
26362  sqlite3_mutex_leave(pShmNode->mutex);
26363
26364  /* If pShmNode->nRef has reached 0, then close the underlying
26365  ** shared-memory file, too */
26366  unixEnterMutex();
26367  assert( pShmNode->nRef>0 );
26368  pShmNode->nRef--;
26369  if( pShmNode->nRef==0 ){
26370    if( deleteFlag ) unlink(pShmNode->zFilename);
26371    unixShmPurge(pDbFd);
26372  }
26373  unixLeaveMutex();
26374
26375  return SQLITE_OK;
26376}
26377
26378
26379#else
26380# define unixShmMap     0
26381# define unixShmLock    0
26382# define unixShmBarrier 0
26383# define unixShmUnmap   0
26384#endif /* #ifndef SQLITE_OMIT_WAL */
26385
26386/*
26387** Here ends the implementation of all sqlite3_file methods.
26388**
26389********************** End sqlite3_file Methods *******************************
26390******************************************************************************/
26391
26392/*
26393** This division contains definitions of sqlite3_io_methods objects that
26394** implement various file locking strategies.  It also contains definitions
26395** of "finder" functions.  A finder-function is used to locate the appropriate
26396** sqlite3_io_methods object for a particular database file.  The pAppData
26397** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26398** the correct finder-function for that VFS.
26399**
26400** Most finder functions return a pointer to a fixed sqlite3_io_methods
26401** object.  The only interesting finder-function is autolockIoFinder, which
26402** looks at the filesystem type and tries to guess the best locking
26403** strategy from that.
26404**
26405** For finder-funtion F, two objects are created:
26406**
26407**    (1) The real finder-function named "FImpt()".
26408**
26409**    (2) A constant pointer to this function named just "F".
26410**
26411**
26412** A pointer to the F pointer is used as the pAppData value for VFS
26413** objects.  We have to do this instead of letting pAppData point
26414** directly at the finder-function since C90 rules prevent a void*
26415** from be cast into a function pointer.
26416**
26417**
26418** Each instance of this macro generates two objects:
26419**
26420**   *  A constant sqlite3_io_methods object call METHOD that has locking
26421**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26422**
26423**   *  An I/O method finder function called FINDER that returns a pointer
26424**      to the METHOD object in the previous bullet.
26425*/
26426#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26427static const sqlite3_io_methods METHOD = {                                   \
26428   VERSION,                    /* iVersion */                                \
26429   CLOSE,                      /* xClose */                                  \
26430   unixRead,                   /* xRead */                                   \
26431   unixWrite,                  /* xWrite */                                  \
26432   unixTruncate,               /* xTruncate */                               \
26433   unixSync,                   /* xSync */                                   \
26434   unixFileSize,               /* xFileSize */                               \
26435   LOCK,                       /* xLock */                                   \
26436   UNLOCK,                     /* xUnlock */                                 \
26437   CKLOCK,                     /* xCheckReservedLock */                      \
26438   unixFileControl,            /* xFileControl */                            \
26439   unixSectorSize,             /* xSectorSize */                             \
26440   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26441   unixShmMap,                 /* xShmMap */                                 \
26442   unixShmLock,                /* xShmLock */                                \
26443   unixShmBarrier,             /* xShmBarrier */                             \
26444   unixShmUnmap                /* xShmUnmap */                               \
26445};                                                                           \
26446static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26447  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26448  return &METHOD;                                                            \
26449}                                                                            \
26450static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26451    = FINDER##Impl;
26452
26453/*
26454** Here are all of the sqlite3_io_methods objects for each of the
26455** locking strategies.  Functions that return pointers to these methods
26456** are also created.
26457*/
26458IOMETHODS(
26459  posixIoFinder,            /* Finder function name */
26460  posixIoMethods,           /* sqlite3_io_methods object name */
26461  2,                        /* shared memory is enabled */
26462  unixClose,                /* xClose method */
26463  unixLock,                 /* xLock method */
26464  unixUnlock,               /* xUnlock method */
26465  unixCheckReservedLock     /* xCheckReservedLock method */
26466)
26467IOMETHODS(
26468  nolockIoFinder,           /* Finder function name */
26469  nolockIoMethods,          /* sqlite3_io_methods object name */
26470  1,                        /* shared memory is disabled */
26471  nolockClose,              /* xClose method */
26472  nolockLock,               /* xLock method */
26473  nolockUnlock,             /* xUnlock method */
26474  nolockCheckReservedLock   /* xCheckReservedLock method */
26475)
26476IOMETHODS(
26477  dotlockIoFinder,          /* Finder function name */
26478  dotlockIoMethods,         /* sqlite3_io_methods object name */
26479  1,                        /* shared memory is disabled */
26480  dotlockClose,             /* xClose method */
26481  dotlockLock,              /* xLock method */
26482  dotlockUnlock,            /* xUnlock method */
26483  dotlockCheckReservedLock  /* xCheckReservedLock method */
26484)
26485
26486#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26487IOMETHODS(
26488  flockIoFinder,            /* Finder function name */
26489  flockIoMethods,           /* sqlite3_io_methods object name */
26490  1,                        /* shared memory is disabled */
26491  flockClose,               /* xClose method */
26492  flockLock,                /* xLock method */
26493  flockUnlock,              /* xUnlock method */
26494  flockCheckReservedLock    /* xCheckReservedLock method */
26495)
26496#endif
26497
26498#if OS_VXWORKS
26499IOMETHODS(
26500  semIoFinder,              /* Finder function name */
26501  semIoMethods,             /* sqlite3_io_methods object name */
26502  1,                        /* shared memory is disabled */
26503  semClose,                 /* xClose method */
26504  semLock,                  /* xLock method */
26505  semUnlock,                /* xUnlock method */
26506  semCheckReservedLock      /* xCheckReservedLock method */
26507)
26508#endif
26509
26510#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26511IOMETHODS(
26512  afpIoFinder,              /* Finder function name */
26513  afpIoMethods,             /* sqlite3_io_methods object name */
26514  1,                        /* shared memory is disabled */
26515  afpClose,                 /* xClose method */
26516  afpLock,                  /* xLock method */
26517  afpUnlock,                /* xUnlock method */
26518  afpCheckReservedLock      /* xCheckReservedLock method */
26519)
26520#endif
26521
26522/*
26523** The proxy locking method is a "super-method" in the sense that it
26524** opens secondary file descriptors for the conch and lock files and
26525** it uses proxy, dot-file, AFP, and flock() locking methods on those
26526** secondary files.  For this reason, the division that implements
26527** proxy locking is located much further down in the file.  But we need
26528** to go ahead and define the sqlite3_io_methods and finder function
26529** for proxy locking here.  So we forward declare the I/O methods.
26530*/
26531#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26532static int proxyClose(sqlite3_file*);
26533static int proxyLock(sqlite3_file*, int);
26534static int proxyUnlock(sqlite3_file*, int);
26535static int proxyCheckReservedLock(sqlite3_file*, int*);
26536IOMETHODS(
26537  proxyIoFinder,            /* Finder function name */
26538  proxyIoMethods,           /* sqlite3_io_methods object name */
26539  1,                        /* shared memory is disabled */
26540  proxyClose,               /* xClose method */
26541  proxyLock,                /* xLock method */
26542  proxyUnlock,              /* xUnlock method */
26543  proxyCheckReservedLock    /* xCheckReservedLock method */
26544)
26545#endif
26546
26547/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
26548#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26549IOMETHODS(
26550  nfsIoFinder,               /* Finder function name */
26551  nfsIoMethods,              /* sqlite3_io_methods object name */
26552  1,                         /* shared memory is disabled */
26553  unixClose,                 /* xClose method */
26554  unixLock,                  /* xLock method */
26555  nfsUnlock,                 /* xUnlock method */
26556  unixCheckReservedLock      /* xCheckReservedLock method */
26557)
26558#endif
26559
26560#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26561/*
26562** This "finder" function attempts to determine the best locking strategy
26563** for the database file "filePath".  It then returns the sqlite3_io_methods
26564** object that implements that strategy.
26565**
26566** This is for MacOSX only.
26567*/
26568static const sqlite3_io_methods *autolockIoFinderImpl(
26569  const char *filePath,    /* name of the database file */
26570  unixFile *pNew           /* open file object for the database file */
26571){
26572  static const struct Mapping {
26573    const char *zFilesystem;              /* Filesystem type name */
26574    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
26575  } aMap[] = {
26576    { "hfs",    &posixIoMethods },
26577    { "ufs",    &posixIoMethods },
26578    { "afpfs",  &afpIoMethods },
26579    { "smbfs",  &afpIoMethods },
26580    { "webdav", &nolockIoMethods },
26581    { 0, 0 }
26582  };
26583  int i;
26584  struct statfs fsInfo;
26585  struct flock lockInfo;
26586
26587  if( !filePath ){
26588    /* If filePath==NULL that means we are dealing with a transient file
26589    ** that does not need to be locked. */
26590    return &nolockIoMethods;
26591  }
26592  if( statfs(filePath, &fsInfo) != -1 ){
26593    if( fsInfo.f_flags & MNT_RDONLY ){
26594      return &nolockIoMethods;
26595    }
26596    for(i=0; aMap[i].zFilesystem; i++){
26597      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
26598        return aMap[i].pMethods;
26599      }
26600    }
26601  }
26602
26603  /* Default case. Handles, amongst others, "nfs".
26604  ** Test byte-range lock using fcntl(). If the call succeeds,
26605  ** assume that the file-system supports POSIX style locks.
26606  */
26607  lockInfo.l_len = 1;
26608  lockInfo.l_start = 0;
26609  lockInfo.l_whence = SEEK_SET;
26610  lockInfo.l_type = F_RDLCK;
26611  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26612    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
26613      return &nfsIoMethods;
26614    } else {
26615      return &posixIoMethods;
26616    }
26617  }else{
26618    return &dotlockIoMethods;
26619  }
26620}
26621static const sqlite3_io_methods
26622  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26623
26624#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26625
26626#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
26627/*
26628** This "finder" function attempts to determine the best locking strategy
26629** for the database file "filePath".  It then returns the sqlite3_io_methods
26630** object that implements that strategy.
26631**
26632** This is for VXWorks only.
26633*/
26634static const sqlite3_io_methods *autolockIoFinderImpl(
26635  const char *filePath,    /* name of the database file */
26636  unixFile *pNew           /* the open file object */
26637){
26638  struct flock lockInfo;
26639
26640  if( !filePath ){
26641    /* If filePath==NULL that means we are dealing with a transient file
26642    ** that does not need to be locked. */
26643    return &nolockIoMethods;
26644  }
26645
26646  /* Test if fcntl() is supported and use POSIX style locks.
26647  ** Otherwise fall back to the named semaphore method.
26648  */
26649  lockInfo.l_len = 1;
26650  lockInfo.l_start = 0;
26651  lockInfo.l_whence = SEEK_SET;
26652  lockInfo.l_type = F_RDLCK;
26653  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26654    return &posixIoMethods;
26655  }else{
26656    return &semIoMethods;
26657  }
26658}
26659static const sqlite3_io_methods
26660  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26661
26662#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
26663
26664/*
26665** An abstract type for a pointer to a IO method finder function:
26666*/
26667typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
26668
26669
26670/****************************************************************************
26671**************************** sqlite3_vfs methods ****************************
26672**
26673** This division contains the implementation of methods on the
26674** sqlite3_vfs object.
26675*/
26676
26677/*
26678** Initialize the contents of the unixFile structure pointed to by pId.
26679*/
26680static int fillInUnixFile(
26681  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
26682  int h,                  /* Open file descriptor of file being opened */
26683  int dirfd,              /* Directory file descriptor */
26684  sqlite3_file *pId,      /* Write to the unixFile structure here */
26685  const char *zFilename,  /* Name of the file being opened */
26686  int noLock,             /* Omit locking if true */
26687  int isDelete            /* Delete on close if true */
26688){
26689  const sqlite3_io_methods *pLockingStyle;
26690  unixFile *pNew = (unixFile *)pId;
26691  int rc = SQLITE_OK;
26692
26693  assert( pNew->pInode==NULL );
26694
26695  /* Parameter isDelete is only used on vxworks. Express this explicitly
26696  ** here to prevent compiler warnings about unused parameters.
26697  */
26698  UNUSED_PARAMETER(isDelete);
26699
26700  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
26701  pNew->h = h;
26702  pNew->dirfd = dirfd;
26703  pNew->fileFlags = 0;
26704  assert( zFilename==0 || zFilename[0]=='/' );  /* Never a relative pathname */
26705  pNew->zPath = zFilename;
26706
26707#if OS_VXWORKS
26708  pNew->pId = vxworksFindFileId(zFilename);
26709  if( pNew->pId==0 ){
26710    noLock = 1;
26711    rc = SQLITE_NOMEM;
26712  }
26713#endif
26714
26715  if( noLock ){
26716    pLockingStyle = &nolockIoMethods;
26717  }else{
26718    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
26719#if SQLITE_ENABLE_LOCKING_STYLE
26720    /* Cache zFilename in the locking context (AFP and dotlock override) for
26721    ** proxyLock activation is possible (remote proxy is based on db name)
26722    ** zFilename remains valid until file is closed, to support */
26723    pNew->lockingContext = (void*)zFilename;
26724#endif
26725  }
26726
26727  if( pLockingStyle == &posixIoMethods
26728#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26729    || pLockingStyle == &nfsIoMethods
26730#endif
26731  ){
26732    unixEnterMutex();
26733    rc = findInodeInfo(pNew, &pNew->pInode);
26734    if( rc!=SQLITE_OK ){
26735      /* If an error occured in findInodeInfo(), close the file descriptor
26736      ** immediately, before releasing the mutex. findInodeInfo() may fail
26737      ** in two scenarios:
26738      **
26739      **   (a) A call to fstat() failed.
26740      **   (b) A malloc failed.
26741      **
26742      ** Scenario (b) may only occur if the process is holding no other
26743      ** file descriptors open on the same file. If there were other file
26744      ** descriptors on this file, then no malloc would be required by
26745      ** findInodeInfo(). If this is the case, it is quite safe to close
26746      ** handle h - as it is guaranteed that no posix locks will be released
26747      ** by doing so.
26748      **
26749      ** If scenario (a) caused the error then things are not so safe. The
26750      ** implicit assumption here is that if fstat() fails, things are in
26751      ** such bad shape that dropping a lock or two doesn't matter much.
26752      */
26753      close(h);
26754      h = -1;
26755    }
26756    unixLeaveMutex();
26757  }
26758
26759#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26760  else if( pLockingStyle == &afpIoMethods ){
26761    /* AFP locking uses the file path so it needs to be included in
26762    ** the afpLockingContext.
26763    */
26764    afpLockingContext *pCtx;
26765    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
26766    if( pCtx==0 ){
26767      rc = SQLITE_NOMEM;
26768    }else{
26769      /* NB: zFilename exists and remains valid until the file is closed
26770      ** according to requirement F11141.  So we do not need to make a
26771      ** copy of the filename. */
26772      pCtx->dbPath = zFilename;
26773      pCtx->reserved = 0;
26774      srandomdev();
26775      unixEnterMutex();
26776      rc = findInodeInfo(pNew, &pNew->pInode);
26777      if( rc!=SQLITE_OK ){
26778        sqlite3_free(pNew->lockingContext);
26779        close(h);
26780        h = -1;
26781      }
26782      unixLeaveMutex();
26783    }
26784  }
26785#endif
26786
26787  else if( pLockingStyle == &dotlockIoMethods ){
26788    /* Dotfile locking uses the file path so it needs to be included in
26789    ** the dotlockLockingContext
26790    */
26791    char *zLockFile;
26792    int nFilename;
26793    nFilename = (int)strlen(zFilename) + 6;
26794    zLockFile = (char *)sqlite3_malloc(nFilename);
26795    if( zLockFile==0 ){
26796      rc = SQLITE_NOMEM;
26797    }else{
26798      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
26799    }
26800    pNew->lockingContext = zLockFile;
26801  }
26802
26803#if OS_VXWORKS
26804  else if( pLockingStyle == &semIoMethods ){
26805    /* Named semaphore locking uses the file path so it needs to be
26806    ** included in the semLockingContext
26807    */
26808    unixEnterMutex();
26809    rc = findInodeInfo(pNew, &pNew->pInode);
26810    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
26811      char *zSemName = pNew->pInode->aSemName;
26812      int n;
26813      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
26814                       pNew->pId->zCanonicalName);
26815      for( n=1; zSemName[n]; n++ )
26816        if( zSemName[n]=='/' ) zSemName[n] = '_';
26817      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
26818      if( pNew->pInode->pSem == SEM_FAILED ){
26819        rc = SQLITE_NOMEM;
26820        pNew->pInode->aSemName[0] = '\0';
26821      }
26822    }
26823    unixLeaveMutex();
26824  }
26825#endif
26826
26827  pNew->lastErrno = 0;
26828#if OS_VXWORKS
26829  if( rc!=SQLITE_OK ){
26830    if( h>=0 ) close(h);
26831    h = -1;
26832    unlink(zFilename);
26833    isDelete = 0;
26834  }
26835  pNew->isDelete = isDelete;
26836#endif
26837  if( rc!=SQLITE_OK ){
26838    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
26839    if( h>=0 ) close(h);
26840  }else{
26841    pNew->pMethod = pLockingStyle;
26842    OpenCounter(+1);
26843  }
26844  return rc;
26845}
26846
26847/*
26848** Open a file descriptor to the directory containing file zFilename.
26849** If successful, *pFd is set to the opened file descriptor and
26850** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26851** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26852** value.
26853**
26854** If SQLITE_OK is returned, the caller is responsible for closing
26855** the file descriptor *pFd using close().
26856*/
26857static int openDirectory(const char *zFilename, int *pFd){
26858  int ii;
26859  int fd = -1;
26860  char zDirname[MAX_PATHNAME+1];
26861
26862  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26863  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26864  if( ii>0 ){
26865    zDirname[ii] = '\0';
26866    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
26867    if( fd>=0 ){
26868#ifdef FD_CLOEXEC
26869      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26870#endif
26871      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26872    }
26873  }
26874  *pFd = fd;
26875  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
26876}
26877
26878/*
26879** Return the name of a directory in which to put temporary files.
26880** If no suitable temporary file directory can be found, return NULL.
26881*/
26882static const char *unixTempFileDir(void){
26883  static const char *azDirs[] = {
26884     0,
26885     0,
26886     "/var/tmp",
26887     "/usr/tmp",
26888     "/tmp",
26889     0        /* List terminator */
26890  };
26891  unsigned int i;
26892  struct stat buf;
26893  const char *zDir = 0;
26894
26895  azDirs[0] = sqlite3_temp_directory;
26896  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
26897  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
26898    if( zDir==0 ) continue;
26899    if( stat(zDir, &buf) ) continue;
26900    if( !S_ISDIR(buf.st_mode) ) continue;
26901    if( access(zDir, 07) ) continue;
26902    break;
26903  }
26904  return zDir;
26905}
26906
26907/*
26908** Create a temporary file name in zBuf.  zBuf must be allocated
26909** by the calling process and must be big enough to hold at least
26910** pVfs->mxPathname bytes.
26911*/
26912static int unixGetTempname(int nBuf, char *zBuf){
26913  static const unsigned char zChars[] =
26914    "abcdefghijklmnopqrstuvwxyz"
26915    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
26916    "0123456789";
26917  unsigned int i, j;
26918  const char *zDir;
26919
26920  /* It's odd to simulate an io-error here, but really this is just
26921  ** using the io-error infrastructure to test that SQLite handles this
26922  ** function failing.
26923  */
26924  SimulateIOError( return SQLITE_IOERR );
26925
26926  zDir = unixTempFileDir();
26927  if( zDir==0 ) zDir = ".";
26928
26929  /* Check that the output buffer is large enough for the temporary file
26930  ** name. If it is not, return SQLITE_ERROR.
26931  */
26932  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
26933    return SQLITE_ERROR;
26934  }
26935
26936  do{
26937    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
26938    j = (int)strlen(zBuf);
26939    sqlite3_randomness(15, &zBuf[j]);
26940    for(i=0; i<15; i++, j++){
26941      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
26942    }
26943    zBuf[j] = 0;
26944  }while( access(zBuf,0)==0 );
26945  return SQLITE_OK;
26946}
26947
26948#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26949/*
26950** Routine to transform a unixFile into a proxy-locking unixFile.
26951** Implementation in the proxy-lock division, but used by unixOpen()
26952** if SQLITE_PREFER_PROXY_LOCKING is defined.
26953*/
26954static int proxyTransformUnixFile(unixFile*, const char*);
26955#endif
26956
26957/*
26958** Search for an unused file descriptor that was opened on the database
26959** file (not a journal or master-journal file) identified by pathname
26960** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
26961** argument to this function.
26962**
26963** Such a file descriptor may exist if a database connection was closed
26964** but the associated file descriptor could not be closed because some
26965** other file descriptor open on the same file is holding a file-lock.
26966** Refer to comments in the unixClose() function and the lengthy comment
26967** describing "Posix Advisory Locking" at the start of this file for
26968** further details. Also, ticket #4018.
26969**
26970** If a suitable file descriptor is found, then it is returned. If no
26971** such file descriptor is located, -1 is returned.
26972*/
26973static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
26974  UnixUnusedFd *pUnused = 0;
26975
26976  /* Do not search for an unused file descriptor on vxworks. Not because
26977  ** vxworks would not benefit from the change (it might, we're not sure),
26978  ** but because no way to test it is currently available. It is better
26979  ** not to risk breaking vxworks support for the sake of such an obscure
26980  ** feature.  */
26981#if !OS_VXWORKS
26982  struct stat sStat;                   /* Results of stat() call */
26983
26984  /* A stat() call may fail for various reasons. If this happens, it is
26985  ** almost certain that an open() call on the same path will also fail.
26986  ** For this reason, if an error occurs in the stat() call here, it is
26987  ** ignored and -1 is returned. The caller will try to open a new file
26988  ** descriptor on the same path, fail, and return an error to SQLite.
26989  **
26990  ** Even if a subsequent open() call does succeed, the consequences of
26991  ** not searching for a resusable file descriptor are not dire.  */
26992  if( 0==stat(zPath, &sStat) ){
26993    unixInodeInfo *pInode;
26994
26995    unixEnterMutex();
26996    pInode = inodeList;
26997    while( pInode && (pInode->fileId.dev!=sStat.st_dev
26998                     || pInode->fileId.ino!=sStat.st_ino) ){
26999       pInode = pInode->pNext;
27000    }
27001    if( pInode ){
27002      UnixUnusedFd **pp;
27003      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27004      pUnused = *pp;
27005      if( pUnused ){
27006        *pp = pUnused->pNext;
27007      }
27008    }
27009    unixLeaveMutex();
27010  }
27011#endif    /* if !OS_VXWORKS */
27012  return pUnused;
27013}
27014
27015/*
27016** This function is called by unixOpen() to determine the unix permissions
27017** to create new files with. If no error occurs, then SQLITE_OK is returned
27018** and a value suitable for passing as the third argument to open(2) is
27019** written to *pMode. If an IO error occurs, an SQLite error code is
27020** returned and the value of *pMode is not modified.
27021**
27022** If the file being opened is a temporary file, it is always created with
27023** the octal permissions 0600 (read/writable by owner only). If the file
27024** is a database or master journal file, it is created with the permissions
27025** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
27026**
27027** Finally, if the file being opened is a WAL or regular journal file, then
27028** this function queries the file-system for the permissions on the
27029** corresponding database file and sets *pMode to this value. Whenever
27030** possible, WAL and journal files are created using the same permissions
27031** as the associated database file.
27032*/
27033static int findCreateFileMode(
27034  const char *zPath,              /* Path of file (possibly) being created */
27035  int flags,                      /* Flags passed as 4th argument to xOpen() */
27036  mode_t *pMode                   /* OUT: Permissions to open file with */
27037){
27038  int rc = SQLITE_OK;             /* Return Code */
27039  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27040    char zDb[MAX_PATHNAME+1];     /* Database file path */
27041    int nDb;                      /* Number of valid bytes in zDb */
27042    struct stat sStat;            /* Output of stat() on database file */
27043
27044    nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
27045    memcpy(zDb, zPath, nDb);
27046    zDb[nDb] = '\0';
27047    if( 0==stat(zDb, &sStat) ){
27048      *pMode = sStat.st_mode & 0777;
27049    }else{
27050      rc = SQLITE_IOERR_FSTAT;
27051    }
27052  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27053    *pMode = 0600;
27054  }else{
27055    *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
27056  }
27057  return rc;
27058}
27059
27060/*
27061** Open the file zPath.
27062**
27063** Previously, the SQLite OS layer used three functions in place of this
27064** one:
27065**
27066**     sqlite3OsOpenReadWrite();
27067**     sqlite3OsOpenReadOnly();
27068**     sqlite3OsOpenExclusive();
27069**
27070** These calls correspond to the following combinations of flags:
27071**
27072**     ReadWrite() ->     (READWRITE | CREATE)
27073**     ReadOnly()  ->     (READONLY)
27074**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
27075**
27076** The old OpenExclusive() accepted a boolean argument - "delFlag". If
27077** true, the file was configured to be automatically deleted when the
27078** file handle closed. To achieve the same effect using this new
27079** interface, add the DELETEONCLOSE flag to those specified above for
27080** OpenExclusive().
27081*/
27082static int unixOpen(
27083  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
27084  const char *zPath,           /* Pathname of file to be opened */
27085  sqlite3_file *pFile,         /* The file descriptor to be filled in */
27086  int flags,                   /* Input flags to control the opening */
27087  int *pOutFlags               /* Output flags returned to SQLite core */
27088){
27089  unixFile *p = (unixFile *)pFile;
27090  int fd = -1;                   /* File descriptor returned by open() */
27091  int dirfd = -1;                /* Directory file descriptor */
27092  int openFlags = 0;             /* Flags to pass to open() */
27093  int eType = flags&0xFFFFFF00;  /* Type of file to open */
27094  int noLock;                    /* True to omit locking primitives */
27095  int rc = SQLITE_OK;            /* Function Return Code */
27096
27097  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
27098  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
27099  int isCreate     = (flags & SQLITE_OPEN_CREATE);
27100  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
27101  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
27102#if SQLITE_ENABLE_LOCKING_STYLE
27103  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
27104#endif
27105
27106  /* If creating a master or main-file journal, this function will open
27107  ** a file-descriptor on the directory too. The first time unixSync()
27108  ** is called the directory file descriptor will be fsync()ed and close()d.
27109  */
27110  int isOpenDirectory = (isCreate && (
27111        eType==SQLITE_OPEN_MASTER_JOURNAL
27112     || eType==SQLITE_OPEN_MAIN_JOURNAL
27113     || eType==SQLITE_OPEN_WAL
27114  ));
27115
27116  /* If argument zPath is a NULL pointer, this function is required to open
27117  ** a temporary file. Use this buffer to store the file name in.
27118  */
27119  char zTmpname[MAX_PATHNAME+1];
27120  const char *zName = zPath;
27121
27122  /* Check the following statements are true:
27123  **
27124  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
27125  **   (b) if CREATE is set, then READWRITE must also be set, and
27126  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
27127  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
27128  */
27129  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
27130  assert(isCreate==0 || isReadWrite);
27131  assert(isExclusive==0 || isCreate);
27132  assert(isDelete==0 || isCreate);
27133
27134  /* The main DB, main journal, WAL file and master journal are never
27135  ** automatically deleted. Nor are they ever temporary files.  */
27136  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
27137  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
27138  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27139  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
27140
27141  /* Assert that the upper layer has set one of the "file-type" flags. */
27142  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
27143       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
27144       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
27145       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
27146  );
27147
27148  memset(p, 0, sizeof(unixFile));
27149
27150  if( eType==SQLITE_OPEN_MAIN_DB ){
27151    UnixUnusedFd *pUnused;
27152    pUnused = findReusableFd(zName, flags);
27153    if( pUnused ){
27154      fd = pUnused->fd;
27155    }else{
27156      pUnused = sqlite3_malloc(sizeof(*pUnused));
27157      if( !pUnused ){
27158        return SQLITE_NOMEM;
27159      }
27160    }
27161    p->pUnused = pUnused;
27162  }else if( !zName ){
27163    /* If zName is NULL, the upper layer is requesting a temp file. */
27164    assert(isDelete && !isOpenDirectory);
27165    rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
27166    if( rc!=SQLITE_OK ){
27167      return rc;
27168    }
27169    zName = zTmpname;
27170  }
27171
27172  /* Determine the value of the flags parameter passed to POSIX function
27173  ** open(). These must be calculated even if open() is not called, as
27174  ** they may be stored as part of the file handle and used by the
27175  ** 'conch file' locking functions later on.  */
27176  if( isReadonly )  openFlags |= O_RDONLY;
27177  if( isReadWrite ) openFlags |= O_RDWR;
27178  if( isCreate )    openFlags |= O_CREAT;
27179  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
27180  openFlags |= (O_LARGEFILE|O_BINARY);
27181
27182  if( fd<0 ){
27183    mode_t openMode;              /* Permissions to create file with */
27184    rc = findCreateFileMode(zName, flags, &openMode);
27185    if( rc!=SQLITE_OK ){
27186      assert( !p->pUnused );
27187      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
27188      return rc;
27189    }
27190    fd = open(zName, openFlags, openMode);
27191    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
27192    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
27193      /* Failed to open the file for read/write access. Try read-only. */
27194      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
27195      openFlags &= ~(O_RDWR|O_CREAT);
27196      flags |= SQLITE_OPEN_READONLY;
27197      openFlags |= O_RDONLY;
27198      fd = open(zName, openFlags, openMode);
27199    }
27200    if( fd<0 ){
27201      rc = SQLITE_CANTOPEN_BKPT;
27202      goto open_finished;
27203    }
27204  }
27205  assert( fd>=0 );
27206  if( pOutFlags ){
27207    *pOutFlags = flags;
27208  }
27209
27210  if( p->pUnused ){
27211    p->pUnused->fd = fd;
27212    p->pUnused->flags = flags;
27213  }
27214
27215  if( isDelete ){
27216#if OS_VXWORKS
27217    zPath = zName;
27218#else
27219    unlink(zName);
27220#endif
27221  }
27222#if SQLITE_ENABLE_LOCKING_STYLE
27223  else{
27224    p->openFlags = openFlags;
27225  }
27226#endif
27227
27228  if( isOpenDirectory ){
27229    rc = openDirectory(zPath, &dirfd);
27230    if( rc!=SQLITE_OK ){
27231      /* It is safe to close fd at this point, because it is guaranteed not
27232      ** to be open on a database file. If it were open on a database file,
27233      ** it would not be safe to close as this would release any locks held
27234      ** on the file by this process.  */
27235      assert( eType!=SQLITE_OPEN_MAIN_DB );
27236      close(fd);             /* silently leak if fail, already in error */
27237      goto open_finished;
27238    }
27239  }
27240
27241#ifdef FD_CLOEXEC
27242  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27243#endif
27244
27245  noLock = eType!=SQLITE_OPEN_MAIN_DB;
27246
27247
27248#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27249  struct statfs fsInfo;
27250  if( fstatfs(fd, &fsInfo) == -1 ){
27251    ((unixFile*)pFile)->lastErrno = errno;
27252    if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
27253    close(fd); /* silently leak if fail, in error */
27254    return SQLITE_IOERR_ACCESS;
27255  }
27256  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27257    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27258  }
27259#endif
27260
27261#if SQLITE_ENABLE_LOCKING_STYLE
27262#if SQLITE_PREFER_PROXY_LOCKING
27263  isAutoProxy = 1;
27264#endif
27265  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27266    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27267    int useProxy = 0;
27268
27269    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
27270    ** never use proxy, NULL means use proxy for non-local files only.  */
27271    if( envforce!=NULL ){
27272      useProxy = atoi(envforce)>0;
27273    }else{
27274      struct statfs fsInfo;
27275      if( statfs(zPath, &fsInfo) == -1 ){
27276        /* In theory, the close(fd) call is sub-optimal. If the file opened
27277        ** with fd is a database file, and there are other connections open
27278        ** on that file that are currently holding advisory locks on it,
27279        ** then the call to close() will cancel those locks. In practice,
27280        ** we're assuming that statfs() doesn't fail very often. At least
27281        ** not while other file descriptors opened by the same process on
27282        ** the same file are working.  */
27283        p->lastErrno = errno;
27284        if( dirfd>=0 ){
27285          close(dirfd); /* silently leak if fail, in error */
27286        }
27287        close(fd); /* silently leak if fail, in error */
27288        rc = SQLITE_IOERR_ACCESS;
27289        goto open_finished;
27290      }
27291      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
27292    }
27293    if( useProxy ){
27294      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27295      if( rc==SQLITE_OK ){
27296        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
27297        if( rc!=SQLITE_OK ){
27298          /* Use unixClose to clean up the resources added in fillInUnixFile
27299          ** and clear all the structure's references.  Specifically,
27300          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
27301          */
27302          unixClose(pFile);
27303          return rc;
27304        }
27305      }
27306      goto open_finished;
27307    }
27308  }
27309#endif
27310
27311  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27312open_finished:
27313  if( rc!=SQLITE_OK ){
27314    sqlite3_free(p->pUnused);
27315  }
27316  return rc;
27317}
27318
27319
27320/*
27321** Delete the file at zPath. If the dirSync argument is true, fsync()
27322** the directory after deleting the file.
27323*/
27324static int unixDelete(
27325  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
27326  const char *zPath,        /* Name of file to be deleted */
27327  int dirSync               /* If true, fsync() directory after deleting file */
27328){
27329  int rc = SQLITE_OK;
27330  UNUSED_PARAMETER(NotUsed);
27331  SimulateIOError(return SQLITE_IOERR_DELETE);
27332  if( unlink(zPath)==(-1) && errno!=ENOENT ){
27333    return SQLITE_IOERR_DELETE;
27334  }
27335#ifndef SQLITE_DISABLE_DIRSYNC
27336  if( dirSync ){
27337    int fd;
27338    rc = openDirectory(zPath, &fd);
27339    if( rc==SQLITE_OK ){
27340#if OS_VXWORKS
27341      if( fsync(fd)==-1 )
27342#else
27343      if( fsync(fd) )
27344#endif
27345      {
27346        rc = SQLITE_IOERR_DIR_FSYNC;
27347      }
27348      if( close(fd)&&!rc ){
27349        rc = SQLITE_IOERR_DIR_CLOSE;
27350      }
27351    }
27352  }
27353#endif
27354  return rc;
27355}
27356
27357/*
27358** Test the existance of or access permissions of file zPath. The
27359** test performed depends on the value of flags:
27360**
27361**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27362**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27363**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27364**
27365** Otherwise return 0.
27366*/
27367static int unixAccess(
27368  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27369  const char *zPath,      /* Path of the file to examine */
27370  int flags,              /* What do we want to learn about the zPath file? */
27371  int *pResOut            /* Write result boolean here */
27372){
27373  int amode = 0;
27374  UNUSED_PARAMETER(NotUsed);
27375  SimulateIOError( return SQLITE_IOERR_ACCESS; );
27376  switch( flags ){
27377    case SQLITE_ACCESS_EXISTS:
27378      amode = F_OK;
27379      break;
27380    case SQLITE_ACCESS_READWRITE:
27381      amode = W_OK|R_OK;
27382      break;
27383    case SQLITE_ACCESS_READ:
27384      amode = R_OK;
27385      break;
27386
27387    default:
27388      assert(!"Invalid flags argument");
27389  }
27390  *pResOut = (access(zPath, amode)==0);
27391  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27392    struct stat buf;
27393    if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27394      *pResOut = 0;
27395    }
27396  }
27397  return SQLITE_OK;
27398}
27399
27400
27401/*
27402** Turn a relative pathname into a full pathname. The relative path
27403** is stored as a nul-terminated string in the buffer pointed to by
27404** zPath.
27405**
27406** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
27407** (in this case, MAX_PATHNAME bytes). The full-path is written to
27408** this buffer before returning.
27409*/
27410static int unixFullPathname(
27411  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27412  const char *zPath,            /* Possibly relative input path */
27413  int nOut,                     /* Size of output buffer in bytes */
27414  char *zOut                    /* Output buffer */
27415){
27416
27417  /* It's odd to simulate an io-error here, but really this is just
27418  ** using the io-error infrastructure to test that SQLite handles this
27419  ** function failing. This function could fail if, for example, the
27420  ** current working directory has been unlinked.
27421  */
27422  SimulateIOError( return SQLITE_ERROR );
27423
27424  assert( pVfs->mxPathname==MAX_PATHNAME );
27425  UNUSED_PARAMETER(pVfs);
27426
27427  zOut[nOut-1] = '\0';
27428  if( zPath[0]=='/' ){
27429    sqlite3_snprintf(nOut, zOut, "%s", zPath);
27430  }else{
27431    int nCwd;
27432    if( getcwd(zOut, nOut-1)==0 ){
27433      return SQLITE_CANTOPEN_BKPT;
27434    }
27435    nCwd = (int)strlen(zOut);
27436    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27437  }
27438  return SQLITE_OK;
27439}
27440
27441
27442#ifndef SQLITE_OMIT_LOAD_EXTENSION
27443/*
27444** Interfaces for opening a shared library, finding entry points
27445** within the shared library, and closing the shared library.
27446*/
27447#include <dlfcn.h>
27448static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27449  UNUSED_PARAMETER(NotUsed);
27450  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27451}
27452
27453/*
27454** SQLite calls this function immediately after a call to unixDlSym() or
27455** unixDlOpen() fails (returns a null pointer). If a more detailed error
27456** message is available, it is written to zBufOut. If no error message
27457** is available, zBufOut is left unmodified and SQLite uses a default
27458** error message.
27459*/
27460static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27461  char *zErr;
27462  UNUSED_PARAMETER(NotUsed);
27463  unixEnterMutex();
27464  zErr = dlerror();
27465  if( zErr ){
27466    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27467  }
27468  unixLeaveMutex();
27469}
27470static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27471  /*
27472  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27473  ** cast into a pointer to a function.  And yet the library dlsym() routine
27474  ** returns a void* which is really a pointer to a function.  So how do we
27475  ** use dlsym() with -pedantic-errors?
27476  **
27477  ** Variable x below is defined to be a pointer to a function taking
27478  ** parameters void* and const char* and returning a pointer to a function.
27479  ** We initialize x by assigning it a pointer to the dlsym() function.
27480  ** (That assignment requires a cast.)  Then we call the function that
27481  ** x points to.
27482  **
27483  ** This work-around is unlikely to work correctly on any system where
27484  ** you really cannot cast a function pointer into void*.  But then, on the
27485  ** other hand, dlsym() will not work on such a system either, so we have
27486  ** not really lost anything.
27487  */
27488  void (*(*x)(void*,const char*))(void);
27489  UNUSED_PARAMETER(NotUsed);
27490  x = (void(*(*)(void*,const char*))(void))dlsym;
27491  return (*x)(p, zSym);
27492}
27493static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27494  UNUSED_PARAMETER(NotUsed);
27495  dlclose(pHandle);
27496}
27497#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27498  #define unixDlOpen  0
27499  #define unixDlError 0
27500  #define unixDlSym   0
27501  #define unixDlClose 0
27502#endif
27503
27504/*
27505** Write nBuf bytes of random data to the supplied buffer zBuf.
27506*/
27507static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27508  UNUSED_PARAMETER(NotUsed);
27509  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27510
27511  /* We have to initialize zBuf to prevent valgrind from reporting
27512  ** errors.  The reports issued by valgrind are incorrect - we would
27513  ** prefer that the randomness be increased by making use of the
27514  ** uninitialized space in zBuf - but valgrind errors tend to worry
27515  ** some users.  Rather than argue, it seems easier just to initialize
27516  ** the whole array and silence valgrind, even if that means less randomness
27517  ** in the random seed.
27518  **
27519  ** When testing, initializing zBuf[] to zero is all we do.  That means
27520  ** that we always use the same random number sequence.  This makes the
27521  ** tests repeatable.
27522  */
27523  memset(zBuf, 0, nBuf);
27524#if !defined(SQLITE_TEST)
27525  {
27526    int pid, fd;
27527    fd = open("/dev/urandom", O_RDONLY);
27528    if( fd<0 ){
27529      time_t t;
27530      time(&t);
27531      memcpy(zBuf, &t, sizeof(t));
27532      pid = getpid();
27533      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
27534      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
27535      nBuf = sizeof(t) + sizeof(pid);
27536    }else{
27537      nBuf = read(fd, zBuf, nBuf);
27538      close(fd);
27539    }
27540  }
27541#endif
27542  return nBuf;
27543}
27544
27545
27546/*
27547** Sleep for a little while.  Return the amount of time slept.
27548** The argument is the number of microseconds we want to sleep.
27549** The return value is the number of microseconds of sleep actually
27550** requested from the underlying operating system, a number which
27551** might be greater than or equal to the argument, but not less
27552** than the argument.
27553*/
27554static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
27555#if OS_VXWORKS
27556  struct timespec sp;
27557
27558  sp.tv_sec = microseconds / 1000000;
27559  sp.tv_nsec = (microseconds % 1000000) * 1000;
27560  nanosleep(&sp, NULL);
27561  UNUSED_PARAMETER(NotUsed);
27562  return microseconds;
27563#elif defined(HAVE_USLEEP) && HAVE_USLEEP
27564  usleep(microseconds);
27565  UNUSED_PARAMETER(NotUsed);
27566  return microseconds;
27567#else
27568  int seconds = (microseconds+999999)/1000000;
27569  sleep(seconds);
27570  UNUSED_PARAMETER(NotUsed);
27571  return seconds*1000000;
27572#endif
27573}
27574
27575/*
27576** The following variable, if set to a non-zero value, is interpreted as
27577** the number of seconds since 1970 and is used to set the result of
27578** sqlite3OsCurrentTime() during testing.
27579*/
27580#ifdef SQLITE_TEST
27581SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
27582#endif
27583
27584/*
27585** Find the current time (in Universal Coordinated Time).  Write into *piNow
27586** the current time and date as a Julian Day number times 86_400_000.  In
27587** other words, write into *piNow the number of milliseconds since the Julian
27588** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27589** proleptic Gregorian calendar.
27590**
27591** On success, return 0.  Return 1 if the time and date cannot be found.
27592*/
27593static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27594  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27595#if defined(NO_GETTOD)
27596  time_t t;
27597  time(&t);
27598  *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
27599#elif OS_VXWORKS
27600  struct timespec sNow;
27601  clock_gettime(CLOCK_REALTIME, &sNow);
27602  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27603#else
27604  struct timeval sNow;
27605  gettimeofday(&sNow, 0);
27606  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
27607#endif
27608
27609#ifdef SQLITE_TEST
27610  if( sqlite3_current_time ){
27611    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
27612  }
27613#endif
27614  UNUSED_PARAMETER(NotUsed);
27615  return 0;
27616}
27617
27618/*
27619** Find the current time (in Universal Coordinated Time).  Write the
27620** current time and date as a Julian Day number into *prNow and
27621** return 0.  Return 1 if the time and date cannot be found.
27622*/
27623static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
27624  sqlite3_int64 i;
27625  UNUSED_PARAMETER(NotUsed);
27626  unixCurrentTimeInt64(0, &i);
27627  *prNow = i/86400000.0;
27628  return 0;
27629}
27630
27631/*
27632** We added the xGetLastError() method with the intention of providing
27633** better low-level error messages when operating-system problems come up
27634** during SQLite operation.  But so far, none of that has been implemented
27635** in the core.  So this routine is never called.  For now, it is merely
27636** a place-holder.
27637*/
27638static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
27639  UNUSED_PARAMETER(NotUsed);
27640  UNUSED_PARAMETER(NotUsed2);
27641  UNUSED_PARAMETER(NotUsed3);
27642  return 0;
27643}
27644
27645
27646/*
27647************************ End of sqlite3_vfs methods ***************************
27648******************************************************************************/
27649
27650/******************************************************************************
27651************************** Begin Proxy Locking ********************************
27652**
27653** Proxy locking is a "uber-locking-method" in this sense:  It uses the
27654** other locking methods on secondary lock files.  Proxy locking is a
27655** meta-layer over top of the primitive locking implemented above.  For
27656** this reason, the division that implements of proxy locking is deferred
27657** until late in the file (here) after all of the other I/O methods have
27658** been defined - so that the primitive locking methods are available
27659** as services to help with the implementation of proxy locking.
27660**
27661****
27662**
27663** The default locking schemes in SQLite use byte-range locks on the
27664** database file to coordinate safe, concurrent access by multiple readers
27665** and writers [http://sqlite.org/lockingv3.html].  The five file locking
27666** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
27667** as POSIX read & write locks over fixed set of locations (via fsctl),
27668** on AFP and SMB only exclusive byte-range locks are available via fsctl
27669** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
27670** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
27671** address in the shared range is taken for a SHARED lock, the entire
27672** shared range is taken for an EXCLUSIVE lock):
27673**
27674**      PENDING_BYTE        0x40000000
27675**      RESERVED_BYTE       0x40000001
27676**      SHARED_RANGE        0x40000002 -> 0x40000200
27677**
27678** This works well on the local file system, but shows a nearly 100x
27679** slowdown in read performance on AFP because the AFP client disables
27680** the read cache when byte-range locks are present.  Enabling the read
27681** cache exposes a cache coherency problem that is present on all OS X
27682** supported network file systems.  NFS and AFP both observe the
27683** close-to-open semantics for ensuring cache coherency
27684** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
27685** address the requirements for concurrent database access by multiple
27686** readers and writers
27687** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
27688**
27689** To address the performance and cache coherency issues, proxy file locking
27690** changes the way database access is controlled by limiting access to a
27691** single host at a time and moving file locks off of the database file
27692** and onto a proxy file on the local file system.
27693**
27694**
27695** Using proxy locks
27696** -----------------
27697**
27698** C APIs
27699**
27700**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
27701**                       <proxy_path> | ":auto:");
27702**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
27703**
27704**
27705** SQL pragmas
27706**
27707**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
27708**  PRAGMA [database.]lock_proxy_file
27709**
27710** Specifying ":auto:" means that if there is a conch file with a matching
27711** host ID in it, the proxy path in the conch file will be used, otherwise
27712** a proxy path based on the user's temp dir
27713** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
27714** actual proxy file name is generated from the name and path of the
27715** database file.  For example:
27716**
27717**       For database path "/Users/me/foo.db"
27718**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
27719**
27720** Once a lock proxy is configured for a database connection, it can not
27721** be removed, however it may be switched to a different proxy path via
27722** the above APIs (assuming the conch file is not being held by another
27723** connection or process).
27724**
27725**
27726** How proxy locking works
27727** -----------------------
27728**
27729** Proxy file locking relies primarily on two new supporting files:
27730**
27731**   *  conch file to limit access to the database file to a single host
27732**      at a time
27733**
27734**   *  proxy file to act as a proxy for the advisory locks normally
27735**      taken on the database
27736**
27737** The conch file - to use a proxy file, sqlite must first "hold the conch"
27738** by taking an sqlite-style shared lock on the conch file, reading the
27739** contents and comparing the host's unique host ID (see below) and lock
27740** proxy path against the values stored in the conch.  The conch file is
27741** stored in the same directory as the database file and the file name
27742** is patterned after the database file name as ".<databasename>-conch".
27743** If the conch file does not exist, or it's contents do not match the
27744** host ID and/or proxy path, then the lock is escalated to an exclusive
27745** lock and the conch file contents is updated with the host ID and proxy
27746** path and the lock is downgraded to a shared lock again.  If the conch
27747** is held by another process (with a shared lock), the exclusive lock
27748** will fail and SQLITE_BUSY is returned.
27749**
27750** The proxy file - a single-byte file used for all advisory file locks
27751** normally taken on the database file.   This allows for safe sharing
27752** of the database file for multiple readers and writers on the same
27753** host (the conch ensures that they all use the same local lock file).
27754**
27755** Requesting the lock proxy does not immediately take the conch, it is
27756** only taken when the first request to lock database file is made.
27757** This matches the semantics of the traditional locking behavior, where
27758** opening a connection to a database file does not take a lock on it.
27759** The shared lock and an open file descriptor are maintained until
27760** the connection to the database is closed.
27761**
27762** The proxy file and the lock file are never deleted so they only need
27763** to be created the first time they are used.
27764**
27765** Configuration options
27766** ---------------------
27767**
27768**  SQLITE_PREFER_PROXY_LOCKING
27769**
27770**       Database files accessed on non-local file systems are
27771**       automatically configured for proxy locking, lock files are
27772**       named automatically using the same logic as
27773**       PRAGMA lock_proxy_file=":auto:"
27774**
27775**  SQLITE_PROXY_DEBUG
27776**
27777**       Enables the logging of error messages during host id file
27778**       retrieval and creation
27779**
27780**  LOCKPROXYDIR
27781**
27782**       Overrides the default directory used for lock proxy files that
27783**       are named automatically via the ":auto:" setting
27784**
27785**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
27786**
27787**       Permissions to use when creating a directory for storing the
27788**       lock proxy files, only used when LOCKPROXYDIR is not set.
27789**
27790**
27791** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
27792** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
27793** force proxy locking to be used for every database file opened, and 0
27794** will force automatic proxy locking to be disabled for all database
27795** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
27796** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
27797*/
27798
27799/*
27800** Proxy locking is only available on MacOSX
27801*/
27802#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27803
27804/*
27805** The proxyLockingContext has the path and file structures for the remote
27806** and local proxy files in it
27807*/
27808typedef struct proxyLockingContext proxyLockingContext;
27809struct proxyLockingContext {
27810  unixFile *conchFile;         /* Open conch file */
27811  char *conchFilePath;         /* Name of the conch file */
27812  unixFile *lockProxy;         /* Open proxy lock file */
27813  char *lockProxyPath;         /* Name of the proxy lock file */
27814  char *dbPath;                /* Name of the open file */
27815  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
27816  void *oldLockingContext;     /* Original lockingcontext to restore on close */
27817  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
27818};
27819
27820/*
27821** The proxy lock file path for the database at dbPath is written into lPath,
27822** which must point to valid, writable memory large enough for a maxLen length
27823** file path.
27824*/
27825static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
27826  int len;
27827  int dbLen;
27828  int i;
27829
27830#ifdef LOCKPROXYDIR
27831  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
27832#else
27833# ifdef _CS_DARWIN_USER_TEMP_DIR
27834  {
27835    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
27836      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
27837               lPath, errno, getpid()));
27838      return SQLITE_IOERR_LOCK;
27839    }
27840    len = strlcat(lPath, "sqliteplocks", maxLen);
27841  }
27842# else
27843  len = strlcpy(lPath, "/tmp/", maxLen);
27844# endif
27845#endif
27846
27847  if( lPath[len-1]!='/' ){
27848    len = strlcat(lPath, "/", maxLen);
27849  }
27850
27851  /* transform the db path to a unique cache name */
27852  dbLen = (int)strlen(dbPath);
27853  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
27854    char c = dbPath[i];
27855    lPath[i+len] = (c=='/')?'_':c;
27856  }
27857  lPath[i+len]='\0';
27858  strlcat(lPath, ":auto:", maxLen);
27859  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
27860  return SQLITE_OK;
27861}
27862
27863/*
27864 ** Creates the lock file and any missing directories in lockPath
27865 */
27866static int proxyCreateLockPath(const char *lockPath){
27867  int i, len;
27868  char buf[MAXPATHLEN];
27869  int start = 0;
27870
27871  assert(lockPath!=NULL);
27872  /* try to create all the intermediate directories */
27873  len = (int)strlen(lockPath);
27874  buf[0] = lockPath[0];
27875  for( i=1; i<len; i++ ){
27876    if( lockPath[i] == '/' && (i - start > 0) ){
27877      /* only mkdir if leaf dir != "." or "/" or ".." */
27878      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
27879         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
27880        buf[i]='\0';
27881        if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
27882          int err=errno;
27883          if( err!=EEXIST ) {
27884            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
27885                     "'%s' proxy lock path=%s pid=%d\n",
27886                     buf, strerror(err), lockPath, getpid()));
27887            return err;
27888          }
27889        }
27890      }
27891      start=i+1;
27892    }
27893    buf[i] = lockPath[i];
27894  }
27895  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
27896  return 0;
27897}
27898
27899/*
27900** Create a new VFS file descriptor (stored in memory obtained from
27901** sqlite3_malloc) and open the file named "path" in the file descriptor.
27902**
27903** The caller is responsible not only for closing the file descriptor
27904** but also for freeing the memory associated with the file descriptor.
27905*/
27906static int proxyCreateUnixFile(
27907    const char *path,        /* path for the new unixFile */
27908    unixFile **ppFile,       /* unixFile created and returned by ref */
27909    int islockfile           /* if non zero missing dirs will be created */
27910) {
27911  int fd = -1;
27912  int dirfd = -1;
27913  unixFile *pNew;
27914  int rc = SQLITE_OK;
27915  int openFlags = O_RDWR | O_CREAT;
27916  sqlite3_vfs dummyVfs;
27917  int terrno = 0;
27918  UnixUnusedFd *pUnused = NULL;
27919
27920  /* 1. first try to open/create the file
27921  ** 2. if that fails, and this is a lock file (not-conch), try creating
27922  ** the parent directories and then try again.
27923  ** 3. if that fails, try to open the file read-only
27924  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
27925  */
27926  pUnused = findReusableFd(path, openFlags);
27927  if( pUnused ){
27928    fd = pUnused->fd;
27929  }else{
27930    pUnused = sqlite3_malloc(sizeof(*pUnused));
27931    if( !pUnused ){
27932      return SQLITE_NOMEM;
27933    }
27934  }
27935  if( fd<0 ){
27936    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27937    terrno = errno;
27938    if( fd<0 && errno==ENOENT && islockfile ){
27939      if( proxyCreateLockPath(path) == SQLITE_OK ){
27940        fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27941      }
27942    }
27943  }
27944  if( fd<0 ){
27945    openFlags = O_RDONLY;
27946    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
27947    terrno = errno;
27948  }
27949  if( fd<0 ){
27950    if( islockfile ){
27951      return SQLITE_BUSY;
27952    }
27953    switch (terrno) {
27954      case EACCES:
27955        return SQLITE_PERM;
27956      case EIO:
27957        return SQLITE_IOERR_LOCK; /* even though it is the conch */
27958      default:
27959        return SQLITE_CANTOPEN_BKPT;
27960    }
27961  }
27962
27963  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
27964  if( pNew==NULL ){
27965    rc = SQLITE_NOMEM;
27966    goto end_create_proxy;
27967  }
27968  memset(pNew, 0, sizeof(unixFile));
27969  pNew->openFlags = openFlags;
27970  dummyVfs.pAppData = (void*)&autolockIoFinder;
27971  pUnused->fd = fd;
27972  pUnused->flags = openFlags;
27973  pNew->pUnused = pUnused;
27974
27975  rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
27976  if( rc==SQLITE_OK ){
27977    *ppFile = pNew;
27978    return SQLITE_OK;
27979  }
27980end_create_proxy:
27981  close(fd); /* silently leak fd if error, we're already in error */
27982  sqlite3_free(pNew);
27983  sqlite3_free(pUnused);
27984  return rc;
27985}
27986
27987#ifdef SQLITE_TEST
27988/* simulate multiple hosts by creating unique hostid file paths */
27989SQLITE_API int sqlite3_hostid_num = 0;
27990#endif
27991
27992#define PROXY_HOSTIDLEN    16  /* conch file host id length */
27993
27994/* Not always defined in the headers as it ought to be */
27995extern int gethostuuid(uuid_t id, const struct timespec *wait);
27996
27997/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
27998** bytes of writable memory.
27999*/
28000static int proxyGetHostID(unsigned char *pHostID, int *pError){
28001  struct timespec timeout = {1, 0}; /* 1 sec timeout */
28002
28003  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28004  memset(pHostID, 0, PROXY_HOSTIDLEN);
28005  if( gethostuuid(pHostID, &timeout) ){
28006    int err = errno;
28007    if( pError ){
28008      *pError = err;
28009    }
28010    return SQLITE_IOERR;
28011  }
28012#ifdef SQLITE_TEST
28013  /* simulate multiple hosts by creating unique hostid file paths */
28014  if( sqlite3_hostid_num != 0){
28015    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28016  }
28017#endif
28018
28019  return SQLITE_OK;
28020}
28021
28022/* The conch file contains the header, host id and lock file path
28023 */
28024#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
28025#define PROXY_HEADERLEN    1   /* conch file header length */
28026#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
28027#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
28028
28029/*
28030** Takes an open conch file, copies the contents to a new path and then moves
28031** it back.  The newly created file's file descriptor is assigned to the
28032** conch file structure and finally the original conch file descriptor is
28033** closed.  Returns zero if successful.
28034*/
28035static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
28036  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28037  unixFile *conchFile = pCtx->conchFile;
28038  char tPath[MAXPATHLEN];
28039  char buf[PROXY_MAXCONCHLEN];
28040  char *cPath = pCtx->conchFilePath;
28041  size_t readLen = 0;
28042  size_t pathLen = 0;
28043  char errmsg[64] = "";
28044  int fd = -1;
28045  int rc = -1;
28046  UNUSED_PARAMETER(myHostID);
28047
28048  /* create a new path by replace the trailing '-conch' with '-break' */
28049  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
28050  if( pathLen>MAXPATHLEN || pathLen<6 ||
28051     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
28052    sprintf(errmsg, "path error (len %d)", (int)pathLen);
28053    goto end_breaklock;
28054  }
28055  /* read the conch content */
28056  readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
28057  if( readLen<PROXY_PATHINDEX ){
28058    sprintf(errmsg, "read error (len %d)", (int)readLen);
28059    goto end_breaklock;
28060  }
28061  /* write it out to the temporary break file */
28062  fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
28063  if( fd<0 ){
28064    sprintf(errmsg, "create failed (%d)", errno);
28065    goto end_breaklock;
28066  }
28067  if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
28068    sprintf(errmsg, "write failed (%d)", errno);
28069    goto end_breaklock;
28070  }
28071  if( rename(tPath, cPath) ){
28072    sprintf(errmsg, "rename failed (%d)", errno);
28073    goto end_breaklock;
28074  }
28075  rc = 0;
28076  fprintf(stderr, "broke stale lock on %s\n", cPath);
28077  close(conchFile->h);
28078  conchFile->h = fd;
28079  conchFile->openFlags = O_RDWR | O_CREAT;
28080
28081end_breaklock:
28082  if( rc ){
28083    if( fd>=0 ){
28084      unlink(tPath);
28085      close(fd);
28086    }
28087    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
28088  }
28089  return rc;
28090}
28091
28092/* Take the requested lock on the conch file and break a stale lock if the
28093** host id matches.
28094*/
28095static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
28096  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28097  unixFile *conchFile = pCtx->conchFile;
28098  int rc = SQLITE_OK;
28099  int nTries = 0;
28100  struct timespec conchModTime;
28101
28102  do {
28103    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28104    nTries ++;
28105    if( rc==SQLITE_BUSY ){
28106      /* If the lock failed (busy):
28107       * 1st try: get the mod time of the conch, wait 0.5s and try again.
28108       * 2nd try: fail if the mod time changed or host id is different, wait
28109       *           10 sec and try again
28110       * 3rd try: break the lock unless the mod time has changed.
28111       */
28112      struct stat buf;
28113      if( fstat(conchFile->h, &buf) ){
28114        pFile->lastErrno = errno;
28115        return SQLITE_IOERR_LOCK;
28116      }
28117
28118      if( nTries==1 ){
28119        conchModTime = buf.st_mtimespec;
28120        usleep(500000); /* wait 0.5 sec and try the lock again*/
28121        continue;
28122      }
28123
28124      assert( nTries>1 );
28125      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
28126         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
28127        return SQLITE_BUSY;
28128      }
28129
28130      if( nTries==2 ){
28131        char tBuf[PROXY_MAXCONCHLEN];
28132        int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
28133        if( len<0 ){
28134          pFile->lastErrno = errno;
28135          return SQLITE_IOERR_LOCK;
28136        }
28137        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
28138          /* don't break the lock if the host id doesn't match */
28139          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
28140            return SQLITE_BUSY;
28141          }
28142        }else{
28143          /* don't break the lock on short read or a version mismatch */
28144          return SQLITE_BUSY;
28145        }
28146        usleep(10000000); /* wait 10 sec and try the lock again */
28147        continue;
28148      }
28149
28150      assert( nTries==3 );
28151      if( 0==proxyBreakConchLock(pFile, myHostID) ){
28152        rc = SQLITE_OK;
28153        if( lockType==EXCLUSIVE_LOCK ){
28154          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
28155        }
28156        if( !rc ){
28157          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28158        }
28159      }
28160    }
28161  } while( rc==SQLITE_BUSY && nTries<3 );
28162
28163  return rc;
28164}
28165
28166/* Takes the conch by taking a shared lock and read the contents conch, if
28167** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
28168** lockPath means that the lockPath in the conch file will be used if the
28169** host IDs match, or a new lock path will be generated automatically
28170** and written to the conch file.
28171*/
28172static int proxyTakeConch(unixFile *pFile){
28173  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28174
28175  if( pCtx->conchHeld!=0 ){
28176    return SQLITE_OK;
28177  }else{
28178    unixFile *conchFile = pCtx->conchFile;
28179    uuid_t myHostID;
28180    int pError = 0;
28181    char readBuf[PROXY_MAXCONCHLEN];
28182    char lockPath[MAXPATHLEN];
28183    char *tempLockPath = NULL;
28184    int rc = SQLITE_OK;
28185    int createConch = 0;
28186    int hostIdMatch = 0;
28187    int readLen = 0;
28188    int tryOldLockPath = 0;
28189    int forceNewLockPath = 0;
28190
28191    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
28192             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
28193
28194    rc = proxyGetHostID(myHostID, &pError);
28195    if( (rc&0xff)==SQLITE_IOERR ){
28196      pFile->lastErrno = pError;
28197      goto end_takeconch;
28198    }
28199    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
28200    if( rc!=SQLITE_OK ){
28201      goto end_takeconch;
28202    }
28203    /* read the existing conch file */
28204    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
28205    if( readLen<0 ){
28206      /* I/O error: lastErrno set by seekAndRead */
28207      pFile->lastErrno = conchFile->lastErrno;
28208      rc = SQLITE_IOERR_READ;
28209      goto end_takeconch;
28210    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
28211             readBuf[0]!=(char)PROXY_CONCHVERSION ){
28212      /* a short read or version format mismatch means we need to create a new
28213      ** conch file.
28214      */
28215      createConch = 1;
28216    }
28217    /* if the host id matches and the lock path already exists in the conch
28218    ** we'll try to use the path there, if we can't open that path, we'll
28219    ** retry with a new auto-generated path
28220    */
28221    do { /* in case we need to try again for an :auto: named lock file */
28222
28223      if( !createConch && !forceNewLockPath ){
28224        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
28225                                  PROXY_HOSTIDLEN);
28226        /* if the conch has data compare the contents */
28227        if( !pCtx->lockProxyPath ){
28228          /* for auto-named local lock file, just check the host ID and we'll
28229           ** use the local lock file path that's already in there
28230           */
28231          if( hostIdMatch ){
28232            size_t pathLen = (readLen - PROXY_PATHINDEX);
28233
28234            if( pathLen>=MAXPATHLEN ){
28235              pathLen=MAXPATHLEN-1;
28236            }
28237            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28238            lockPath[pathLen] = 0;
28239            tempLockPath = lockPath;
28240            tryOldLockPath = 1;
28241            /* create a copy of the lock path if the conch is taken */
28242            goto end_takeconch;
28243          }
28244        }else if( hostIdMatch
28245               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28246                           readLen-PROXY_PATHINDEX)
28247        ){
28248          /* conch host and lock path match */
28249          goto end_takeconch;
28250        }
28251      }
28252
28253      /* if the conch isn't writable and doesn't match, we can't take it */
28254      if( (conchFile->openFlags&O_RDWR) == 0 ){
28255        rc = SQLITE_BUSY;
28256        goto end_takeconch;
28257      }
28258
28259      /* either the conch didn't match or we need to create a new one */
28260      if( !pCtx->lockProxyPath ){
28261        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28262        tempLockPath = lockPath;
28263        /* create a copy of the lock path _only_ if the conch is taken */
28264      }
28265
28266      /* update conch with host and path (this will fail if other process
28267      ** has a shared lock already), if the host id matches, use the big
28268      ** stick.
28269      */
28270      futimes(conchFile->h, NULL);
28271      if( hostIdMatch && !createConch ){
28272        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
28273          /* We are trying for an exclusive lock but another thread in this
28274           ** same process is still holding a shared lock. */
28275          rc = SQLITE_BUSY;
28276        } else {
28277          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
28278        }
28279      }else{
28280        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
28281      }
28282      if( rc==SQLITE_OK ){
28283        char writeBuffer[PROXY_MAXCONCHLEN];
28284        int writeSize = 0;
28285
28286        writeBuffer[0] = (char)PROXY_CONCHVERSION;
28287        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
28288        if( pCtx->lockProxyPath!=NULL ){
28289          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
28290        }else{
28291          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
28292        }
28293        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
28294        ftruncate(conchFile->h, writeSize);
28295        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
28296        fsync(conchFile->h);
28297        /* If we created a new conch file (not just updated the contents of a
28298         ** valid conch file), try to match the permissions of the database
28299         */
28300        if( rc==SQLITE_OK && createConch ){
28301          struct stat buf;
28302          int err = fstat(pFile->h, &buf);
28303          if( err==0 ){
28304            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
28305                                        S_IROTH|S_IWOTH);
28306            /* try to match the database file R/W permissions, ignore failure */
28307#ifndef SQLITE_PROXY_DEBUG
28308            fchmod(conchFile->h, cmode);
28309#else
28310            if( fchmod(conchFile->h, cmode)!=0 ){
28311              int code = errno;
28312              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
28313                      cmode, code, strerror(code));
28314            } else {
28315              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
28316            }
28317          }else{
28318            int code = errno;
28319            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
28320                    err, code, strerror(code));
28321#endif
28322          }
28323        }
28324      }
28325      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28326
28327    end_takeconch:
28328      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
28329      if( rc==SQLITE_OK && pFile->openFlags ){
28330        if( pFile->h>=0 ){
28331#ifdef STRICT_CLOSE_ERROR
28332          if( close(pFile->h) ){
28333            pFile->lastErrno = errno;
28334            return SQLITE_IOERR_CLOSE;
28335          }
28336#else
28337          close(pFile->h); /* silently leak fd if fail */
28338#endif
28339        }
28340        pFile->h = -1;
28341        int fd = open(pCtx->dbPath, pFile->openFlags,
28342                      SQLITE_DEFAULT_FILE_PERMISSIONS);
28343        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
28344        if( fd>=0 ){
28345          pFile->h = fd;
28346        }else{
28347          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
28348           during locking */
28349        }
28350      }
28351      if( rc==SQLITE_OK && !pCtx->lockProxy ){
28352        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
28353        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
28354        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
28355          /* we couldn't create the proxy lock file with the old lock file path
28356           ** so try again via auto-naming
28357           */
28358          forceNewLockPath = 1;
28359          tryOldLockPath = 0;
28360          continue; /* go back to the do {} while start point, try again */
28361        }
28362      }
28363      if( rc==SQLITE_OK ){
28364        /* Need to make a copy of path if we extracted the value
28365         ** from the conch file or the path was allocated on the stack
28366         */
28367        if( tempLockPath ){
28368          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28369          if( !pCtx->lockProxyPath ){
28370            rc = SQLITE_NOMEM;
28371          }
28372        }
28373      }
28374      if( rc==SQLITE_OK ){
28375        pCtx->conchHeld = 1;
28376
28377        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28378          afpLockingContext *afpCtx;
28379          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28380          afpCtx->dbPath = pCtx->lockProxyPath;
28381        }
28382      } else {
28383        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28384      }
28385      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28386               rc==SQLITE_OK?"ok":"failed"));
28387      return rc;
28388    } while (1); /* in case we need to retry the :auto: lock file -
28389                 ** we should never get here except via the 'continue' call. */
28390  }
28391}
28392
28393/*
28394** If pFile holds a lock on a conch file, then release that lock.
28395*/
28396static int proxyReleaseConch(unixFile *pFile){
28397  int rc = SQLITE_OK;         /* Subroutine return code */
28398  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28399  unixFile *conchFile;        /* Name of the conch file */
28400
28401  pCtx = (proxyLockingContext *)pFile->lockingContext;
28402  conchFile = pCtx->conchFile;
28403  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28404           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
28405           getpid()));
28406  if( pCtx->conchHeld>0 ){
28407    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28408  }
28409  pCtx->conchHeld = 0;
28410  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28411           (rc==SQLITE_OK ? "ok" : "failed")));
28412  return rc;
28413}
28414
28415/*
28416** Given the name of a database file, compute the name of its conch file.
28417** Store the conch filename in memory obtained from sqlite3_malloc().
28418** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28419** or SQLITE_NOMEM if unable to obtain memory.
28420**
28421** The caller is responsible for ensuring that the allocated memory
28422** space is eventually freed.
28423**
28424** *pConchPath is set to NULL if a memory allocation error occurs.
28425*/
28426static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28427  int i;                        /* Loop counter */
28428  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28429  char *conchPath;              /* buffer in which to construct conch name */
28430
28431  /* Allocate space for the conch filename and initialize the name to
28432  ** the name of the original database file. */
28433  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28434  if( conchPath==0 ){
28435    return SQLITE_NOMEM;
28436  }
28437  memcpy(conchPath, dbPath, len+1);
28438
28439  /* now insert a "." before the last / character */
28440  for( i=(len-1); i>=0; i-- ){
28441    if( conchPath[i]=='/' ){
28442      i++;
28443      break;
28444    }
28445  }
28446  conchPath[i]='.';
28447  while ( i<len ){
28448    conchPath[i+1]=dbPath[i];
28449    i++;
28450  }
28451
28452  /* append the "-conch" suffix to the file */
28453  memcpy(&conchPath[i+1], "-conch", 7);
28454  assert( (int)strlen(conchPath) == len+7 );
28455
28456  return SQLITE_OK;
28457}
28458
28459
28460/* Takes a fully configured proxy locking-style unix file and switches
28461** the local lock file path
28462*/
28463static int switchLockProxyPath(unixFile *pFile, const char *path) {
28464  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28465  char *oldPath = pCtx->lockProxyPath;
28466  int rc = SQLITE_OK;
28467
28468  if( pFile->eFileLock!=NO_LOCK ){
28469    return SQLITE_BUSY;
28470  }
28471
28472  /* nothing to do if the path is NULL, :auto: or matches the existing path */
28473  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28474    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28475    return SQLITE_OK;
28476  }else{
28477    unixFile *lockProxy = pCtx->lockProxy;
28478    pCtx->lockProxy=NULL;
28479    pCtx->conchHeld = 0;
28480    if( lockProxy!=NULL ){
28481      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28482      if( rc ) return rc;
28483      sqlite3_free(lockProxy);
28484    }
28485    sqlite3_free(oldPath);
28486    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28487  }
28488
28489  return rc;
28490}
28491
28492/*
28493** pFile is a file that has been opened by a prior xOpen call.  dbPath
28494** is a string buffer at least MAXPATHLEN+1 characters in size.
28495**
28496** This routine find the filename associated with pFile and writes it
28497** int dbPath.
28498*/
28499static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28500#if defined(__APPLE__)
28501  if( pFile->pMethod == &afpIoMethods ){
28502    /* afp style keeps a reference to the db path in the filePath field
28503    ** of the struct */
28504    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28505    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28506  } else
28507#endif
28508  if( pFile->pMethod == &dotlockIoMethods ){
28509    /* dot lock style uses the locking context to store the dot lock
28510    ** file path */
28511    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28512    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
28513  }else{
28514    /* all other styles use the locking context to store the db file path */
28515    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28516    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
28517  }
28518  return SQLITE_OK;
28519}
28520
28521/*
28522** Takes an already filled in unix file and alters it so all file locking
28523** will be performed on the local proxy lock file.  The following fields
28524** are preserved in the locking context so that they can be restored and
28525** the unix structure properly cleaned up at close time:
28526**  ->lockingContext
28527**  ->pMethod
28528*/
28529static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
28530  proxyLockingContext *pCtx;
28531  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
28532  char *lockPath=NULL;
28533  int rc = SQLITE_OK;
28534
28535  if( pFile->eFileLock!=NO_LOCK ){
28536    return SQLITE_BUSY;
28537  }
28538  proxyGetDbPathForUnixFile(pFile, dbPath);
28539  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
28540    lockPath=NULL;
28541  }else{
28542    lockPath=(char *)path;
28543  }
28544
28545  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28546           (lockPath ? lockPath : ":auto:"), getpid()));
28547
28548  pCtx = sqlite3_malloc( sizeof(*pCtx) );
28549  if( pCtx==0 ){
28550    return SQLITE_NOMEM;
28551  }
28552  memset(pCtx, 0, sizeof(*pCtx));
28553
28554  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
28555  if( rc==SQLITE_OK ){
28556    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
28557    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
28558      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
28559      ** (c) the file system is read-only, then enable no-locking access.
28560      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
28561      ** that openFlags will have only one of O_RDONLY or O_RDWR.
28562      */
28563      struct statfs fsInfo;
28564      struct stat conchInfo;
28565      int goLockless = 0;
28566
28567      if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
28568        int err = errno;
28569        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
28570          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
28571        }
28572      }
28573      if( goLockless ){
28574        pCtx->conchHeld = -1; /* read only FS/ lockless */
28575        rc = SQLITE_OK;
28576      }
28577    }
28578  }
28579  if( rc==SQLITE_OK && lockPath ){
28580    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
28581  }
28582
28583  if( rc==SQLITE_OK ){
28584    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
28585    if( pCtx->dbPath==NULL ){
28586      rc = SQLITE_NOMEM;
28587    }
28588  }
28589  if( rc==SQLITE_OK ){
28590    /* all memory is allocated, proxys are created and assigned,
28591    ** switch the locking context and pMethod then return.
28592    */
28593    pCtx->oldLockingContext = pFile->lockingContext;
28594    pFile->lockingContext = pCtx;
28595    pCtx->pOldMethod = pFile->pMethod;
28596    pFile->pMethod = &proxyIoMethods;
28597  }else{
28598    if( pCtx->conchFile ){
28599      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28600      sqlite3_free(pCtx->conchFile);
28601    }
28602    sqlite3DbFree(0, pCtx->lockProxyPath);
28603    sqlite3_free(pCtx->conchFilePath);
28604    sqlite3_free(pCtx);
28605  }
28606  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
28607           (rc==SQLITE_OK ? "ok" : "failed")));
28608  return rc;
28609}
28610
28611
28612/*
28613** This routine handles sqlite3_file_control() calls that are specific
28614** to proxy locking.
28615*/
28616static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
28617  switch( op ){
28618    case SQLITE_GET_LOCKPROXYFILE: {
28619      unixFile *pFile = (unixFile*)id;
28620      if( pFile->pMethod == &proxyIoMethods ){
28621        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28622        proxyTakeConch(pFile);
28623        if( pCtx->lockProxyPath ){
28624          *(const char **)pArg = pCtx->lockProxyPath;
28625        }else{
28626          *(const char **)pArg = ":auto: (not held)";
28627        }
28628      } else {
28629        *(const char **)pArg = NULL;
28630      }
28631      return SQLITE_OK;
28632    }
28633    case SQLITE_SET_LOCKPROXYFILE: {
28634      unixFile *pFile = (unixFile*)id;
28635      int rc = SQLITE_OK;
28636      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
28637      if( pArg==NULL || (const char *)pArg==0 ){
28638        if( isProxyStyle ){
28639          /* turn off proxy locking - not supported */
28640          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
28641        }else{
28642          /* turn off proxy locking - already off - NOOP */
28643          rc = SQLITE_OK;
28644        }
28645      }else{
28646        const char *proxyPath = (const char *)pArg;
28647        if( isProxyStyle ){
28648          proxyLockingContext *pCtx =
28649            (proxyLockingContext*)pFile->lockingContext;
28650          if( !strcmp(pArg, ":auto:")
28651           || (pCtx->lockProxyPath &&
28652               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
28653          ){
28654            rc = SQLITE_OK;
28655          }else{
28656            rc = switchLockProxyPath(pFile, proxyPath);
28657          }
28658        }else{
28659          /* turn on proxy file locking */
28660          rc = proxyTransformUnixFile(pFile, proxyPath);
28661        }
28662      }
28663      return rc;
28664    }
28665    default: {
28666      assert( 0 );  /* The call assures that only valid opcodes are sent */
28667    }
28668  }
28669  /*NOTREACHED*/
28670  return SQLITE_ERROR;
28671}
28672
28673/*
28674** Within this division (the proxying locking implementation) the procedures
28675** above this point are all utilities.  The lock-related methods of the
28676** proxy-locking sqlite3_io_method object follow.
28677*/
28678
28679
28680/*
28681** This routine checks if there is a RESERVED lock held on the specified
28682** file by this or any other process. If such a lock is held, set *pResOut
28683** to a non-zero value otherwise *pResOut is set to zero.  The return value
28684** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28685*/
28686static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
28687  unixFile *pFile = (unixFile*)id;
28688  int rc = proxyTakeConch(pFile);
28689  if( rc==SQLITE_OK ){
28690    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28691    if( pCtx->conchHeld>0 ){
28692      unixFile *proxy = pCtx->lockProxy;
28693      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
28694    }else{ /* conchHeld < 0 is lockless */
28695      pResOut=0;
28696    }
28697  }
28698  return rc;
28699}
28700
28701/*
28702** Lock the file with the lock specified by parameter eFileLock - one
28703** of the following:
28704**
28705**     (1) SHARED_LOCK
28706**     (2) RESERVED_LOCK
28707**     (3) PENDING_LOCK
28708**     (4) EXCLUSIVE_LOCK
28709**
28710** Sometimes when requesting one lock state, additional lock states
28711** are inserted in between.  The locking might fail on one of the later
28712** transitions leaving the lock state different from what it started but
28713** still short of its goal.  The following chart shows the allowed
28714** transitions and the inserted intermediate states:
28715**
28716**    UNLOCKED -> SHARED
28717**    SHARED -> RESERVED
28718**    SHARED -> (PENDING) -> EXCLUSIVE
28719**    RESERVED -> (PENDING) -> EXCLUSIVE
28720**    PENDING -> EXCLUSIVE
28721**
28722** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28723** routine to lower a locking level.
28724*/
28725static int proxyLock(sqlite3_file *id, int eFileLock) {
28726  unixFile *pFile = (unixFile*)id;
28727  int rc = proxyTakeConch(pFile);
28728  if( rc==SQLITE_OK ){
28729    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28730    if( pCtx->conchHeld>0 ){
28731      unixFile *proxy = pCtx->lockProxy;
28732      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
28733      pFile->eFileLock = proxy->eFileLock;
28734    }else{
28735      /* conchHeld < 0 is lockless */
28736    }
28737  }
28738  return rc;
28739}
28740
28741
28742/*
28743** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28744** must be either NO_LOCK or SHARED_LOCK.
28745**
28746** If the locking level of the file descriptor is already at or below
28747** the requested locking level, this routine is a no-op.
28748*/
28749static int proxyUnlock(sqlite3_file *id, int eFileLock) {
28750  unixFile *pFile = (unixFile*)id;
28751  int rc = proxyTakeConch(pFile);
28752  if( rc==SQLITE_OK ){
28753    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28754    if( pCtx->conchHeld>0 ){
28755      unixFile *proxy = pCtx->lockProxy;
28756      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
28757      pFile->eFileLock = proxy->eFileLock;
28758    }else{
28759      /* conchHeld < 0 is lockless */
28760    }
28761  }
28762  return rc;
28763}
28764
28765/*
28766** Close a file that uses proxy locks.
28767*/
28768static int proxyClose(sqlite3_file *id) {
28769  if( id ){
28770    unixFile *pFile = (unixFile*)id;
28771    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
28772    unixFile *lockProxy = pCtx->lockProxy;
28773    unixFile *conchFile = pCtx->conchFile;
28774    int rc = SQLITE_OK;
28775
28776    if( lockProxy ){
28777      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
28778      if( rc ) return rc;
28779      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
28780      if( rc ) return rc;
28781      sqlite3_free(lockProxy);
28782      pCtx->lockProxy = 0;
28783    }
28784    if( conchFile ){
28785      if( pCtx->conchHeld ){
28786        rc = proxyReleaseConch(pFile);
28787        if( rc ) return rc;
28788      }
28789      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
28790      if( rc ) return rc;
28791      sqlite3_free(conchFile);
28792    }
28793    sqlite3DbFree(0, pCtx->lockProxyPath);
28794    sqlite3_free(pCtx->conchFilePath);
28795    sqlite3DbFree(0, pCtx->dbPath);
28796    /* restore the original locking context and pMethod then close it */
28797    pFile->lockingContext = pCtx->oldLockingContext;
28798    pFile->pMethod = pCtx->pOldMethod;
28799    sqlite3_free(pCtx);
28800    return pFile->pMethod->xClose(id);
28801  }
28802  return SQLITE_OK;
28803}
28804
28805
28806
28807#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28808/*
28809** The proxy locking style is intended for use with AFP filesystems.
28810** And since AFP is only supported on MacOSX, the proxy locking is also
28811** restricted to MacOSX.
28812**
28813**
28814******************* End of the proxy lock implementation **********************
28815******************************************************************************/
28816
28817/*
28818** Initialize the operating system interface.
28819**
28820** This routine registers all VFS implementations for unix-like operating
28821** systems.  This routine, and the sqlite3_os_end() routine that follows,
28822** should be the only routines in this file that are visible from other
28823** files.
28824**
28825** This routine is called once during SQLite initialization and by a
28826** single thread.  The memory allocation and mutex subsystems have not
28827** necessarily been initialized when this routine is called, and so they
28828** should not be used.
28829*/
28830SQLITE_API int sqlite3_os_init(void){
28831  /*
28832  ** The following macro defines an initializer for an sqlite3_vfs object.
28833  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
28834  ** to the "finder" function.  (pAppData is a pointer to a pointer because
28835  ** silly C90 rules prohibit a void* from being cast to a function pointer
28836  ** and so we have to go through the intermediate pointer to avoid problems
28837  ** when compiling with -pedantic-errors on GCC.)
28838  **
28839  ** The FINDER parameter to this macro is the name of the pointer to the
28840  ** finder-function.  The finder-function returns a pointer to the
28841  ** sqlite_io_methods object that implements the desired locking
28842  ** behaviors.  See the division above that contains the IOMETHODS
28843  ** macro for addition information on finder-functions.
28844  **
28845  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
28846  ** object.  But the "autolockIoFinder" available on MacOSX does a little
28847  ** more than that; it looks at the filesystem type that hosts the
28848  ** database file and tries to choose an locking method appropriate for
28849  ** that filesystem time.
28850  */
28851  #define UNIXVFS(VFSNAME, FINDER) {                        \
28852    2,                    /* iVersion */                    \
28853    sizeof(unixFile),     /* szOsFile */                    \
28854    MAX_PATHNAME,         /* mxPathname */                  \
28855    0,                    /* pNext */                       \
28856    VFSNAME,              /* zName */                       \
28857    (void*)&FINDER,       /* pAppData */                    \
28858    unixOpen,             /* xOpen */                       \
28859    unixDelete,           /* xDelete */                     \
28860    unixAccess,           /* xAccess */                     \
28861    unixFullPathname,     /* xFullPathname */               \
28862    unixDlOpen,           /* xDlOpen */                     \
28863    unixDlError,          /* xDlError */                    \
28864    unixDlSym,            /* xDlSym */                      \
28865    unixDlClose,          /* xDlClose */                    \
28866    unixRandomness,       /* xRandomness */                 \
28867    unixSleep,            /* xSleep */                      \
28868    unixCurrentTime,      /* xCurrentTime */                \
28869    unixGetLastError,     /* xGetLastError */               \
28870    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
28871  }
28872
28873  /*
28874  ** All default VFSes for unix are contained in the following array.
28875  **
28876  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
28877  ** by the SQLite core when the VFS is registered.  So the following
28878  ** array cannot be const.
28879  */
28880  static sqlite3_vfs aVfs[] = {
28881#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
28882    UNIXVFS("unix",          autolockIoFinder ),
28883#else
28884    UNIXVFS("unix",          posixIoFinder ),
28885#endif
28886    UNIXVFS("unix-none",     nolockIoFinder ),
28887    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
28888#if OS_VXWORKS
28889    UNIXVFS("unix-namedsem", semIoFinder ),
28890#endif
28891#if SQLITE_ENABLE_LOCKING_STYLE
28892    UNIXVFS("unix-posix",    posixIoFinder ),
28893#if !OS_VXWORKS
28894    UNIXVFS("unix-flock",    flockIoFinder ),
28895#endif
28896#endif
28897#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28898    UNIXVFS("unix-afp",      afpIoFinder ),
28899    UNIXVFS("unix-nfs",      nfsIoFinder ),
28900    UNIXVFS("unix-proxy",    proxyIoFinder ),
28901#endif
28902  };
28903  unsigned int i;          /* Loop counter */
28904
28905  /* Register all VFSes defined in the aVfs[] array */
28906  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
28907    sqlite3_vfs_register(&aVfs[i], i==0);
28908  }
28909  return SQLITE_OK;
28910}
28911
28912/*
28913** Shutdown the operating system interface.
28914**
28915** Some operating systems might need to do some cleanup in this routine,
28916** to release dynamically allocated objects.  But not on unix.
28917** This routine is a no-op for unix.
28918*/
28919SQLITE_API int sqlite3_os_end(void){
28920  return SQLITE_OK;
28921}
28922
28923#endif /* SQLITE_OS_UNIX */
28924
28925/************** End of os_unix.c *********************************************/
28926/************** Begin file os_win.c ******************************************/
28927/*
28928** 2004 May 22
28929**
28930** The author disclaims copyright to this source code.  In place of
28931** a legal notice, here is a blessing:
28932**
28933**    May you do good and not evil.
28934**    May you find forgiveness for yourself and forgive others.
28935**    May you share freely, never taking more than you give.
28936**
28937******************************************************************************
28938**
28939** This file contains code that is specific to windows.
28940*/
28941#if SQLITE_OS_WIN               /* This file is used for windows only */
28942
28943
28944/*
28945** A Note About Memory Allocation:
28946**
28947** This driver uses malloc()/free() directly rather than going through
28948** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
28949** are designed for use on embedded systems where memory is scarce and
28950** malloc failures happen frequently.  Win32 does not typically run on
28951** embedded systems, and when it does the developers normally have bigger
28952** problems to worry about than running out of memory.  So there is not
28953** a compelling need to use the wrappers.
28954**
28955** But there is a good reason to not use the wrappers.  If we use the
28956** wrappers then we will get simulated malloc() failures within this
28957** driver.  And that causes all kinds of problems for our tests.  We
28958** could enhance SQLite to deal with simulated malloc failures within
28959** the OS driver, but the code to deal with those failure would not
28960** be exercised on Linux (which does not need to malloc() in the driver)
28961** and so we would have difficulty writing coverage tests for that
28962** code.  Better to leave the code out, we think.
28963**
28964** The point of this discussion is as follows:  When creating a new
28965** OS layer for an embedded system, if you use this file as an example,
28966** avoid the use of malloc()/free().  Those routines work ok on windows
28967** desktops but not so well in embedded systems.
28968*/
28969
28970#include <winbase.h>
28971
28972#ifdef __CYGWIN__
28973# include <sys/cygwin.h>
28974#endif
28975
28976/*
28977** Macros used to determine whether or not to use threads.
28978*/
28979#if defined(THREADSAFE) && THREADSAFE
28980# define SQLITE_W32_THREADS 1
28981#endif
28982
28983/*
28984** Include code that is common to all os_*.c files
28985*/
28986/************** Include os_common.h in the middle of os_win.c ****************/
28987/************** Begin file os_common.h ***************************************/
28988/*
28989** 2004 May 22
28990**
28991** The author disclaims copyright to this source code.  In place of
28992** a legal notice, here is a blessing:
28993**
28994**    May you do good and not evil.
28995**    May you find forgiveness for yourself and forgive others.
28996**    May you share freely, never taking more than you give.
28997**
28998******************************************************************************
28999**
29000** This file contains macros and a little bit of code that is common to
29001** all of the platform-specific files (os_*.c) and is #included into those
29002** files.
29003**
29004** This file should be #included by the os_*.c files only.  It is not a
29005** general purpose header file.
29006*/
29007#ifndef _OS_COMMON_H_
29008#define _OS_COMMON_H_
29009
29010/*
29011** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29012** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29013** switch.  The following code should catch this problem at compile-time.
29014*/
29015#ifdef MEMORY_DEBUG
29016# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29017#endif
29018
29019#ifdef SQLITE_DEBUG
29020SQLITE_PRIVATE int sqlite3OSTrace = 0;
29021#define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
29022#else
29023#define OSTRACE(X)
29024#endif
29025
29026/*
29027** Macros for performance tracing.  Normally turned off.  Only works
29028** on i486 hardware.
29029*/
29030#ifdef SQLITE_PERFORMANCE_TRACE
29031
29032/*
29033** hwtime.h contains inline assembler code for implementing
29034** high-performance timing routines.
29035*/
29036/************** Include hwtime.h in the middle of os_common.h ****************/
29037/************** Begin file hwtime.h ******************************************/
29038/*
29039** 2008 May 27
29040**
29041** The author disclaims copyright to this source code.  In place of
29042** a legal notice, here is a blessing:
29043**
29044**    May you do good and not evil.
29045**    May you find forgiveness for yourself and forgive others.
29046**    May you share freely, never taking more than you give.
29047**
29048******************************************************************************
29049**
29050** This file contains inline asm code for retrieving "high-performance"
29051** counters for x86 class CPUs.
29052*/
29053#ifndef _HWTIME_H_
29054#define _HWTIME_H_
29055
29056/*
29057** The following routine only works on pentium-class (or newer) processors.
29058** It uses the RDTSC opcode to read the cycle count value out of the
29059** processor and returns that value.  This can be used for high-res
29060** profiling.
29061*/
29062#if (defined(__GNUC__) || defined(_MSC_VER)) && \
29063      (defined(i386) || defined(__i386__) || defined(_M_IX86))
29064
29065  #if defined(__GNUC__)
29066
29067  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29068     unsigned int lo, hi;
29069     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29070     return (sqlite_uint64)hi << 32 | lo;
29071  }
29072
29073  #elif defined(_MSC_VER)
29074
29075  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29076     __asm {
29077        rdtsc
29078        ret       ; return value at EDX:EAX
29079     }
29080  }
29081
29082  #endif
29083
29084#elif (defined(__GNUC__) && defined(__x86_64__))
29085
29086  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29087      unsigned long val;
29088      __asm__ __volatile__ ("rdtsc" : "=A" (val));
29089      return val;
29090  }
29091
29092#elif (defined(__GNUC__) && defined(__ppc__))
29093
29094  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29095      unsigned long long retval;
29096      unsigned long junk;
29097      __asm__ __volatile__ ("\n\
29098          1:      mftbu   %1\n\
29099                  mftb    %L0\n\
29100                  mftbu   %0\n\
29101                  cmpw    %0,%1\n\
29102                  bne     1b"
29103                  : "=r" (retval), "=r" (junk));
29104      return retval;
29105  }
29106
29107#else
29108
29109  #error Need implementation of sqlite3Hwtime() for your platform.
29110
29111  /*
29112  ** To compile without implementing sqlite3Hwtime() for your platform,
29113  ** you can remove the above #error and use the following
29114  ** stub function.  You will lose timing support for many
29115  ** of the debugging and testing utilities, but it should at
29116  ** least compile and run.
29117  */
29118SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29119
29120#endif
29121
29122#endif /* !defined(_HWTIME_H_) */
29123
29124/************** End of hwtime.h **********************************************/
29125/************** Continuing where we left off in os_common.h ******************/
29126
29127static sqlite_uint64 g_start;
29128static sqlite_uint64 g_elapsed;
29129#define TIMER_START       g_start=sqlite3Hwtime()
29130#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29131#define TIMER_ELAPSED     g_elapsed
29132#else
29133#define TIMER_START
29134#define TIMER_END
29135#define TIMER_ELAPSED     ((sqlite_uint64)0)
29136#endif
29137
29138/*
29139** If we compile with the SQLITE_TEST macro set, then the following block
29140** of code will give us the ability to simulate a disk I/O error.  This
29141** is used for testing the I/O recovery logic.
29142*/
29143#ifdef SQLITE_TEST
29144SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
29145SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
29146SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
29147SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
29148SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
29149SQLITE_API int sqlite3_diskfull_pending = 0;
29150SQLITE_API int sqlite3_diskfull = 0;
29151#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29152#define SimulateIOError(CODE)  \
29153  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29154       || sqlite3_io_error_pending-- == 1 )  \
29155              { local_ioerr(); CODE; }
29156static void local_ioerr(){
29157  IOTRACE(("IOERR\n"));
29158  sqlite3_io_error_hit++;
29159  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29160}
29161#define SimulateDiskfullError(CODE) \
29162   if( sqlite3_diskfull_pending ){ \
29163     if( sqlite3_diskfull_pending == 1 ){ \
29164       local_ioerr(); \
29165       sqlite3_diskfull = 1; \
29166       sqlite3_io_error_hit = 1; \
29167       CODE; \
29168     }else{ \
29169       sqlite3_diskfull_pending--; \
29170     } \
29171   }
29172#else
29173#define SimulateIOErrorBenign(X)
29174#define SimulateIOError(A)
29175#define SimulateDiskfullError(A)
29176#endif
29177
29178/*
29179** When testing, keep a count of the number of open files.
29180*/
29181#ifdef SQLITE_TEST
29182SQLITE_API int sqlite3_open_file_count = 0;
29183#define OpenCounter(X)  sqlite3_open_file_count+=(X)
29184#else
29185#define OpenCounter(X)
29186#endif
29187
29188#endif /* !defined(_OS_COMMON_H_) */
29189
29190/************** End of os_common.h *******************************************/
29191/************** Continuing where we left off in os_win.c *********************/
29192
29193/*
29194** Some microsoft compilers lack this definition.
29195*/
29196#ifndef INVALID_FILE_ATTRIBUTES
29197# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
29198#endif
29199
29200/*
29201** Determine if we are dealing with WindowsCE - which has a much
29202** reduced API.
29203*/
29204#if SQLITE_OS_WINCE
29205# define AreFileApisANSI() 1
29206# define FormatMessageW(a,b,c,d,e,f,g) 0
29207#endif
29208
29209/* Forward references */
29210typedef struct winShm winShm;           /* A connection to shared-memory */
29211typedef struct winShmNode winShmNode;   /* A region of shared-memory */
29212
29213/*
29214** WinCE lacks native support for file locking so we have to fake it
29215** with some code of our own.
29216*/
29217#if SQLITE_OS_WINCE
29218typedef struct winceLock {
29219  int nReaders;       /* Number of reader locks obtained */
29220  BOOL bPending;      /* Indicates a pending lock has been obtained */
29221  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
29222  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
29223} winceLock;
29224#endif
29225
29226/*
29227** The winFile structure is a subclass of sqlite3_file* specific to the win32
29228** portability layer.
29229*/
29230typedef struct winFile winFile;
29231struct winFile {
29232  const sqlite3_io_methods *pMethod; /*** Must be first ***/
29233  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29234  HANDLE h;               /* Handle for accessing the file */
29235  unsigned char locktype; /* Type of lock currently held on this file */
29236  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29237  DWORD lastErrno;        /* The Windows errno from the last I/O error */
29238  DWORD sectorSize;       /* Sector size of the device file is on */
29239  winShm *pShm;           /* Instance of shared memory on this file */
29240  const char *zPath;      /* Full pathname of this file */
29241  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
29242#if SQLITE_OS_WINCE
29243  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29244  HANDLE hMutex;          /* Mutex used to control access to shared lock */
29245  HANDLE hShared;         /* Shared memory segment used for locking */
29246  winceLock local;        /* Locks obtained by this instance of winFile */
29247  winceLock *shared;      /* Global shared lock memory for the file  */
29248#endif
29249};
29250
29251/*
29252** Forward prototypes.
29253*/
29254static int getSectorSize(
29255    sqlite3_vfs *pVfs,
29256    const char *zRelative     /* UTF-8 file name */
29257);
29258
29259/*
29260** The following variable is (normally) set once and never changes
29261** thereafter.  It records whether the operating system is Win95
29262** or WinNT.
29263**
29264** 0:   Operating system unknown.
29265** 1:   Operating system is Win95.
29266** 2:   Operating system is WinNT.
29267**
29268** In order to facilitate testing on a WinNT system, the test fixture
29269** can manually set this value to 1 to emulate Win98 behavior.
29270*/
29271#ifdef SQLITE_TEST
29272SQLITE_API int sqlite3_os_type = 0;
29273#else
29274static int sqlite3_os_type = 0;
29275#endif
29276
29277/*
29278** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
29279** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
29280**
29281** Here is an interesting observation:  Win95, Win98, and WinME lack
29282** the LockFileEx() API.  But we can still statically link against that
29283** API as long as we don't call it when running Win95/98/ME.  A call to
29284** this routine is used to determine if the host is Win95/98/ME or
29285** WinNT/2K/XP so that we will know whether or not we can safely call
29286** the LockFileEx() API.
29287*/
29288#if SQLITE_OS_WINCE
29289# define isNT()  (1)
29290#else
29291  static int isNT(void){
29292    if( sqlite3_os_type==0 ){
29293      OSVERSIONINFO sInfo;
29294      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
29295      GetVersionEx(&sInfo);
29296      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
29297    }
29298    return sqlite3_os_type==2;
29299  }
29300#endif /* SQLITE_OS_WINCE */
29301
29302/*
29303** Convert a UTF-8 string to microsoft unicode (UTF-16?).
29304**
29305** Space to hold the returned string is obtained from malloc.
29306*/
29307static WCHAR *utf8ToUnicode(const char *zFilename){
29308  int nChar;
29309  WCHAR *zWideFilename;
29310
29311  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
29312  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
29313  if( zWideFilename==0 ){
29314    return 0;
29315  }
29316  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
29317  if( nChar==0 ){
29318    free(zWideFilename);
29319    zWideFilename = 0;
29320  }
29321  return zWideFilename;
29322}
29323
29324/*
29325** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
29326** obtained from malloc().
29327*/
29328static char *unicodeToUtf8(const WCHAR *zWideFilename){
29329  int nByte;
29330  char *zFilename;
29331
29332  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
29333  zFilename = malloc( nByte );
29334  if( zFilename==0 ){
29335    return 0;
29336  }
29337  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
29338                              0, 0);
29339  if( nByte == 0 ){
29340    free(zFilename);
29341    zFilename = 0;
29342  }
29343  return zFilename;
29344}
29345
29346/*
29347** Convert an ansi string to microsoft unicode, based on the
29348** current codepage settings for file apis.
29349**
29350** Space to hold the returned string is obtained
29351** from malloc.
29352*/
29353static WCHAR *mbcsToUnicode(const char *zFilename){
29354  int nByte;
29355  WCHAR *zMbcsFilename;
29356  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29357
29358  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
29359  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
29360  if( zMbcsFilename==0 ){
29361    return 0;
29362  }
29363  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29364  if( nByte==0 ){
29365    free(zMbcsFilename);
29366    zMbcsFilename = 0;
29367  }
29368  return zMbcsFilename;
29369}
29370
29371/*
29372** Convert microsoft unicode to multibyte character string, based on the
29373** user's Ansi codepage.
29374**
29375** Space to hold the returned string is obtained from
29376** malloc().
29377*/
29378static char *unicodeToMbcs(const WCHAR *zWideFilename){
29379  int nByte;
29380  char *zFilename;
29381  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29382
29383  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29384  zFilename = malloc( nByte );
29385  if( zFilename==0 ){
29386    return 0;
29387  }
29388  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29389                              0, 0);
29390  if( nByte == 0 ){
29391    free(zFilename);
29392    zFilename = 0;
29393  }
29394  return zFilename;
29395}
29396
29397/*
29398** Convert multibyte character string to UTF-8.  Space to hold the
29399** returned string is obtained from malloc().
29400*/
29401SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29402  char *zFilenameUtf8;
29403  WCHAR *zTmpWide;
29404
29405  zTmpWide = mbcsToUnicode(zFilename);
29406  if( zTmpWide==0 ){
29407    return 0;
29408  }
29409  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29410  free(zTmpWide);
29411  return zFilenameUtf8;
29412}
29413
29414/*
29415** Convert UTF-8 to multibyte character string.  Space to hold the
29416** returned string is obtained from malloc().
29417*/
29418static char *utf8ToMbcs(const char *zFilename){
29419  char *zFilenameMbcs;
29420  WCHAR *zTmpWide;
29421
29422  zTmpWide = utf8ToUnicode(zFilename);
29423  if( zTmpWide==0 ){
29424    return 0;
29425  }
29426  zFilenameMbcs = unicodeToMbcs(zTmpWide);
29427  free(zTmpWide);
29428  return zFilenameMbcs;
29429}
29430
29431#if SQLITE_OS_WINCE
29432/*************************************************************************
29433** This section contains code for WinCE only.
29434*/
29435/*
29436** WindowsCE does not have a localtime() function.  So create a
29437** substitute.
29438*/
29439struct tm *__cdecl localtime(const time_t *t)
29440{
29441  static struct tm y;
29442  FILETIME uTm, lTm;
29443  SYSTEMTIME pTm;
29444  sqlite3_int64 t64;
29445  t64 = *t;
29446  t64 = (t64 + 11644473600)*10000000;
29447  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29448  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29449  FileTimeToLocalFileTime(&uTm,&lTm);
29450  FileTimeToSystemTime(&lTm,&pTm);
29451  y.tm_year = pTm.wYear - 1900;
29452  y.tm_mon = pTm.wMonth - 1;
29453  y.tm_wday = pTm.wDayOfWeek;
29454  y.tm_mday = pTm.wDay;
29455  y.tm_hour = pTm.wHour;
29456  y.tm_min = pTm.wMinute;
29457  y.tm_sec = pTm.wSecond;
29458  return &y;
29459}
29460
29461/* This will never be called, but defined to make the code compile */
29462#define GetTempPathA(a,b)
29463
29464#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29465#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29466#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29467
29468#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29469
29470/*
29471** Acquire a lock on the handle h
29472*/
29473static void winceMutexAcquire(HANDLE h){
29474   DWORD dwErr;
29475   do {
29476     dwErr = WaitForSingleObject(h, INFINITE);
29477   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29478}
29479/*
29480** Release a lock acquired by winceMutexAcquire()
29481*/
29482#define winceMutexRelease(h) ReleaseMutex(h)
29483
29484/*
29485** Create the mutex and shared memory used for locking in the file
29486** descriptor pFile
29487*/
29488static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29489  WCHAR *zTok;
29490  WCHAR *zName = utf8ToUnicode(zFilename);
29491  BOOL bInit = TRUE;
29492
29493  /* Initialize the local lockdata */
29494  ZeroMemory(&pFile->local, sizeof(pFile->local));
29495
29496  /* Replace the backslashes from the filename and lowercase it
29497  ** to derive a mutex name. */
29498  zTok = CharLowerW(zName);
29499  for (;*zTok;zTok++){
29500    if (*zTok == '\\') *zTok = '_';
29501  }
29502
29503  /* Create/open the named mutex */
29504  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29505  if (!pFile->hMutex){
29506    pFile->lastErrno = GetLastError();
29507    free(zName);
29508    return FALSE;
29509  }
29510
29511  /* Acquire the mutex before continuing */
29512  winceMutexAcquire(pFile->hMutex);
29513
29514  /* Since the names of named mutexes, semaphores, file mappings etc are
29515  ** case-sensitive, take advantage of that by uppercasing the mutex name
29516  ** and using that as the shared filemapping name.
29517  */
29518  CharUpperW(zName);
29519  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
29520                                       PAGE_READWRITE, 0, sizeof(winceLock),
29521                                       zName);
29522
29523  /* Set a flag that indicates we're the first to create the memory so it
29524  ** must be zero-initialized */
29525  if (GetLastError() == ERROR_ALREADY_EXISTS){
29526    bInit = FALSE;
29527  }
29528
29529  free(zName);
29530
29531  /* If we succeeded in making the shared memory handle, map it. */
29532  if (pFile->hShared){
29533    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
29534             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
29535    /* If mapping failed, close the shared memory handle and erase it */
29536    if (!pFile->shared){
29537      pFile->lastErrno = GetLastError();
29538      CloseHandle(pFile->hShared);
29539      pFile->hShared = NULL;
29540    }
29541  }
29542
29543  /* If shared memory could not be created, then close the mutex and fail */
29544  if (pFile->hShared == NULL){
29545    winceMutexRelease(pFile->hMutex);
29546    CloseHandle(pFile->hMutex);
29547    pFile->hMutex = NULL;
29548    return FALSE;
29549  }
29550
29551  /* Initialize the shared memory if we're supposed to */
29552  if (bInit) {
29553    ZeroMemory(pFile->shared, sizeof(winceLock));
29554  }
29555
29556  winceMutexRelease(pFile->hMutex);
29557  return TRUE;
29558}
29559
29560/*
29561** Destroy the part of winFile that deals with wince locks
29562*/
29563static void winceDestroyLock(winFile *pFile){
29564  if (pFile->hMutex){
29565    /* Acquire the mutex */
29566    winceMutexAcquire(pFile->hMutex);
29567
29568    /* The following blocks should probably assert in debug mode, but they
29569       are to cleanup in case any locks remained open */
29570    if (pFile->local.nReaders){
29571      pFile->shared->nReaders --;
29572    }
29573    if (pFile->local.bReserved){
29574      pFile->shared->bReserved = FALSE;
29575    }
29576    if (pFile->local.bPending){
29577      pFile->shared->bPending = FALSE;
29578    }
29579    if (pFile->local.bExclusive){
29580      pFile->shared->bExclusive = FALSE;
29581    }
29582
29583    /* De-reference and close our copy of the shared memory handle */
29584    UnmapViewOfFile(pFile->shared);
29585    CloseHandle(pFile->hShared);
29586
29587    /* Done with the mutex */
29588    winceMutexRelease(pFile->hMutex);
29589    CloseHandle(pFile->hMutex);
29590    pFile->hMutex = NULL;
29591  }
29592}
29593
29594/*
29595** An implementation of the LockFile() API of windows for wince
29596*/
29597static BOOL winceLockFile(
29598  HANDLE *phFile,
29599  DWORD dwFileOffsetLow,
29600  DWORD dwFileOffsetHigh,
29601  DWORD nNumberOfBytesToLockLow,
29602  DWORD nNumberOfBytesToLockHigh
29603){
29604  winFile *pFile = HANDLE_TO_WINFILE(phFile);
29605  BOOL bReturn = FALSE;
29606
29607  UNUSED_PARAMETER(dwFileOffsetHigh);
29608  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29609
29610  if (!pFile->hMutex) return TRUE;
29611  winceMutexAcquire(pFile->hMutex);
29612
29613  /* Wanting an exclusive lock? */
29614  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
29615       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29616    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
29617       pFile->shared->bExclusive = TRUE;
29618       pFile->local.bExclusive = TRUE;
29619       bReturn = TRUE;
29620    }
29621  }
29622
29623  /* Want a read-only lock? */
29624  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
29625           nNumberOfBytesToLockLow == 1){
29626    if (pFile->shared->bExclusive == 0){
29627      pFile->local.nReaders ++;
29628      if (pFile->local.nReaders == 1){
29629        pFile->shared->nReaders ++;
29630      }
29631      bReturn = TRUE;
29632    }
29633  }
29634
29635  /* Want a pending lock? */
29636  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
29637    /* If no pending lock has been acquired, then acquire it */
29638    if (pFile->shared->bPending == 0) {
29639      pFile->shared->bPending = TRUE;
29640      pFile->local.bPending = TRUE;
29641      bReturn = TRUE;
29642    }
29643  }
29644
29645  /* Want a reserved lock? */
29646  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
29647    if (pFile->shared->bReserved == 0) {
29648      pFile->shared->bReserved = TRUE;
29649      pFile->local.bReserved = TRUE;
29650      bReturn = TRUE;
29651    }
29652  }
29653
29654  winceMutexRelease(pFile->hMutex);
29655  return bReturn;
29656}
29657
29658/*
29659** An implementation of the UnlockFile API of windows for wince
29660*/
29661static BOOL winceUnlockFile(
29662  HANDLE *phFile,
29663  DWORD dwFileOffsetLow,
29664  DWORD dwFileOffsetHigh,
29665  DWORD nNumberOfBytesToUnlockLow,
29666  DWORD nNumberOfBytesToUnlockHigh
29667){
29668  winFile *pFile = HANDLE_TO_WINFILE(phFile);
29669  BOOL bReturn = FALSE;
29670
29671  UNUSED_PARAMETER(dwFileOffsetHigh);
29672  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
29673
29674  if (!pFile->hMutex) return TRUE;
29675  winceMutexAcquire(pFile->hMutex);
29676
29677  /* Releasing a reader lock or an exclusive lock */
29678  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
29679    /* Did we have an exclusive lock? */
29680    if (pFile->local.bExclusive){
29681      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
29682      pFile->local.bExclusive = FALSE;
29683      pFile->shared->bExclusive = FALSE;
29684      bReturn = TRUE;
29685    }
29686
29687    /* Did we just have a reader lock? */
29688    else if (pFile->local.nReaders){
29689      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
29690      pFile->local.nReaders --;
29691      if (pFile->local.nReaders == 0)
29692      {
29693        pFile->shared->nReaders --;
29694      }
29695      bReturn = TRUE;
29696    }
29697  }
29698
29699  /* Releasing a pending lock */
29700  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
29701    if (pFile->local.bPending){
29702      pFile->local.bPending = FALSE;
29703      pFile->shared->bPending = FALSE;
29704      bReturn = TRUE;
29705    }
29706  }
29707  /* Releasing a reserved lock */
29708  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
29709    if (pFile->local.bReserved) {
29710      pFile->local.bReserved = FALSE;
29711      pFile->shared->bReserved = FALSE;
29712      bReturn = TRUE;
29713    }
29714  }
29715
29716  winceMutexRelease(pFile->hMutex);
29717  return bReturn;
29718}
29719
29720/*
29721** An implementation of the LockFileEx() API of windows for wince
29722*/
29723static BOOL winceLockFileEx(
29724  HANDLE *phFile,
29725  DWORD dwFlags,
29726  DWORD dwReserved,
29727  DWORD nNumberOfBytesToLockLow,
29728  DWORD nNumberOfBytesToLockHigh,
29729  LPOVERLAPPED lpOverlapped
29730){
29731  UNUSED_PARAMETER(dwReserved);
29732  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
29733
29734  /* If the caller wants a shared read lock, forward this call
29735  ** to winceLockFile */
29736  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
29737      dwFlags == 1 &&
29738      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
29739    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
29740  }
29741  return FALSE;
29742}
29743/*
29744** End of the special code for wince
29745*****************************************************************************/
29746#endif /* SQLITE_OS_WINCE */
29747
29748/*****************************************************************************
29749** The next group of routines implement the I/O methods specified
29750** by the sqlite3_io_methods object.
29751******************************************************************************/
29752
29753/*
29754** Some microsoft compilers lack this definition.
29755*/
29756#ifndef INVALID_SET_FILE_POINTER
29757# define INVALID_SET_FILE_POINTER ((DWORD)-1)
29758#endif
29759
29760/*
29761** Move the current position of the file handle passed as the first
29762** argument to offset iOffset within the file. If successful, return 0.
29763** Otherwise, set pFile->lastErrno and return non-zero.
29764*/
29765static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
29766  LONG upperBits;                 /* Most sig. 32 bits of new offset */
29767  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
29768  DWORD dwRet;                    /* Value returned by SetFilePointer() */
29769
29770  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
29771  lowerBits = (LONG)(iOffset & 0xffffffff);
29772
29773  /* API oddity: If successful, SetFilePointer() returns a dword
29774  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
29775  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
29776  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
29777  ** whether an error has actually occured, it is also necessary to call
29778  ** GetLastError().
29779  */
29780  dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
29781  if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
29782    pFile->lastErrno = GetLastError();
29783    return 1;
29784  }
29785
29786  return 0;
29787}
29788
29789/*
29790** Close a file.
29791**
29792** It is reported that an attempt to close a handle might sometimes
29793** fail.  This is a very unreasonable result, but windows is notorious
29794** for being unreasonable so I do not doubt that it might happen.  If
29795** the close fails, we pause for 100 milliseconds and try again.  As
29796** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
29797** giving up and returning an error.
29798*/
29799#define MX_CLOSE_ATTEMPT 3
29800static int winClose(sqlite3_file *id){
29801  int rc, cnt = 0;
29802  winFile *pFile = (winFile*)id;
29803
29804  assert( id!=0 );
29805  assert( pFile->pShm==0 );
29806  OSTRACE(("CLOSE %d\n", pFile->h));
29807  do{
29808    rc = CloseHandle(pFile->h);
29809    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
29810  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
29811#if SQLITE_OS_WINCE
29812#define WINCE_DELETION_ATTEMPTS 3
29813  winceDestroyLock(pFile);
29814  if( pFile->zDeleteOnClose ){
29815    int cnt = 0;
29816    while(
29817           DeleteFileW(pFile->zDeleteOnClose)==0
29818        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
29819        && cnt++ < WINCE_DELETION_ATTEMPTS
29820    ){
29821       Sleep(100);  /* Wait a little before trying again */
29822    }
29823    free(pFile->zDeleteOnClose);
29824  }
29825#endif
29826  OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
29827  OpenCounter(-1);
29828  return rc ? SQLITE_OK : SQLITE_IOERR;
29829}
29830
29831/*
29832** Read data from a file into a buffer.  Return SQLITE_OK if all
29833** bytes were read successfully and SQLITE_IOERR if anything goes
29834** wrong.
29835*/
29836static int winRead(
29837  sqlite3_file *id,          /* File to read from */
29838  void *pBuf,                /* Write content into this buffer */
29839  int amt,                   /* Number of bytes to read */
29840  sqlite3_int64 offset       /* Begin reading at this offset */
29841){
29842  winFile *pFile = (winFile*)id;  /* file handle */
29843  DWORD nRead;                    /* Number of bytes actually read from file */
29844
29845  assert( id!=0 );
29846  SimulateIOError(return SQLITE_IOERR_READ);
29847  OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
29848
29849  if( seekWinFile(pFile, offset) ){
29850    return SQLITE_FULL;
29851  }
29852  if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
29853    pFile->lastErrno = GetLastError();
29854    return SQLITE_IOERR_READ;
29855  }
29856  if( nRead<(DWORD)amt ){
29857    /* Unread parts of the buffer must be zero-filled */
29858    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
29859    return SQLITE_IOERR_SHORT_READ;
29860  }
29861
29862  return SQLITE_OK;
29863}
29864
29865/*
29866** Write data from a buffer into a file.  Return SQLITE_OK on success
29867** or some other error code on failure.
29868*/
29869static int winWrite(
29870  sqlite3_file *id,               /* File to write into */
29871  const void *pBuf,               /* The bytes to be written */
29872  int amt,                        /* Number of bytes to write */
29873  sqlite3_int64 offset            /* Offset into the file to begin writing at */
29874){
29875  int rc;                         /* True if error has occured, else false */
29876  winFile *pFile = (winFile*)id;  /* File handle */
29877
29878  assert( amt>0 );
29879  assert( pFile );
29880  SimulateIOError(return SQLITE_IOERR_WRITE);
29881  SimulateDiskfullError(return SQLITE_FULL);
29882
29883  OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
29884
29885  rc = seekWinFile(pFile, offset);
29886  if( rc==0 ){
29887    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
29888    int nRem = amt;               /* Number of bytes yet to be written */
29889    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
29890
29891    while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
29892      aRem += nWrite;
29893      nRem -= nWrite;
29894    }
29895    if( nRem>0 ){
29896      pFile->lastErrno = GetLastError();
29897      rc = 1;
29898    }
29899  }
29900
29901  if( rc ){
29902    if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
29903      return SQLITE_FULL;
29904    }
29905    return SQLITE_IOERR_WRITE;
29906  }
29907  return SQLITE_OK;
29908}
29909
29910/*
29911** Truncate an open file to a specified size
29912*/
29913static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
29914  winFile *pFile = (winFile*)id;  /* File handle object */
29915  int rc = SQLITE_OK;             /* Return code for this function */
29916
29917  assert( pFile );
29918
29919  OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
29920  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
29921
29922  /* If the user has configured a chunk-size for this file, truncate the
29923  ** file so that it consists of an integer number of chunks (i.e. the
29924  ** actual file size after the operation may be larger than the requested
29925  ** size).
29926  */
29927  if( pFile->szChunk ){
29928    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
29929  }
29930
29931  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
29932  if( seekWinFile(pFile, nByte) ){
29933    rc = SQLITE_IOERR_TRUNCATE;
29934  }else if( 0==SetEndOfFile(pFile->h) ){
29935    pFile->lastErrno = GetLastError();
29936    rc = SQLITE_IOERR_TRUNCATE;
29937  }
29938
29939  OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
29940  return rc;
29941}
29942
29943#ifdef SQLITE_TEST
29944/*
29945** Count the number of fullsyncs and normal syncs.  This is used to test
29946** that syncs and fullsyncs are occuring at the right times.
29947*/
29948SQLITE_API int sqlite3_sync_count = 0;
29949SQLITE_API int sqlite3_fullsync_count = 0;
29950#endif
29951
29952/*
29953** Make sure all writes to a particular file are committed to disk.
29954*/
29955static int winSync(sqlite3_file *id, int flags){
29956#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
29957  winFile *pFile = (winFile*)id;
29958#else
29959  UNUSED_PARAMETER(id);
29960#endif
29961
29962  assert( pFile );
29963  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
29964  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
29965      || (flags&0x0F)==SQLITE_SYNC_FULL
29966  );
29967
29968  OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
29969
29970#ifndef SQLITE_TEST
29971  UNUSED_PARAMETER(flags);
29972#else
29973  if( flags & SQLITE_SYNC_FULL ){
29974    sqlite3_fullsync_count++;
29975  }
29976  sqlite3_sync_count++;
29977#endif
29978
29979  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
29980  ** line is to test that doing so does not cause any problems.
29981  */
29982  SimulateDiskfullError( return SQLITE_FULL );
29983  SimulateIOError( return SQLITE_IOERR; );
29984
29985  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
29986  ** no-op
29987  */
29988#ifdef SQLITE_NO_SYNC
29989  return SQLITE_OK;
29990#else
29991  if( FlushFileBuffers(pFile->h) ){
29992    return SQLITE_OK;
29993  }else{
29994    pFile->lastErrno = GetLastError();
29995    return SQLITE_IOERR;
29996  }
29997#endif
29998}
29999
30000/*
30001** Determine the current size of a file in bytes
30002*/
30003static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
30004  DWORD upperBits;
30005  DWORD lowerBits;
30006  winFile *pFile = (winFile*)id;
30007  DWORD error;
30008
30009  assert( id!=0 );
30010  SimulateIOError(return SQLITE_IOERR_FSTAT);
30011  lowerBits = GetFileSize(pFile->h, &upperBits);
30012  if(   (lowerBits == INVALID_FILE_SIZE)
30013     && ((error = GetLastError()) != NO_ERROR) )
30014  {
30015    pFile->lastErrno = error;
30016    return SQLITE_IOERR_FSTAT;
30017  }
30018  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
30019  return SQLITE_OK;
30020}
30021
30022/*
30023** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
30024*/
30025#ifndef LOCKFILE_FAIL_IMMEDIATELY
30026# define LOCKFILE_FAIL_IMMEDIATELY 1
30027#endif
30028
30029/*
30030** Acquire a reader lock.
30031** Different API routines are called depending on whether or not this
30032** is Win95 or WinNT.
30033*/
30034static int getReadLock(winFile *pFile){
30035  int res;
30036  if( isNT() ){
30037    OVERLAPPED ovlp;
30038    ovlp.Offset = SHARED_FIRST;
30039    ovlp.OffsetHigh = 0;
30040    ovlp.hEvent = 0;
30041    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
30042                     0, SHARED_SIZE, 0, &ovlp);
30043/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30044*/
30045#if SQLITE_OS_WINCE==0
30046  }else{
30047    int lk;
30048    sqlite3_randomness(sizeof(lk), &lk);
30049    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
30050    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
30051#endif
30052  }
30053  if( res == 0 ){
30054    pFile->lastErrno = GetLastError();
30055  }
30056  return res;
30057}
30058
30059/*
30060** Undo a readlock
30061*/
30062static int unlockReadLock(winFile *pFile){
30063  int res;
30064  if( isNT() ){
30065    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30066/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30067*/
30068#if SQLITE_OS_WINCE==0
30069  }else{
30070    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
30071#endif
30072  }
30073  if( res == 0 ){
30074    pFile->lastErrno = GetLastError();
30075  }
30076  return res;
30077}
30078
30079/*
30080** Lock the file with the lock specified by parameter locktype - one
30081** of the following:
30082**
30083**     (1) SHARED_LOCK
30084**     (2) RESERVED_LOCK
30085**     (3) PENDING_LOCK
30086**     (4) EXCLUSIVE_LOCK
30087**
30088** Sometimes when requesting one lock state, additional lock states
30089** are inserted in between.  The locking might fail on one of the later
30090** transitions leaving the lock state different from what it started but
30091** still short of its goal.  The following chart shows the allowed
30092** transitions and the inserted intermediate states:
30093**
30094**    UNLOCKED -> SHARED
30095**    SHARED -> RESERVED
30096**    SHARED -> (PENDING) -> EXCLUSIVE
30097**    RESERVED -> (PENDING) -> EXCLUSIVE
30098**    PENDING -> EXCLUSIVE
30099**
30100** This routine will only increase a lock.  The winUnlock() routine
30101** erases all locks at once and returns us immediately to locking level 0.
30102** It is not possible to lower the locking level one step at a time.  You
30103** must go straight to locking level 0.
30104*/
30105static int winLock(sqlite3_file *id, int locktype){
30106  int rc = SQLITE_OK;    /* Return code from subroutines */
30107  int res = 1;           /* Result of a windows lock call */
30108  int newLocktype;       /* Set pFile->locktype to this value before exiting */
30109  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
30110  winFile *pFile = (winFile*)id;
30111  DWORD error = NO_ERROR;
30112
30113  assert( id!=0 );
30114  OSTRACE(("LOCK %d %d was %d(%d)\n",
30115           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
30116
30117  /* If there is already a lock of this type or more restrictive on the
30118  ** OsFile, do nothing. Don't use the end_lock: exit path, as
30119  ** sqlite3OsEnterMutex() hasn't been called yet.
30120  */
30121  if( pFile->locktype>=locktype ){
30122    return SQLITE_OK;
30123  }
30124
30125  /* Make sure the locking sequence is correct
30126  */
30127  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
30128  assert( locktype!=PENDING_LOCK );
30129  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
30130
30131  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
30132  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
30133  ** the PENDING_LOCK byte is temporary.
30134  */
30135  newLocktype = pFile->locktype;
30136  if(   (pFile->locktype==NO_LOCK)
30137     || (   (locktype==EXCLUSIVE_LOCK)
30138         && (pFile->locktype==RESERVED_LOCK))
30139  ){
30140    int cnt = 3;
30141    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
30142      /* Try 3 times to get the pending lock.  The pending lock might be
30143      ** held by another reader process who will release it momentarily.
30144      */
30145      OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
30146      Sleep(1);
30147    }
30148    gotPendingLock = res;
30149    if( !res ){
30150      error = GetLastError();
30151    }
30152  }
30153
30154  /* Acquire a shared lock
30155  */
30156  if( locktype==SHARED_LOCK && res ){
30157    assert( pFile->locktype==NO_LOCK );
30158    res = getReadLock(pFile);
30159    if( res ){
30160      newLocktype = SHARED_LOCK;
30161    }else{
30162      error = GetLastError();
30163    }
30164  }
30165
30166  /* Acquire a RESERVED lock
30167  */
30168  if( locktype==RESERVED_LOCK && res ){
30169    assert( pFile->locktype==SHARED_LOCK );
30170    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30171    if( res ){
30172      newLocktype = RESERVED_LOCK;
30173    }else{
30174      error = GetLastError();
30175    }
30176  }
30177
30178  /* Acquire a PENDING lock
30179  */
30180  if( locktype==EXCLUSIVE_LOCK && res ){
30181    newLocktype = PENDING_LOCK;
30182    gotPendingLock = 0;
30183  }
30184
30185  /* Acquire an EXCLUSIVE lock
30186  */
30187  if( locktype==EXCLUSIVE_LOCK && res ){
30188    assert( pFile->locktype>=SHARED_LOCK );
30189    res = unlockReadLock(pFile);
30190    OSTRACE(("unreadlock = %d\n", res));
30191    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30192    if( res ){
30193      newLocktype = EXCLUSIVE_LOCK;
30194    }else{
30195      error = GetLastError();
30196      OSTRACE(("error-code = %d\n", error));
30197      getReadLock(pFile);
30198    }
30199  }
30200
30201  /* If we are holding a PENDING lock that ought to be released, then
30202  ** release it now.
30203  */
30204  if( gotPendingLock && locktype==SHARED_LOCK ){
30205    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30206  }
30207
30208  /* Update the state of the lock has held in the file descriptor then
30209  ** return the appropriate result code.
30210  */
30211  if( res ){
30212    rc = SQLITE_OK;
30213  }else{
30214    OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
30215           locktype, newLocktype));
30216    pFile->lastErrno = error;
30217    rc = SQLITE_BUSY;
30218  }
30219  pFile->locktype = (u8)newLocktype;
30220  return rc;
30221}
30222
30223/*
30224** This routine checks if there is a RESERVED lock held on the specified
30225** file by this or any other process. If such a lock is held, return
30226** non-zero, otherwise zero.
30227*/
30228static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
30229  int rc;
30230  winFile *pFile = (winFile*)id;
30231
30232  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30233
30234  assert( id!=0 );
30235  if( pFile->locktype>=RESERVED_LOCK ){
30236    rc = 1;
30237    OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
30238  }else{
30239    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30240    if( rc ){
30241      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30242    }
30243    rc = !rc;
30244    OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
30245  }
30246  *pResOut = rc;
30247  return SQLITE_OK;
30248}
30249
30250/*
30251** Lower the locking level on file descriptor id to locktype.  locktype
30252** must be either NO_LOCK or SHARED_LOCK.
30253**
30254** If the locking level of the file descriptor is already at or below
30255** the requested locking level, this routine is a no-op.
30256**
30257** It is not possible for this routine to fail if the second argument
30258** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
30259** might return SQLITE_IOERR;
30260*/
30261static int winUnlock(sqlite3_file *id, int locktype){
30262  int type;
30263  winFile *pFile = (winFile*)id;
30264  int rc = SQLITE_OK;
30265  assert( pFile!=0 );
30266  assert( locktype<=SHARED_LOCK );
30267  OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30268          pFile->locktype, pFile->sharedLockByte));
30269  type = pFile->locktype;
30270  if( type>=EXCLUSIVE_LOCK ){
30271    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30272    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
30273      /* This should never happen.  We should always be able to
30274      ** reacquire the read lock */
30275      rc = SQLITE_IOERR_UNLOCK;
30276    }
30277  }
30278  if( type>=RESERVED_LOCK ){
30279    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30280  }
30281  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
30282    unlockReadLock(pFile);
30283  }
30284  if( type>=PENDING_LOCK ){
30285    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30286  }
30287  pFile->locktype = (u8)locktype;
30288  return rc;
30289}
30290
30291/*
30292** Control and query of the open file handle.
30293*/
30294static int winFileControl(sqlite3_file *id, int op, void *pArg){
30295  switch( op ){
30296    case SQLITE_FCNTL_LOCKSTATE: {
30297      *(int*)pArg = ((winFile*)id)->locktype;
30298      return SQLITE_OK;
30299    }
30300    case SQLITE_LAST_ERRNO: {
30301      *(int*)pArg = (int)((winFile*)id)->lastErrno;
30302      return SQLITE_OK;
30303    }
30304    case SQLITE_FCNTL_CHUNK_SIZE: {
30305      ((winFile*)id)->szChunk = *(int *)pArg;
30306      return SQLITE_OK;
30307    }
30308    case SQLITE_FCNTL_SIZE_HINT: {
30309      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30310      SimulateIOErrorBenign(1);
30311      winTruncate(id, sz);
30312      SimulateIOErrorBenign(0);
30313      return SQLITE_OK;
30314    }
30315  }
30316  return SQLITE_ERROR;
30317}
30318
30319/*
30320** Return the sector size in bytes of the underlying block device for
30321** the specified file. This is almost always 512 bytes, but may be
30322** larger for some devices.
30323**
30324** SQLite code assumes this function cannot fail. It also assumes that
30325** if two files are created in the same file-system directory (i.e.
30326** a database and its journal file) that the sector size will be the
30327** same for both.
30328*/
30329static int winSectorSize(sqlite3_file *id){
30330  assert( id!=0 );
30331  return (int)(((winFile*)id)->sectorSize);
30332}
30333
30334/*
30335** Return a vector of device characteristics.
30336*/
30337static int winDeviceCharacteristics(sqlite3_file *id){
30338  UNUSED_PARAMETER(id);
30339  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30340}
30341
30342#ifndef SQLITE_OMIT_WAL
30343
30344/*
30345** Helper functions to obtain and relinquish the global mutex. The
30346** global mutex is used to protect the winLockInfo objects used by
30347** this file, all of which may be shared by multiple threads.
30348**
30349** Function winShmMutexHeld() is used to assert() that the global mutex
30350** is held when required. This function is only used as part of assert()
30351** statements. e.g.
30352**
30353**   winShmEnterMutex()
30354**     assert( winShmMutexHeld() );
30355**   winShmLeaveMutex()
30356*/
30357static void winShmEnterMutex(void){
30358  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30359}
30360static void winShmLeaveMutex(void){
30361  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30362}
30363#ifdef SQLITE_DEBUG
30364static int winShmMutexHeld(void) {
30365  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30366}
30367#endif
30368
30369/*
30370** Object used to represent a single file opened and mmapped to provide
30371** shared memory.  When multiple threads all reference the same
30372** log-summary, each thread has its own winFile object, but they all
30373** point to a single instance of this object.  In other words, each
30374** log-summary is opened only once per process.
30375**
30376** winShmMutexHeld() must be true when creating or destroying
30377** this object or while reading or writing the following fields:
30378**
30379**      nRef
30380**      pNext
30381**
30382** The following fields are read-only after the object is created:
30383**
30384**      fid
30385**      zFilename
30386**
30387** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30388** winShmMutexHeld() is true when reading or writing any other field
30389** in this structure.
30390**
30391*/
30392struct winShmNode {
30393  sqlite3_mutex *mutex;      /* Mutex to access this object */
30394  char *zFilename;           /* Name of the file */
30395  winFile hFile;             /* File handle from winOpen */
30396
30397  int szRegion;              /* Size of shared-memory regions */
30398  int nRegion;               /* Size of array apRegion */
30399  struct ShmRegion {
30400    HANDLE hMap;             /* File handle from CreateFileMapping */
30401    void *pMap;
30402  } *aRegion;
30403  DWORD lastErrno;           /* The Windows errno from the last I/O error */
30404
30405  int nRef;                  /* Number of winShm objects pointing to this */
30406  winShm *pFirst;            /* All winShm objects pointing to this */
30407  winShmNode *pNext;         /* Next in list of all winShmNode objects */
30408#ifdef SQLITE_DEBUG
30409  u8 nextShmId;              /* Next available winShm.id value */
30410#endif
30411};
30412
30413/*
30414** A global array of all winShmNode objects.
30415**
30416** The winShmMutexHeld() must be true while reading or writing this list.
30417*/
30418static winShmNode *winShmNodeList = 0;
30419
30420/*
30421** Structure used internally by this VFS to record the state of an
30422** open shared memory connection.
30423**
30424** The following fields are initialized when this object is created and
30425** are read-only thereafter:
30426**
30427**    winShm.pShmNode
30428**    winShm.id
30429**
30430** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30431** while accessing any read/write fields.
30432*/
30433struct winShm {
30434  winShmNode *pShmNode;      /* The underlying winShmNode object */
30435  winShm *pNext;             /* Next winShm with the same winShmNode */
30436  u8 hasMutex;               /* True if holding the winShmNode mutex */
30437  u16 sharedMask;            /* Mask of shared locks held */
30438  u16 exclMask;              /* Mask of exclusive locks held */
30439#ifdef SQLITE_DEBUG
30440  u8 id;                     /* Id of this connection with its winShmNode */
30441#endif
30442};
30443
30444/*
30445** Constants used for locking
30446*/
30447#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30448#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30449
30450/*
30451** Apply advisory locks for all n bytes beginning at ofst.
30452*/
30453#define _SHM_UNLCK  1
30454#define _SHM_RDLCK  2
30455#define _SHM_WRLCK  3
30456static int winShmSystemLock(
30457  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30458  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30459  int ofst,             /* Offset to first byte to be locked/unlocked */
30460  int nByte             /* Number of bytes to lock or unlock */
30461){
30462  OVERLAPPED ovlp;
30463  DWORD dwFlags;
30464  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30465
30466  /* Access to the winShmNode object is serialized by the caller */
30467  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30468
30469  /* Initialize the locking parameters */
30470  dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30471  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30472
30473  memset(&ovlp, 0, sizeof(OVERLAPPED));
30474  ovlp.Offset = ofst;
30475
30476  /* Release/Acquire the system-level lock */
30477  if( lockType==_SHM_UNLCK ){
30478    rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30479  }else{
30480    rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30481  }
30482
30483  if( rc!= 0 ){
30484    rc = SQLITE_OK;
30485  }else{
30486    pFile->lastErrno =  GetLastError();
30487    rc = SQLITE_BUSY;
30488  }
30489
30490  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
30491           pFile->hFile.h,
30492           rc==SQLITE_OK ? "ok" : "failed",
30493           lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30494           pFile->lastErrno));
30495
30496  return rc;
30497}
30498
30499/* Forward references to VFS methods */
30500static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30501static int winDelete(sqlite3_vfs *,const char*,int);
30502
30503/*
30504** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30505**
30506** This is not a VFS shared-memory method; it is a utility function called
30507** by VFS shared-memory methods.
30508*/
30509static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30510  winShmNode **pp;
30511  winShmNode *p;
30512  assert( winShmMutexHeld() );
30513  pp = &winShmNodeList;
30514  while( (p = *pp)!=0 ){
30515    if( p->nRef==0 ){
30516      int i;
30517      if( p->mutex ) sqlite3_mutex_free(p->mutex);
30518      for(i=0; i<p->nRegion; i++){
30519        UnmapViewOfFile(p->aRegion[i].pMap);
30520        CloseHandle(p->aRegion[i].hMap);
30521      }
30522      if( p->hFile.h != INVALID_HANDLE_VALUE ){
30523        SimulateIOErrorBenign(1);
30524        winClose((sqlite3_file *)&p->hFile);
30525        SimulateIOErrorBenign(0);
30526      }
30527      if( deleteFlag ){
30528        SimulateIOErrorBenign(1);
30529        winDelete(pVfs, p->zFilename, 0);
30530        SimulateIOErrorBenign(0);
30531      }
30532      *pp = p->pNext;
30533      sqlite3_free(p->aRegion);
30534      sqlite3_free(p);
30535    }else{
30536      pp = &p->pNext;
30537    }
30538  }
30539}
30540
30541/*
30542** Open the shared-memory area associated with database file pDbFd.
30543**
30544** When opening a new shared-memory file, if no other instances of that
30545** file are currently open, in this process or in other processes, then
30546** the file must be truncated to zero length or have its header cleared.
30547*/
30548static int winOpenSharedMemory(winFile *pDbFd){
30549  struct winShm *p;                  /* The connection to be opened */
30550  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30551  int rc;                            /* Result code */
30552  struct winShmNode *pNew;           /* Newly allocated winShmNode */
30553  int nName;                         /* Size of zName in bytes */
30554
30555  assert( pDbFd->pShm==0 );    /* Not previously opened */
30556
30557  /* Allocate space for the new sqlite3_shm object.  Also speculatively
30558  ** allocate space for a new winShmNode and filename.
30559  */
30560  p = sqlite3_malloc( sizeof(*p) );
30561  if( p==0 ) return SQLITE_NOMEM;
30562  memset(p, 0, sizeof(*p));
30563  nName = sqlite3Strlen30(pDbFd->zPath);
30564  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30565  if( pNew==0 ){
30566    sqlite3_free(p);
30567    return SQLITE_NOMEM;
30568  }
30569  memset(pNew, 0, sizeof(*pNew));
30570  pNew->zFilename = (char*)&pNew[1];
30571  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30572
30573  /* Look to see if there is an existing winShmNode that can be used.
30574  ** If no matching winShmNode currently exists, create a new one.
30575  */
30576  winShmEnterMutex();
30577  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30578    /* TBD need to come up with better match here.  Perhaps
30579    ** use FILE_ID_BOTH_DIR_INFO Structure.
30580    */
30581    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30582  }
30583  if( pShmNode ){
30584    sqlite3_free(pNew);
30585  }else{
30586    pShmNode = pNew;
30587    pNew = 0;
30588    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
30589    pShmNode->pNext = winShmNodeList;
30590    winShmNodeList = pShmNode;
30591
30592    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30593    if( pShmNode->mutex==0 ){
30594      rc = SQLITE_NOMEM;
30595      goto shm_open_err;
30596    }
30597    rc = winOpen(pDbFd->pVfs,
30598                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
30599                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
30600                 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30601                 0);
30602    if( SQLITE_OK!=rc ){
30603      rc = SQLITE_CANTOPEN_BKPT;
30604      goto shm_open_err;
30605    }
30606
30607    /* Check to see if another process is holding the dead-man switch.
30608    ** If not, truncate the file to zero length.
30609    */
30610    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
30611      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
30612      if( rc!=SQLITE_OK ){
30613        rc = SQLITE_IOERR_SHMOPEN;
30614      }
30615    }
30616    if( rc==SQLITE_OK ){
30617      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30618      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
30619    }
30620    if( rc ) goto shm_open_err;
30621  }
30622
30623  /* Make the new connection a child of the winShmNode */
30624  p->pShmNode = pShmNode;
30625#ifdef SQLITE_DEBUG
30626  p->id = pShmNode->nextShmId++;
30627#endif
30628  pShmNode->nRef++;
30629  pDbFd->pShm = p;
30630  winShmLeaveMutex();
30631
30632  /* The reference count on pShmNode has already been incremented under
30633  ** the cover of the winShmEnterMutex() mutex and the pointer from the
30634  ** new (struct winShm) object to the pShmNode has been set. All that is
30635  ** left to do is to link the new object into the linked list starting
30636  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
30637  ** mutex.
30638  */
30639  sqlite3_mutex_enter(pShmNode->mutex);
30640  p->pNext = pShmNode->pFirst;
30641  pShmNode->pFirst = p;
30642  sqlite3_mutex_leave(pShmNode->mutex);
30643  return SQLITE_OK;
30644
30645  /* Jump here on any error */
30646shm_open_err:
30647  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
30648  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
30649  sqlite3_free(p);
30650  sqlite3_free(pNew);
30651  winShmLeaveMutex();
30652  return rc;
30653}
30654
30655/*
30656** Close a connection to shared-memory.  Delete the underlying
30657** storage if deleteFlag is true.
30658*/
30659static int winShmUnmap(
30660  sqlite3_file *fd,          /* Database holding shared memory */
30661  int deleteFlag             /* Delete after closing if true */
30662){
30663  winFile *pDbFd;       /* Database holding shared-memory */
30664  winShm *p;            /* The connection to be closed */
30665  winShmNode *pShmNode; /* The underlying shared-memory file */
30666  winShm **pp;          /* For looping over sibling connections */
30667
30668  pDbFd = (winFile*)fd;
30669  p = pDbFd->pShm;
30670  if( p==0 ) return SQLITE_OK;
30671  pShmNode = p->pShmNode;
30672
30673  /* Remove connection p from the set of connections associated
30674  ** with pShmNode */
30675  sqlite3_mutex_enter(pShmNode->mutex);
30676  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30677  *pp = p->pNext;
30678
30679  /* Free the connection p */
30680  sqlite3_free(p);
30681  pDbFd->pShm = 0;
30682  sqlite3_mutex_leave(pShmNode->mutex);
30683
30684  /* If pShmNode->nRef has reached 0, then close the underlying
30685  ** shared-memory file, too */
30686  winShmEnterMutex();
30687  assert( pShmNode->nRef>0 );
30688  pShmNode->nRef--;
30689  if( pShmNode->nRef==0 ){
30690    winShmPurge(pDbFd->pVfs, deleteFlag);
30691  }
30692  winShmLeaveMutex();
30693
30694  return SQLITE_OK;
30695}
30696
30697/*
30698** Change the lock state for a shared-memory segment.
30699*/
30700static int winShmLock(
30701  sqlite3_file *fd,          /* Database file holding the shared memory */
30702  int ofst,                  /* First lock to acquire or release */
30703  int n,                     /* Number of locks to acquire or release */
30704  int flags                  /* What to do with the lock */
30705){
30706  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
30707  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
30708  winShm *pX;                           /* For looping over all siblings */
30709  winShmNode *pShmNode = p->pShmNode;
30710  int rc = SQLITE_OK;                   /* Result code */
30711  u16 mask;                             /* Mask of locks to take or release */
30712
30713  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
30714  assert( n>=1 );
30715  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
30716       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
30717       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
30718       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
30719  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
30720
30721  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
30722  assert( n>1 || mask==(1<<ofst) );
30723  sqlite3_mutex_enter(pShmNode->mutex);
30724  if( flags & SQLITE_SHM_UNLOCK ){
30725    u16 allMask = 0; /* Mask of locks held by siblings */
30726
30727    /* See if any siblings hold this same lock */
30728    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30729      if( pX==p ) continue;
30730      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30731      allMask |= pX->sharedMask;
30732    }
30733
30734    /* Unlock the system-level locks */
30735    if( (mask & allMask)==0 ){
30736      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
30737    }else{
30738      rc = SQLITE_OK;
30739    }
30740
30741    /* Undo the local locks */
30742    if( rc==SQLITE_OK ){
30743      p->exclMask &= ~mask;
30744      p->sharedMask &= ~mask;
30745    }
30746  }else if( flags & SQLITE_SHM_SHARED ){
30747    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30748
30749    /* Find out which shared locks are already held by sibling connections.
30750    ** If any sibling already holds an exclusive lock, go ahead and return
30751    ** SQLITE_BUSY.
30752    */
30753    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30754      if( (pX->exclMask & mask)!=0 ){
30755        rc = SQLITE_BUSY;
30756        break;
30757      }
30758      allShared |= pX->sharedMask;
30759    }
30760
30761    /* Get shared locks at the system level, if necessary */
30762    if( rc==SQLITE_OK ){
30763      if( (allShared & mask)==0 ){
30764        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
30765      }else{
30766        rc = SQLITE_OK;
30767      }
30768    }
30769
30770    /* Get the local shared locks */
30771    if( rc==SQLITE_OK ){
30772      p->sharedMask |= mask;
30773    }
30774  }else{
30775    /* Make sure no sibling connections hold locks that will block this
30776    ** lock.  If any do, return SQLITE_BUSY right away.
30777    */
30778    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30779      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30780        rc = SQLITE_BUSY;
30781        break;
30782      }
30783    }
30784
30785    /* Get the exclusive locks at the system level.  Then if successful
30786    ** also mark the local connection as being locked.
30787    */
30788    if( rc==SQLITE_OK ){
30789      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
30790      if( rc==SQLITE_OK ){
30791        assert( (p->sharedMask & mask)==0 );
30792        p->exclMask |= mask;
30793      }
30794    }
30795  }
30796  sqlite3_mutex_leave(pShmNode->mutex);
30797  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
30798           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
30799           rc ? "failed" : "ok"));
30800  return rc;
30801}
30802
30803/*
30804** Implement a memory barrier or memory fence on shared memory.
30805**
30806** All loads and stores begun before the barrier must complete before
30807** any load or store begun after the barrier.
30808*/
30809static void winShmBarrier(
30810  sqlite3_file *fd          /* Database holding the shared memory */
30811){
30812  UNUSED_PARAMETER(fd);
30813  /* MemoryBarrier(); // does not work -- do not know why not */
30814  winShmEnterMutex();
30815  winShmLeaveMutex();
30816}
30817
30818/*
30819** This function is called to obtain a pointer to region iRegion of the
30820** shared-memory associated with the database file fd. Shared-memory regions
30821** are numbered starting from zero. Each shared-memory region is szRegion
30822** bytes in size.
30823**
30824** If an error occurs, an error code is returned and *pp is set to NULL.
30825**
30826** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
30827** region has not been allocated (by any client, including one running in a
30828** separate process), then *pp is set to NULL and SQLITE_OK returned. If
30829** isWrite is non-zero and the requested shared-memory region has not yet
30830** been allocated, it is allocated by this function.
30831**
30832** If the shared-memory region has already been allocated or is allocated by
30833** this call as described above, then it is mapped into this processes
30834** address space (if it is not already), *pp is set to point to the mapped
30835** memory and SQLITE_OK returned.
30836*/
30837static int winShmMap(
30838  sqlite3_file *fd,               /* Handle open on database file */
30839  int iRegion,                    /* Region to retrieve */
30840  int szRegion,                   /* Size of regions */
30841  int isWrite,                    /* True to extend file if necessary */
30842  void volatile **pp              /* OUT: Mapped memory */
30843){
30844  winFile *pDbFd = (winFile*)fd;
30845  winShm *p = pDbFd->pShm;
30846  winShmNode *pShmNode;
30847  int rc = SQLITE_OK;
30848
30849  if( !p ){
30850    rc = winOpenSharedMemory(pDbFd);
30851    if( rc!=SQLITE_OK ) return rc;
30852    p = pDbFd->pShm;
30853  }
30854  pShmNode = p->pShmNode;
30855
30856  sqlite3_mutex_enter(pShmNode->mutex);
30857  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
30858
30859  if( pShmNode->nRegion<=iRegion ){
30860    struct ShmRegion *apNew;           /* New aRegion[] array */
30861    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
30862    sqlite3_int64 sz;                  /* Current size of wal-index file */
30863
30864    pShmNode->szRegion = szRegion;
30865
30866    /* The requested region is not mapped into this processes address space.
30867    ** Check to see if it has been allocated (i.e. if the wal-index file is
30868    ** large enough to contain the requested region).
30869    */
30870    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
30871    if( rc!=SQLITE_OK ){
30872      rc = SQLITE_IOERR_SHMSIZE;
30873      goto shmpage_out;
30874    }
30875
30876    if( sz<nByte ){
30877      /* The requested memory region does not exist. If isWrite is set to
30878      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
30879      **
30880      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
30881      ** the requested memory region.
30882      */
30883      if( !isWrite ) goto shmpage_out;
30884      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
30885      if( rc!=SQLITE_OK ){
30886        rc = SQLITE_IOERR_SHMSIZE;
30887        goto shmpage_out;
30888      }
30889    }
30890
30891    /* Map the requested memory region into this processes address space. */
30892    apNew = (struct ShmRegion *)sqlite3_realloc(
30893        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
30894    );
30895    if( !apNew ){
30896      rc = SQLITE_IOERR_NOMEM;
30897      goto shmpage_out;
30898    }
30899    pShmNode->aRegion = apNew;
30900
30901    while( pShmNode->nRegion<=iRegion ){
30902      HANDLE hMap;                /* file-mapping handle */
30903      void *pMap = 0;             /* Mapped memory region */
30904
30905      hMap = CreateFileMapping(pShmNode->hFile.h,
30906          NULL, PAGE_READWRITE, 0, nByte, NULL
30907      );
30908      if( hMap ){
30909        pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30910            0, 0, nByte
30911        );
30912      }
30913      if( !pMap ){
30914        pShmNode->lastErrno = GetLastError();
30915        rc = SQLITE_IOERR;
30916        if( hMap ) CloseHandle(hMap);
30917        goto shmpage_out;
30918      }
30919
30920      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
30921      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
30922      pShmNode->nRegion++;
30923    }
30924  }
30925
30926shmpage_out:
30927  if( pShmNode->nRegion>iRegion ){
30928    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30929    *pp = (void *)&p[iRegion*szRegion];
30930  }else{
30931    *pp = 0;
30932  }
30933  sqlite3_mutex_leave(pShmNode->mutex);
30934  return rc;
30935}
30936
30937#else
30938# define winShmMap     0
30939# define winShmLock    0
30940# define winShmBarrier 0
30941# define winShmUnmap   0
30942#endif /* #ifndef SQLITE_OMIT_WAL */
30943
30944/*
30945** Here ends the implementation of all sqlite3_file methods.
30946**
30947********************** End sqlite3_file Methods *******************************
30948******************************************************************************/
30949
30950/*
30951** This vector defines all the methods that can operate on an
30952** sqlite3_file for win32.
30953*/
30954static const sqlite3_io_methods winIoMethod = {
30955  2,                              /* iVersion */
30956  winClose,                       /* xClose */
30957  winRead,                        /* xRead */
30958  winWrite,                       /* xWrite */
30959  winTruncate,                    /* xTruncate */
30960  winSync,                        /* xSync */
30961  winFileSize,                    /* xFileSize */
30962  winLock,                        /* xLock */
30963  winUnlock,                      /* xUnlock */
30964  winCheckReservedLock,           /* xCheckReservedLock */
30965  winFileControl,                 /* xFileControl */
30966  winSectorSize,                  /* xSectorSize */
30967  winDeviceCharacteristics,       /* xDeviceCharacteristics */
30968  winShmMap,                      /* xShmMap */
30969  winShmLock,                     /* xShmLock */
30970  winShmBarrier,                  /* xShmBarrier */
30971  winShmUnmap                     /* xShmUnmap */
30972};
30973
30974/****************************************************************************
30975**************************** sqlite3_vfs methods ****************************
30976**
30977** This division contains the implementation of methods on the
30978** sqlite3_vfs object.
30979*/
30980
30981/*
30982** Convert a UTF-8 filename into whatever form the underlying
30983** operating system wants filenames in.  Space to hold the result
30984** is obtained from malloc and must be freed by the calling
30985** function.
30986*/
30987static void *convertUtf8Filename(const char *zFilename){
30988  void *zConverted = 0;
30989  if( isNT() ){
30990    zConverted = utf8ToUnicode(zFilename);
30991/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
30992*/
30993#if SQLITE_OS_WINCE==0
30994  }else{
30995    zConverted = utf8ToMbcs(zFilename);
30996#endif
30997  }
30998  /* caller will handle out of memory */
30999  return zConverted;
31000}
31001
31002/*
31003** Create a temporary file name in zBuf.  zBuf must be big enough to
31004** hold at pVfs->mxPathname characters.
31005*/
31006static int getTempname(int nBuf, char *zBuf){
31007  static char zChars[] =
31008    "abcdefghijklmnopqrstuvwxyz"
31009    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
31010    "0123456789";
31011  size_t i, j;
31012  char zTempPath[MAX_PATH+1];
31013
31014  /* It's odd to simulate an io-error here, but really this is just
31015  ** using the io-error infrastructure to test that SQLite handles this
31016  ** function failing.
31017  */
31018  SimulateIOError( return SQLITE_IOERR );
31019
31020  if( sqlite3_temp_directory ){
31021    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
31022  }else if( isNT() ){
31023    char *zMulti;
31024    WCHAR zWidePath[MAX_PATH];
31025    GetTempPathW(MAX_PATH-30, zWidePath);
31026    zMulti = unicodeToUtf8(zWidePath);
31027    if( zMulti ){
31028      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
31029      free(zMulti);
31030    }else{
31031      return SQLITE_NOMEM;
31032    }
31033/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31034** Since the ASCII version of these Windows API do not exist for WINCE,
31035** it's important to not reference them for WINCE builds.
31036*/
31037#if SQLITE_OS_WINCE==0
31038  }else{
31039    char *zUtf8;
31040    char zMbcsPath[MAX_PATH];
31041    GetTempPathA(MAX_PATH-30, zMbcsPath);
31042    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
31043    if( zUtf8 ){
31044      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
31045      free(zUtf8);
31046    }else{
31047      return SQLITE_NOMEM;
31048    }
31049#endif
31050  }
31051
31052  /* Check that the output buffer is large enough for the temporary file
31053  ** name. If it is not, return SQLITE_ERROR.
31054  */
31055  if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
31056    return SQLITE_ERROR;
31057  }
31058
31059  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
31060  zTempPath[i] = 0;
31061
31062  sqlite3_snprintf(nBuf-17, zBuf,
31063                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
31064  j = sqlite3Strlen30(zBuf);
31065  sqlite3_randomness(15, &zBuf[j]);
31066  for(i=0; i<15; i++, j++){
31067    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31068  }
31069  zBuf[j] = 0;
31070
31071  OSTRACE(("TEMP FILENAME: %s\n", zBuf));
31072  return SQLITE_OK;
31073}
31074
31075/*
31076** The return value of getLastErrorMsg
31077** is zero if the error message fits in the buffer, or non-zero
31078** otherwise (if the message was truncated).
31079*/
31080static int getLastErrorMsg(int nBuf, char *zBuf){
31081  /* FormatMessage returns 0 on failure.  Otherwise it
31082  ** returns the number of TCHARs written to the output
31083  ** buffer, excluding the terminating null char.
31084  */
31085  DWORD error = GetLastError();
31086  DWORD dwLen = 0;
31087  char *zOut = 0;
31088
31089  if( isNT() ){
31090    WCHAR *zTempWide = NULL;
31091    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31092                           NULL,
31093                           error,
31094                           0,
31095                           (LPWSTR) &zTempWide,
31096                           0,
31097                           0);
31098    if( dwLen > 0 ){
31099      /* allocate a buffer and convert to UTF8 */
31100      zOut = unicodeToUtf8(zTempWide);
31101      /* free the system buffer allocated by FormatMessage */
31102      LocalFree(zTempWide);
31103    }
31104/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31105** Since the ASCII version of these Windows API do not exist for WINCE,
31106** it's important to not reference them for WINCE builds.
31107*/
31108#if SQLITE_OS_WINCE==0
31109  }else{
31110    char *zTemp = NULL;
31111    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31112                           NULL,
31113                           error,
31114                           0,
31115                           (LPSTR) &zTemp,
31116                           0,
31117                           0);
31118    if( dwLen > 0 ){
31119      /* allocate a buffer and convert to UTF8 */
31120      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31121      /* free the system buffer allocated by FormatMessage */
31122      LocalFree(zTemp);
31123    }
31124#endif
31125  }
31126  if( 0 == dwLen ){
31127    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
31128  }else{
31129    /* copy a maximum of nBuf chars to output buffer */
31130    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31131    /* free the UTF8 buffer */
31132    free(zOut);
31133  }
31134  return 0;
31135}
31136
31137/*
31138** Open a file.
31139*/
31140static int winOpen(
31141  sqlite3_vfs *pVfs,        /* Not used */
31142  const char *zName,        /* Name of the file (UTF-8) */
31143  sqlite3_file *id,         /* Write the SQLite file handle here */
31144  int flags,                /* Open mode flags */
31145  int *pOutFlags            /* Status return flags */
31146){
31147  HANDLE h;
31148  DWORD dwDesiredAccess;
31149  DWORD dwShareMode;
31150  DWORD dwCreationDisposition;
31151  DWORD dwFlagsAndAttributes = 0;
31152#if SQLITE_OS_WINCE
31153  int isTemp = 0;
31154#endif
31155  winFile *pFile = (winFile*)id;
31156  void *zConverted;                 /* Filename in OS encoding */
31157  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
31158  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
31159
31160  assert( id!=0 );
31161  UNUSED_PARAMETER(pVfs);
31162
31163  pFile->h = INVALID_HANDLE_VALUE;
31164
31165  /* If the second argument to this function is NULL, generate a
31166  ** temporary file name to use
31167  */
31168  if( !zUtf8Name ){
31169    int rc = getTempname(MAX_PATH+1, zTmpname);
31170    if( rc!=SQLITE_OK ){
31171      return rc;
31172    }
31173    zUtf8Name = zTmpname;
31174  }
31175
31176  /* Convert the filename to the system encoding. */
31177  zConverted = convertUtf8Filename(zUtf8Name);
31178  if( zConverted==0 ){
31179    return SQLITE_NOMEM;
31180  }
31181
31182  if( flags & SQLITE_OPEN_READWRITE ){
31183    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
31184  }else{
31185    dwDesiredAccess = GENERIC_READ;
31186  }
31187  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
31188  ** created. SQLite doesn't use it to indicate "exclusive access"
31189  ** as it is usually understood.
31190  */
31191  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
31192  if( flags & SQLITE_OPEN_EXCLUSIVE ){
31193    /* Creates a new file, only if it does not already exist. */
31194    /* If the file exists, it fails. */
31195    dwCreationDisposition = CREATE_NEW;
31196  }else if( flags & SQLITE_OPEN_CREATE ){
31197    /* Open existing file, or create if it doesn't exist */
31198    dwCreationDisposition = OPEN_ALWAYS;
31199  }else{
31200    /* Opens a file, only if it exists. */
31201    dwCreationDisposition = OPEN_EXISTING;
31202  }
31203  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31204  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
31205#if SQLITE_OS_WINCE
31206    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
31207    isTemp = 1;
31208#else
31209    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
31210                               | FILE_ATTRIBUTE_HIDDEN
31211                               | FILE_FLAG_DELETE_ON_CLOSE;
31212#endif
31213  }else{
31214    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
31215  }
31216  /* Reports from the internet are that performance is always
31217  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
31218#if SQLITE_OS_WINCE
31219  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
31220#endif
31221  if( isNT() ){
31222    h = CreateFileW((WCHAR*)zConverted,
31223       dwDesiredAccess,
31224       dwShareMode,
31225       NULL,
31226       dwCreationDisposition,
31227       dwFlagsAndAttributes,
31228       NULL
31229    );
31230/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31231** Since the ASCII version of these Windows API do not exist for WINCE,
31232** it's important to not reference them for WINCE builds.
31233*/
31234#if SQLITE_OS_WINCE==0
31235  }else{
31236    h = CreateFileA((char*)zConverted,
31237       dwDesiredAccess,
31238       dwShareMode,
31239       NULL,
31240       dwCreationDisposition,
31241       dwFlagsAndAttributes,
31242       NULL
31243    );
31244#endif
31245  }
31246  OSTRACE(("OPEN %d %s 0x%lx %s\n",
31247           h, zName, dwDesiredAccess,
31248           h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
31249  if( h==INVALID_HANDLE_VALUE ){
31250    pFile->lastErrno = GetLastError();
31251    free(zConverted);
31252    if( flags & SQLITE_OPEN_READWRITE ){
31253      return winOpen(pVfs, zName, id,
31254             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
31255    }else{
31256      return SQLITE_CANTOPEN_BKPT;
31257    }
31258  }
31259  if( pOutFlags ){
31260    if( flags & SQLITE_OPEN_READWRITE ){
31261      *pOutFlags = SQLITE_OPEN_READWRITE;
31262    }else{
31263      *pOutFlags = SQLITE_OPEN_READONLY;
31264    }
31265  }
31266  memset(pFile, 0, sizeof(*pFile));
31267  pFile->pMethod = &winIoMethod;
31268  pFile->h = h;
31269  pFile->lastErrno = NO_ERROR;
31270  pFile->pVfs = pVfs;
31271  pFile->pShm = 0;
31272  pFile->zPath = zName;
31273  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31274#if SQLITE_OS_WINCE
31275  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
31276               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
31277       && !winceCreateLock(zName, pFile)
31278  ){
31279    CloseHandle(h);
31280    free(zConverted);
31281    return SQLITE_CANTOPEN_BKPT;
31282  }
31283  if( isTemp ){
31284    pFile->zDeleteOnClose = zConverted;
31285  }else
31286#endif
31287  {
31288    free(zConverted);
31289  }
31290  OpenCounter(+1);
31291  return SQLITE_OK;
31292}
31293
31294/*
31295** Delete the named file.
31296**
31297** Note that windows does not allow a file to be deleted if some other
31298** process has it open.  Sometimes a virus scanner or indexing program
31299** will open a journal file shortly after it is created in order to do
31300** whatever it does.  While this other process is holding the
31301** file open, we will be unable to delete it.  To work around this
31302** problem, we delay 100 milliseconds and try to delete again.  Up
31303** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
31304** up and returning an error.
31305*/
31306#define MX_DELETION_ATTEMPTS 5
31307static int winDelete(
31308  sqlite3_vfs *pVfs,          /* Not used on win32 */
31309  const char *zFilename,      /* Name of file to delete */
31310  int syncDir                 /* Not used on win32 */
31311){
31312  int cnt = 0;
31313  DWORD rc;
31314  DWORD error = 0;
31315  void *zConverted;
31316  UNUSED_PARAMETER(pVfs);
31317  UNUSED_PARAMETER(syncDir);
31318
31319  SimulateIOError(return SQLITE_IOERR_DELETE);
31320  zConverted = convertUtf8Filename(zFilename);
31321  if( zConverted==0 ){
31322    return SQLITE_NOMEM;
31323  }
31324  if( isNT() ){
31325    do{
31326      DeleteFileW(zConverted);
31327    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
31328               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31329           && (++cnt < MX_DELETION_ATTEMPTS)
31330           && (Sleep(100), 1) );
31331/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31332** Since the ASCII version of these Windows API do not exist for WINCE,
31333** it's important to not reference them for WINCE builds.
31334*/
31335#if SQLITE_OS_WINCE==0
31336  }else{
31337    do{
31338      DeleteFileA(zConverted);
31339    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
31340               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31341           && (++cnt < MX_DELETION_ATTEMPTS)
31342           && (Sleep(100), 1) );
31343#endif
31344  }
31345  free(zConverted);
31346  OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31347       ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31348         "ok" : "failed" ));
31349
31350  return (   (rc == INVALID_FILE_ATTRIBUTES)
31351          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31352}
31353
31354/*
31355** Check the existance and status of a file.
31356*/
31357static int winAccess(
31358  sqlite3_vfs *pVfs,         /* Not used on win32 */
31359  const char *zFilename,     /* Name of file to check */
31360  int flags,                 /* Type of test to make on this file */
31361  int *pResOut               /* OUT: Result */
31362){
31363  DWORD attr;
31364  int rc = 0;
31365  void *zConverted;
31366  UNUSED_PARAMETER(pVfs);
31367
31368  SimulateIOError( return SQLITE_IOERR_ACCESS; );
31369  zConverted = convertUtf8Filename(zFilename);
31370  if( zConverted==0 ){
31371    return SQLITE_NOMEM;
31372  }
31373  if( isNT() ){
31374    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31375    memset(&sAttrData, 0, sizeof(sAttrData));
31376    if( GetFileAttributesExW((WCHAR*)zConverted,
31377                             GetFileExInfoStandard,
31378                             &sAttrData) ){
31379      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31380      ** as if it does not exist.
31381      */
31382      if(    flags==SQLITE_ACCESS_EXISTS
31383          && sAttrData.nFileSizeHigh==0
31384          && sAttrData.nFileSizeLow==0 ){
31385        attr = INVALID_FILE_ATTRIBUTES;
31386      }else{
31387        attr = sAttrData.dwFileAttributes;
31388      }
31389    }else{
31390      if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31391        free(zConverted);
31392        return SQLITE_IOERR_ACCESS;
31393      }else{
31394        attr = INVALID_FILE_ATTRIBUTES;
31395      }
31396    }
31397/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31398** Since the ASCII version of these Windows API do not exist for WINCE,
31399** it's important to not reference them for WINCE builds.
31400*/
31401#if SQLITE_OS_WINCE==0
31402  }else{
31403    attr = GetFileAttributesA((char*)zConverted);
31404#endif
31405  }
31406  free(zConverted);
31407  switch( flags ){
31408    case SQLITE_ACCESS_READ:
31409    case SQLITE_ACCESS_EXISTS:
31410      rc = attr!=INVALID_FILE_ATTRIBUTES;
31411      break;
31412    case SQLITE_ACCESS_READWRITE:
31413      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
31414      break;
31415    default:
31416      assert(!"Invalid flags argument");
31417  }
31418  *pResOut = rc;
31419  return SQLITE_OK;
31420}
31421
31422
31423/*
31424** Turn a relative pathname into a full pathname.  Write the full
31425** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
31426** bytes in size.
31427*/
31428static int winFullPathname(
31429  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31430  const char *zRelative,        /* Possibly relative input path */
31431  int nFull,                    /* Size of output buffer in bytes */
31432  char *zFull                   /* Output buffer */
31433){
31434
31435#if defined(__CYGWIN__)
31436  SimulateIOError( return SQLITE_ERROR );
31437  UNUSED_PARAMETER(nFull);
31438  cygwin_conv_to_full_win32_path(zRelative, zFull);
31439  return SQLITE_OK;
31440#endif
31441
31442#if SQLITE_OS_WINCE
31443  SimulateIOError( return SQLITE_ERROR );
31444  UNUSED_PARAMETER(nFull);
31445  /* WinCE has no concept of a relative pathname, or so I am told. */
31446  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
31447  return SQLITE_OK;
31448#endif
31449
31450#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
31451  int nByte;
31452  void *zConverted;
31453  char *zOut;
31454
31455  /* It's odd to simulate an io-error here, but really this is just
31456  ** using the io-error infrastructure to test that SQLite handles this
31457  ** function failing. This function could fail if, for example, the
31458  ** current working directory has been unlinked.
31459  */
31460  SimulateIOError( return SQLITE_ERROR );
31461  UNUSED_PARAMETER(nFull);
31462  zConverted = convertUtf8Filename(zRelative);
31463  if( isNT() ){
31464    WCHAR *zTemp;
31465    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
31466    zTemp = malloc( nByte*sizeof(zTemp[0]) );
31467    if( zTemp==0 ){
31468      free(zConverted);
31469      return SQLITE_NOMEM;
31470    }
31471    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
31472    free(zConverted);
31473    zOut = unicodeToUtf8(zTemp);
31474    free(zTemp);
31475/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31476** Since the ASCII version of these Windows API do not exist for WINCE,
31477** it's important to not reference them for WINCE builds.
31478*/
31479#if SQLITE_OS_WINCE==0
31480  }else{
31481    char *zTemp;
31482    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
31483    zTemp = malloc( nByte*sizeof(zTemp[0]) );
31484    if( zTemp==0 ){
31485      free(zConverted);
31486      return SQLITE_NOMEM;
31487    }
31488    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
31489    free(zConverted);
31490    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31491    free(zTemp);
31492#endif
31493  }
31494  if( zOut ){
31495    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
31496    free(zOut);
31497    return SQLITE_OK;
31498  }else{
31499    return SQLITE_NOMEM;
31500  }
31501#endif
31502}
31503
31504/*
31505** Get the sector size of the device used to store
31506** file.
31507*/
31508static int getSectorSize(
31509    sqlite3_vfs *pVfs,
31510    const char *zRelative     /* UTF-8 file name */
31511){
31512  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31513  /* GetDiskFreeSpace is not supported under WINCE */
31514#if SQLITE_OS_WINCE
31515  UNUSED_PARAMETER(pVfs);
31516  UNUSED_PARAMETER(zRelative);
31517#else
31518  char zFullpath[MAX_PATH+1];
31519  int rc;
31520  DWORD dwRet = 0;
31521  DWORD dwDummy;
31522
31523  /*
31524  ** We need to get the full path name of the file
31525  ** to get the drive letter to look up the sector
31526  ** size.
31527  */
31528  SimulateIOErrorBenign(1);
31529  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
31530  SimulateIOErrorBenign(0);
31531  if( rc == SQLITE_OK )
31532  {
31533    void *zConverted = convertUtf8Filename(zFullpath);
31534    if( zConverted ){
31535      if( isNT() ){
31536        /* trim path to just drive reference */
31537        WCHAR *p = zConverted;
31538        for(;*p;p++){
31539          if( *p == '\\' ){
31540            *p = '\0';
31541            break;
31542          }
31543        }
31544        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
31545                                  &dwDummy,
31546                                  &bytesPerSector,
31547                                  &dwDummy,
31548                                  &dwDummy);
31549      }else{
31550        /* trim path to just drive reference */
31551        char *p = (char *)zConverted;
31552        for(;*p;p++){
31553          if( *p == '\\' ){
31554            *p = '\0';
31555            break;
31556          }
31557        }
31558        dwRet = GetDiskFreeSpaceA((char*)zConverted,
31559                                  &dwDummy,
31560                                  &bytesPerSector,
31561                                  &dwDummy,
31562                                  &dwDummy);
31563      }
31564      free(zConverted);
31565    }
31566    if( !dwRet ){
31567      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31568    }
31569  }
31570#endif
31571  return (int) bytesPerSector;
31572}
31573
31574#ifndef SQLITE_OMIT_LOAD_EXTENSION
31575/*
31576** Interfaces for opening a shared library, finding entry points
31577** within the shared library, and closing the shared library.
31578*/
31579/*
31580** Interfaces for opening a shared library, finding entry points
31581** within the shared library, and closing the shared library.
31582*/
31583static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
31584  HANDLE h;
31585  void *zConverted = convertUtf8Filename(zFilename);
31586  UNUSED_PARAMETER(pVfs);
31587  if( zConverted==0 ){
31588    return 0;
31589  }
31590  if( isNT() ){
31591    h = LoadLibraryW((WCHAR*)zConverted);
31592/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
31593** Since the ASCII version of these Windows API do not exist for WINCE,
31594** it's important to not reference them for WINCE builds.
31595*/
31596#if SQLITE_OS_WINCE==0
31597  }else{
31598    h = LoadLibraryA((char*)zConverted);
31599#endif
31600  }
31601  free(zConverted);
31602  return (void*)h;
31603}
31604static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
31605  UNUSED_PARAMETER(pVfs);
31606  getLastErrorMsg(nBuf, zBufOut);
31607}
31608void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
31609  UNUSED_PARAMETER(pVfs);
31610#if SQLITE_OS_WINCE
31611  /* The GetProcAddressA() routine is only available on wince. */
31612  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
31613#else
31614  /* All other windows platforms expect GetProcAddress() to take
31615  ** an Ansi string regardless of the _UNICODE setting */
31616  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
31617#endif
31618}
31619void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
31620  UNUSED_PARAMETER(pVfs);
31621  FreeLibrary((HANDLE)pHandle);
31622}
31623#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31624  #define winDlOpen  0
31625  #define winDlError 0
31626  #define winDlSym   0
31627  #define winDlClose 0
31628#endif
31629
31630
31631/*
31632** Write up to nBuf bytes of randomness into zBuf.
31633*/
31634static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31635  int n = 0;
31636  UNUSED_PARAMETER(pVfs);
31637#if defined(SQLITE_TEST)
31638  n = nBuf;
31639  memset(zBuf, 0, nBuf);
31640#else
31641  if( sizeof(SYSTEMTIME)<=nBuf-n ){
31642    SYSTEMTIME x;
31643    GetSystemTime(&x);
31644    memcpy(&zBuf[n], &x, sizeof(x));
31645    n += sizeof(x);
31646  }
31647  if( sizeof(DWORD)<=nBuf-n ){
31648    DWORD pid = GetCurrentProcessId();
31649    memcpy(&zBuf[n], &pid, sizeof(pid));
31650    n += sizeof(pid);
31651  }
31652  if( sizeof(DWORD)<=nBuf-n ){
31653    DWORD cnt = GetTickCount();
31654    memcpy(&zBuf[n], &cnt, sizeof(cnt));
31655    n += sizeof(cnt);
31656  }
31657  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
31658    LARGE_INTEGER i;
31659    QueryPerformanceCounter(&i);
31660    memcpy(&zBuf[n], &i, sizeof(i));
31661    n += sizeof(i);
31662  }
31663#endif
31664  return n;
31665}
31666
31667
31668/*
31669** Sleep for a little while.  Return the amount of time slept.
31670*/
31671static int winSleep(sqlite3_vfs *pVfs, int microsec){
31672  Sleep((microsec+999)/1000);
31673  UNUSED_PARAMETER(pVfs);
31674  return ((microsec+999)/1000)*1000;
31675}
31676
31677/*
31678** The following variable, if set to a non-zero value, is interpreted as
31679** the number of seconds since 1970 and is used to set the result of
31680** sqlite3OsCurrentTime() during testing.
31681*/
31682#ifdef SQLITE_TEST
31683SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
31684#endif
31685
31686/*
31687** Find the current time (in Universal Coordinated Time).  Write into *piNow
31688** the current time and date as a Julian Day number times 86_400_000.  In
31689** other words, write into *piNow the number of milliseconds since the Julian
31690** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31691** proleptic Gregorian calendar.
31692**
31693** On success, return 0.  Return 1 if the time and date cannot be found.
31694*/
31695static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
31696  /* FILETIME structure is a 64-bit value representing the number of
31697     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
31698  */
31699  FILETIME ft;
31700  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
31701#ifdef SQLITE_TEST
31702  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31703#endif
31704  /* 2^32 - to avoid use of LL and warnings in gcc */
31705  static const sqlite3_int64 max32BitValue =
31706      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
31707
31708#if SQLITE_OS_WINCE
31709  SYSTEMTIME time;
31710  GetSystemTime(&time);
31711  /* if SystemTimeToFileTime() fails, it returns zero. */
31712  if (!SystemTimeToFileTime(&time,&ft)){
31713    return 1;
31714  }
31715#else
31716  GetSystemTimeAsFileTime( &ft );
31717#endif
31718
31719  *piNow = winFiletimeEpoch +
31720            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
31721               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
31722
31723#ifdef SQLITE_TEST
31724  if( sqlite3_current_time ){
31725    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31726  }
31727#endif
31728  UNUSED_PARAMETER(pVfs);
31729  return 0;
31730}
31731
31732/*
31733** Find the current time (in Universal Coordinated Time).  Write the
31734** current time and date as a Julian Day number into *prNow and
31735** return 0.  Return 1 if the time and date cannot be found.
31736*/
31737int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
31738  int rc;
31739  sqlite3_int64 i;
31740  rc = winCurrentTimeInt64(pVfs, &i);
31741  if( !rc ){
31742    *prNow = i/86400000.0;
31743  }
31744  return rc;
31745}
31746
31747/*
31748** The idea is that this function works like a combination of
31749** GetLastError() and FormatMessage() on windows (or errno and
31750** strerror_r() on unix). After an error is returned by an OS
31751** function, SQLite calls this function with zBuf pointing to
31752** a buffer of nBuf bytes. The OS layer should populate the
31753** buffer with a nul-terminated UTF-8 encoded error message
31754** describing the last IO error to have occurred within the calling
31755** thread.
31756**
31757** If the error message is too large for the supplied buffer,
31758** it should be truncated. The return value of xGetLastError
31759** is zero if the error message fits in the buffer, or non-zero
31760** otherwise (if the message was truncated). If non-zero is returned,
31761** then it is not necessary to include the nul-terminator character
31762** in the output buffer.
31763**
31764** Not supplying an error message will have no adverse effect
31765** on SQLite. It is fine to have an implementation that never
31766** returns an error message:
31767**
31768**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31769**     assert(zBuf[0]=='\0');
31770**     return 0;
31771**   }
31772**
31773** However if an error message is supplied, it will be incorporated
31774** by sqlite into the error message available to the user using
31775** sqlite3_errmsg(), possibly making IO errors easier to debug.
31776*/
31777static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
31778  UNUSED_PARAMETER(pVfs);
31779  return getLastErrorMsg(nBuf, zBuf);
31780}
31781
31782
31783
31784/*
31785** Initialize and deinitialize the operating system interface.
31786*/
31787SQLITE_API int sqlite3_os_init(void){
31788  static sqlite3_vfs winVfs = {
31789    2,                   /* iVersion */
31790    sizeof(winFile),     /* szOsFile */
31791    MAX_PATH,            /* mxPathname */
31792    0,                   /* pNext */
31793    "win32",             /* zName */
31794    0,                   /* pAppData */
31795    winOpen,             /* xOpen */
31796    winDelete,           /* xDelete */
31797    winAccess,           /* xAccess */
31798    winFullPathname,     /* xFullPathname */
31799    winDlOpen,           /* xDlOpen */
31800    winDlError,          /* xDlError */
31801    winDlSym,            /* xDlSym */
31802    winDlClose,          /* xDlClose */
31803    winRandomness,       /* xRandomness */
31804    winSleep,            /* xSleep */
31805    winCurrentTime,      /* xCurrentTime */
31806    winGetLastError,     /* xGetLastError */
31807    winCurrentTimeInt64, /* xCurrentTimeInt64 */
31808  };
31809
31810  sqlite3_vfs_register(&winVfs, 1);
31811  return SQLITE_OK;
31812}
31813SQLITE_API int sqlite3_os_end(void){
31814  return SQLITE_OK;
31815}
31816
31817#endif /* SQLITE_OS_WIN */
31818
31819/************** End of os_win.c **********************************************/
31820/************** Begin file bitvec.c ******************************************/
31821/*
31822** 2008 February 16
31823**
31824** The author disclaims copyright to this source code.  In place of
31825** a legal notice, here is a blessing:
31826**
31827**    May you do good and not evil.
31828**    May you find forgiveness for yourself and forgive others.
31829**    May you share freely, never taking more than you give.
31830**
31831*************************************************************************
31832** This file implements an object that represents a fixed-length
31833** bitmap.  Bits are numbered starting with 1.
31834**
31835** A bitmap is used to record which pages of a database file have been
31836** journalled during a transaction, or which pages have the "dont-write"
31837** property.  Usually only a few pages are meet either condition.
31838** So the bitmap is usually sparse and has low cardinality.
31839** But sometimes (for example when during a DROP of a large table) most
31840** or all of the pages in a database can get journalled.  In those cases,
31841** the bitmap becomes dense with high cardinality.  The algorithm needs
31842** to handle both cases well.
31843**
31844** The size of the bitmap is fixed when the object is created.
31845**
31846** All bits are clear when the bitmap is created.  Individual bits
31847** may be set or cleared one at a time.
31848**
31849** Test operations are about 100 times more common that set operations.
31850** Clear operations are exceedingly rare.  There are usually between
31851** 5 and 500 set operations per Bitvec object, though the number of sets can
31852** sometimes grow into tens of thousands or larger.  The size of the
31853** Bitvec object is the number of pages in the database file at the
31854** start of a transaction, and is thus usually less than a few thousand,
31855** but can be as large as 2 billion for a really big database.
31856*/
31857
31858/* Size of the Bitvec structure in bytes. */
31859#define BITVEC_SZ        512
31860
31861/* Round the union size down to the nearest pointer boundary, since that's how
31862** it will be aligned within the Bitvec struct. */
31863#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
31864
31865/* Type of the array "element" for the bitmap representation.
31866** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
31867** Setting this to the "natural word" size of your CPU may improve
31868** performance. */
31869#define BITVEC_TELEM     u8
31870/* Size, in bits, of the bitmap element. */
31871#define BITVEC_SZELEM    8
31872/* Number of elements in a bitmap array. */
31873#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
31874/* Number of bits in the bitmap array. */
31875#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
31876
31877/* Number of u32 values in hash table. */
31878#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
31879/* Maximum number of entries in hash table before
31880** sub-dividing and re-hashing. */
31881#define BITVEC_MXHASH    (BITVEC_NINT/2)
31882/* Hashing function for the aHash representation.
31883** Empirical testing showed that the *37 multiplier
31884** (an arbitrary prime)in the hash function provided
31885** no fewer collisions than the no-op *1. */
31886#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
31887
31888#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
31889
31890
31891/*
31892** A bitmap is an instance of the following structure.
31893**
31894** This bitmap records the existance of zero or more bits
31895** with values between 1 and iSize, inclusive.
31896**
31897** There are three possible representations of the bitmap.
31898** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
31899** bitmap.  The least significant bit is bit 1.
31900**
31901** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
31902** a hash table that will hold up to BITVEC_MXHASH distinct values.
31903**
31904** Otherwise, the value i is redirected into one of BITVEC_NPTR
31905** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
31906** handles up to iDivisor separate values of i.  apSub[0] holds
31907** values between 1 and iDivisor.  apSub[1] holds values between
31908** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
31909** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
31910** to hold deal with values between 1 and iDivisor.
31911*/
31912struct Bitvec {
31913  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
31914  u32 nSet;       /* Number of bits that are set - only valid for aHash
31915                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
31916                  ** this would be 125. */
31917  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
31918                  /* Should >=0 for apSub element. */
31919                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
31920                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
31921  union {
31922    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
31923    u32 aHash[BITVEC_NINT];      /* Hash table representation */
31924    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
31925  } u;
31926};
31927
31928/*
31929** Create a new bitmap object able to handle bits between 0 and iSize,
31930** inclusive.  Return a pointer to the new object.  Return NULL if
31931** malloc fails.
31932*/
31933SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
31934  Bitvec *p;
31935  assert( sizeof(*p)==BITVEC_SZ );
31936  p = sqlite3MallocZero( sizeof(*p) );
31937  if( p ){
31938    p->iSize = iSize;
31939  }
31940  return p;
31941}
31942
31943/*
31944** Check to see if the i-th bit is set.  Return true or false.
31945** If p is NULL (if the bitmap has not been created) or if
31946** i is out of range, then return false.
31947*/
31948SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
31949  if( p==0 ) return 0;
31950  if( i>p->iSize || i==0 ) return 0;
31951  i--;
31952  while( p->iDivisor ){
31953    u32 bin = i/p->iDivisor;
31954    i = i%p->iDivisor;
31955    p = p->u.apSub[bin];
31956    if (!p) {
31957      return 0;
31958    }
31959  }
31960  if( p->iSize<=BITVEC_NBIT ){
31961    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
31962  } else{
31963    u32 h = BITVEC_HASH(i++);
31964    while( p->u.aHash[h] ){
31965      if( p->u.aHash[h]==i ) return 1;
31966      h = (h+1) % BITVEC_NINT;
31967    }
31968    return 0;
31969  }
31970}
31971
31972/*
31973** Set the i-th bit.  Return 0 on success and an error code if
31974** anything goes wrong.
31975**
31976** This routine might cause sub-bitmaps to be allocated.  Failing
31977** to get the memory needed to hold the sub-bitmap is the only
31978** that can go wrong with an insert, assuming p and i are valid.
31979**
31980** The calling function must ensure that p is a valid Bitvec object
31981** and that the value for "i" is within range of the Bitvec object.
31982** Otherwise the behavior is undefined.
31983*/
31984SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
31985  u32 h;
31986  if( p==0 ) return SQLITE_OK;
31987  assert( i>0 );
31988  assert( i<=p->iSize );
31989  i--;
31990  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
31991    u32 bin = i/p->iDivisor;
31992    i = i%p->iDivisor;
31993    if( p->u.apSub[bin]==0 ){
31994      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
31995      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
31996    }
31997    p = p->u.apSub[bin];
31998  }
31999  if( p->iSize<=BITVEC_NBIT ){
32000    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
32001    return SQLITE_OK;
32002  }
32003  h = BITVEC_HASH(i++);
32004  /* if there wasn't a hash collision, and this doesn't */
32005  /* completely fill the hash, then just add it without */
32006  /* worring about sub-dividing and re-hashing. */
32007  if( !p->u.aHash[h] ){
32008    if (p->nSet<(BITVEC_NINT-1)) {
32009      goto bitvec_set_end;
32010    } else {
32011      goto bitvec_set_rehash;
32012    }
32013  }
32014  /* there was a collision, check to see if it's already */
32015  /* in hash, if not, try to find a spot for it */
32016  do {
32017    if( p->u.aHash[h]==i ) return SQLITE_OK;
32018    h++;
32019    if( h>=BITVEC_NINT ) h = 0;
32020  } while( p->u.aHash[h] );
32021  /* we didn't find it in the hash.  h points to the first */
32022  /* available free spot. check to see if this is going to */
32023  /* make our hash too "full".  */
32024bitvec_set_rehash:
32025  if( p->nSet>=BITVEC_MXHASH ){
32026    unsigned int j;
32027    int rc;
32028    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
32029    if( aiValues==0 ){
32030      return SQLITE_NOMEM;
32031    }else{
32032      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32033      memset(p->u.apSub, 0, sizeof(p->u.apSub));
32034      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
32035      rc = sqlite3BitvecSet(p, i);
32036      for(j=0; j<BITVEC_NINT; j++){
32037        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
32038      }
32039      sqlite3StackFree(0, aiValues);
32040      return rc;
32041    }
32042  }
32043bitvec_set_end:
32044  p->nSet++;
32045  p->u.aHash[h] = i;
32046  return SQLITE_OK;
32047}
32048
32049/*
32050** Clear the i-th bit.
32051**
32052** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
32053** that BitvecClear can use to rebuilt its hash table.
32054*/
32055SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
32056  if( p==0 ) return;
32057  assert( i>0 );
32058  i--;
32059  while( p->iDivisor ){
32060    u32 bin = i/p->iDivisor;
32061    i = i%p->iDivisor;
32062    p = p->u.apSub[bin];
32063    if (!p) {
32064      return;
32065    }
32066  }
32067  if( p->iSize<=BITVEC_NBIT ){
32068    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
32069  }else{
32070    unsigned int j;
32071    u32 *aiValues = pBuf;
32072    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32073    memset(p->u.aHash, 0, sizeof(p->u.aHash));
32074    p->nSet = 0;
32075    for(j=0; j<BITVEC_NINT; j++){
32076      if( aiValues[j] && aiValues[j]!=(i+1) ){
32077        u32 h = BITVEC_HASH(aiValues[j]-1);
32078        p->nSet++;
32079        while( p->u.aHash[h] ){
32080          h++;
32081          if( h>=BITVEC_NINT ) h = 0;
32082        }
32083        p->u.aHash[h] = aiValues[j];
32084      }
32085    }
32086  }
32087}
32088
32089/*
32090** Destroy a bitmap object.  Reclaim all memory used.
32091*/
32092SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
32093  if( p==0 ) return;
32094  if( p->iDivisor ){
32095    unsigned int i;
32096    for(i=0; i<BITVEC_NPTR; i++){
32097      sqlite3BitvecDestroy(p->u.apSub[i]);
32098    }
32099  }
32100  sqlite3_free(p);
32101}
32102
32103/*
32104** Return the value of the iSize parameter specified when Bitvec *p
32105** was created.
32106*/
32107SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
32108  return p->iSize;
32109}
32110
32111#ifndef SQLITE_OMIT_BUILTIN_TEST
32112/*
32113** Let V[] be an array of unsigned characters sufficient to hold
32114** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
32115** Then the following macros can be used to set, clear, or test
32116** individual bits within V.
32117*/
32118#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
32119#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
32120#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
32121
32122/*
32123** This routine runs an extensive test of the Bitvec code.
32124**
32125** The input is an array of integers that acts as a program
32126** to test the Bitvec.  The integers are opcodes followed
32127** by 0, 1, or 3 operands, depending on the opcode.  Another
32128** opcode follows immediately after the last operand.
32129**
32130** There are 6 opcodes numbered from 0 through 5.  0 is the
32131** "halt" opcode and causes the test to end.
32132**
32133**    0          Halt and return the number of errors
32134**    1 N S X    Set N bits beginning with S and incrementing by X
32135**    2 N S X    Clear N bits beginning with S and incrementing by X
32136**    3 N        Set N randomly chosen bits
32137**    4 N        Clear N randomly chosen bits
32138**    5 N S X    Set N bits from S increment X in array only, not in bitvec
32139**
32140** The opcodes 1 through 4 perform set and clear operations are performed
32141** on both a Bitvec object and on a linear array of bits obtained from malloc.
32142** Opcode 5 works on the linear array only, not on the Bitvec.
32143** Opcode 5 is used to deliberately induce a fault in order to
32144** confirm that error detection works.
32145**
32146** At the conclusion of the test the linear array is compared
32147** against the Bitvec object.  If there are any differences,
32148** an error is returned.  If they are the same, zero is returned.
32149**
32150** If a memory allocation error occurs, return -1.
32151*/
32152SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
32153  Bitvec *pBitvec = 0;
32154  unsigned char *pV = 0;
32155  int rc = -1;
32156  int i, nx, pc, op;
32157  void *pTmpSpace;
32158
32159  /* Allocate the Bitvec to be tested and a linear array of
32160  ** bits to act as the reference */
32161  pBitvec = sqlite3BitvecCreate( sz );
32162  pV = sqlite3_malloc( (sz+7)/8 + 1 );
32163  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
32164  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
32165  memset(pV, 0, (sz+7)/8 + 1);
32166
32167  /* NULL pBitvec tests */
32168  sqlite3BitvecSet(0, 1);
32169  sqlite3BitvecClear(0, 1, pTmpSpace);
32170
32171  /* Run the program */
32172  pc = 0;
32173  while( (op = aOp[pc])!=0 ){
32174    switch( op ){
32175      case 1:
32176      case 2:
32177      case 5: {
32178        nx = 4;
32179        i = aOp[pc+2] - 1;
32180        aOp[pc+2] += aOp[pc+3];
32181        break;
32182      }
32183      case 3:
32184      case 4:
32185      default: {
32186        nx = 2;
32187        sqlite3_randomness(sizeof(i), &i);
32188        break;
32189      }
32190    }
32191    if( (--aOp[pc+1]) > 0 ) nx = 0;
32192    pc += nx;
32193    i = (i & 0x7fffffff)%sz;
32194    if( (op & 1)!=0 ){
32195      SETBIT(pV, (i+1));
32196      if( op!=5 ){
32197        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
32198      }
32199    }else{
32200      CLEARBIT(pV, (i+1));
32201      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
32202    }
32203  }
32204
32205  /* Test to make sure the linear array exactly matches the
32206  ** Bitvec object.  Start with the assumption that they do
32207  ** match (rc==0).  Change rc to non-zero if a discrepancy
32208  ** is found.
32209  */
32210  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
32211          + sqlite3BitvecTest(pBitvec, 0)
32212          + (sqlite3BitvecSize(pBitvec) - sz);
32213  for(i=1; i<=sz; i++){
32214    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
32215      rc = i;
32216      break;
32217    }
32218  }
32219
32220  /* Free allocated structure */
32221bitvec_end:
32222  sqlite3_free(pTmpSpace);
32223  sqlite3_free(pV);
32224  sqlite3BitvecDestroy(pBitvec);
32225  return rc;
32226}
32227#endif /* SQLITE_OMIT_BUILTIN_TEST */
32228
32229/************** End of bitvec.c **********************************************/
32230/************** Begin file pcache.c ******************************************/
32231/*
32232** 2008 August 05
32233**
32234** The author disclaims copyright to this source code.  In place of
32235** a legal notice, here is a blessing:
32236**
32237**    May you do good and not evil.
32238**    May you find forgiveness for yourself and forgive others.
32239**    May you share freely, never taking more than you give.
32240**
32241*************************************************************************
32242** This file implements that page cache.
32243*/
32244
32245/*
32246** A complete page cache is an instance of this structure.
32247*/
32248struct PCache {
32249  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
32250  PgHdr *pSynced;                     /* Last synced page in dirty page list */
32251  int nRef;                           /* Number of referenced pages */
32252  int nMax;                           /* Configured cache size */
32253  int szPage;                         /* Size of every page in this cache */
32254  int szExtra;                        /* Size of extra space for each page */
32255  int bPurgeable;                     /* True if pages are on backing store */
32256  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
32257  void *pStress;                      /* Argument to xStress */
32258  sqlite3_pcache *pCache;             /* Pluggable cache module */
32259  PgHdr *pPage1;                      /* Reference to page 1 */
32260};
32261
32262/*
32263** Some of the assert() macros in this code are too expensive to run
32264** even during normal debugging.  Use them only rarely on long-running
32265** tests.  Enable the expensive asserts using the
32266** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
32267*/
32268#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
32269# define expensive_assert(X)  assert(X)
32270#else
32271# define expensive_assert(X)
32272#endif
32273
32274/********************************** Linked List Management ********************/
32275
32276#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
32277/*
32278** Check that the pCache->pSynced variable is set correctly. If it
32279** is not, either fail an assert or return zero. Otherwise, return
32280** non-zero. This is only used in debugging builds, as follows:
32281**
32282**   expensive_assert( pcacheCheckSynced(pCache) );
32283*/
32284static int pcacheCheckSynced(PCache *pCache){
32285  PgHdr *p;
32286  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
32287    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
32288  }
32289  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
32290}
32291#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
32292
32293/*
32294** Remove page pPage from the list of dirty pages.
32295*/
32296static void pcacheRemoveFromDirtyList(PgHdr *pPage){
32297  PCache *p = pPage->pCache;
32298
32299  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
32300  assert( pPage->pDirtyPrev || pPage==p->pDirty );
32301
32302  /* Update the PCache1.pSynced variable if necessary. */
32303  if( p->pSynced==pPage ){
32304    PgHdr *pSynced = pPage->pDirtyPrev;
32305    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
32306      pSynced = pSynced->pDirtyPrev;
32307    }
32308    p->pSynced = pSynced;
32309  }
32310
32311  if( pPage->pDirtyNext ){
32312    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
32313  }else{
32314    assert( pPage==p->pDirtyTail );
32315    p->pDirtyTail = pPage->pDirtyPrev;
32316  }
32317  if( pPage->pDirtyPrev ){
32318    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
32319  }else{
32320    assert( pPage==p->pDirty );
32321    p->pDirty = pPage->pDirtyNext;
32322  }
32323  pPage->pDirtyNext = 0;
32324  pPage->pDirtyPrev = 0;
32325
32326  expensive_assert( pcacheCheckSynced(p) );
32327}
32328
32329/*
32330** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
32331** pPage).
32332*/
32333static void pcacheAddToDirtyList(PgHdr *pPage){
32334  PCache *p = pPage->pCache;
32335
32336  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
32337
32338  pPage->pDirtyNext = p->pDirty;
32339  if( pPage->pDirtyNext ){
32340    assert( pPage->pDirtyNext->pDirtyPrev==0 );
32341    pPage->pDirtyNext->pDirtyPrev = pPage;
32342  }
32343  p->pDirty = pPage;
32344  if( !p->pDirtyTail ){
32345    p->pDirtyTail = pPage;
32346  }
32347  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
32348    p->pSynced = pPage;
32349  }
32350  expensive_assert( pcacheCheckSynced(p) );
32351}
32352
32353/*
32354** Wrapper around the pluggable caches xUnpin method. If the cache is
32355** being used for an in-memory database, this function is a no-op.
32356*/
32357static void pcacheUnpin(PgHdr *p){
32358  PCache *pCache = p->pCache;
32359  if( pCache->bPurgeable ){
32360    if( p->pgno==1 ){
32361      pCache->pPage1 = 0;
32362    }
32363    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
32364  }
32365}
32366
32367/*************************************************** General Interfaces ******
32368**
32369** Initialize and shutdown the page cache subsystem. Neither of these
32370** functions are threadsafe.
32371*/
32372SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32373  if( sqlite3GlobalConfig.pcache.xInit==0 ){
32374    sqlite3PCacheSetDefault();
32375  }
32376  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32377}
32378SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32379  if( sqlite3GlobalConfig.pcache.xShutdown ){
32380    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32381  }
32382}
32383
32384/*
32385** Return the size in bytes of a PCache object.
32386*/
32387SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
32388
32389/*
32390** Create a new PCache object. Storage space to hold the object
32391** has already been allocated and is passed in as the p pointer.
32392** The caller discovers how much space needs to be allocated by
32393** calling sqlite3PcacheSize().
32394*/
32395SQLITE_PRIVATE void sqlite3PcacheOpen(
32396  int szPage,                  /* Size of every page */
32397  int szExtra,                 /* Extra space associated with each page */
32398  int bPurgeable,              /* True if pages are on backing store */
32399  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
32400  void *pStress,               /* Argument to xStress */
32401  PCache *p                    /* Preallocated space for the PCache */
32402){
32403  memset(p, 0, sizeof(PCache));
32404  p->szPage = szPage;
32405  p->szExtra = szExtra;
32406  p->bPurgeable = bPurgeable;
32407  p->xStress = xStress;
32408  p->pStress = pStress;
32409  p->nMax = 100;
32410}
32411
32412/*
32413** Change the page size for PCache object. The caller must ensure that there
32414** are no outstanding page references when this function is called.
32415*/
32416SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
32417  assert( pCache->nRef==0 && pCache->pDirty==0 );
32418  if( pCache->pCache ){
32419    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32420    pCache->pCache = 0;
32421    pCache->pPage1 = 0;
32422  }
32423  pCache->szPage = szPage;
32424}
32425
32426/*
32427** Try to obtain a page from the cache.
32428*/
32429SQLITE_PRIVATE int sqlite3PcacheFetch(
32430  PCache *pCache,       /* Obtain the page from this cache */
32431  Pgno pgno,            /* Page number to obtain */
32432  int createFlag,       /* If true, create page if it does not exist already */
32433  PgHdr **ppPage        /* Write the page here */
32434){
32435  PgHdr *pPage = 0;
32436  int eCreate;
32437
32438  assert( pCache!=0 );
32439  assert( createFlag==1 || createFlag==0 );
32440  assert( pgno>0 );
32441
32442  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
32443  ** allocate it now.
32444  */
32445  if( !pCache->pCache && createFlag ){
32446    sqlite3_pcache *p;
32447    int nByte;
32448    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
32449    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
32450    if( !p ){
32451      return SQLITE_NOMEM;
32452    }
32453    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
32454    pCache->pCache = p;
32455  }
32456
32457  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
32458  if( pCache->pCache ){
32459    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
32460  }
32461
32462  if( !pPage && eCreate==1 ){
32463    PgHdr *pPg;
32464
32465    /* Find a dirty page to write-out and recycle. First try to find a
32466    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
32467    ** cleared), but if that is not possible settle for any other
32468    ** unreferenced dirty page.
32469    */
32470    expensive_assert( pcacheCheckSynced(pCache) );
32471    for(pPg=pCache->pSynced;
32472        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
32473        pPg=pPg->pDirtyPrev
32474    );
32475    pCache->pSynced = pPg;
32476    if( !pPg ){
32477      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
32478    }
32479    if( pPg ){
32480      int rc;
32481      rc = pCache->xStress(pCache->pStress, pPg);
32482      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
32483        return rc;
32484      }
32485    }
32486
32487    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
32488  }
32489
32490  if( pPage ){
32491    if( !pPage->pData ){
32492      memset(pPage, 0, sizeof(PgHdr));
32493      pPage->pData = (void *)&pPage[1];
32494      pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
32495      memset(pPage->pExtra, 0, pCache->szExtra);
32496      pPage->pCache = pCache;
32497      pPage->pgno = pgno;
32498    }
32499    assert( pPage->pCache==pCache );
32500    assert( pPage->pgno==pgno );
32501    assert( pPage->pData==(void *)&pPage[1] );
32502    assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
32503
32504    if( 0==pPage->nRef ){
32505      pCache->nRef++;
32506    }
32507    pPage->nRef++;
32508    if( pgno==1 ){
32509      pCache->pPage1 = pPage;
32510    }
32511  }
32512  *ppPage = pPage;
32513  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
32514}
32515
32516/*
32517** Decrement the reference count on a page. If the page is clean and the
32518** reference count drops to 0, then it is made elible for recycling.
32519*/
32520SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
32521  assert( p->nRef>0 );
32522  p->nRef--;
32523  if( p->nRef==0 ){
32524    PCache *pCache = p->pCache;
32525    pCache->nRef--;
32526    if( (p->flags&PGHDR_DIRTY)==0 ){
32527      pcacheUnpin(p);
32528    }else{
32529      /* Move the page to the head of the dirty list. */
32530      pcacheRemoveFromDirtyList(p);
32531      pcacheAddToDirtyList(p);
32532    }
32533  }
32534}
32535
32536/*
32537** Increase the reference count of a supplied page by 1.
32538*/
32539SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
32540  assert(p->nRef>0);
32541  p->nRef++;
32542}
32543
32544/*
32545** Drop a page from the cache. There must be exactly one reference to the
32546** page. This function deletes that reference, so after it returns the
32547** page pointed to by p is invalid.
32548*/
32549SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
32550  PCache *pCache;
32551  assert( p->nRef==1 );
32552  if( p->flags&PGHDR_DIRTY ){
32553    pcacheRemoveFromDirtyList(p);
32554  }
32555  pCache = p->pCache;
32556  pCache->nRef--;
32557  if( p->pgno==1 ){
32558    pCache->pPage1 = 0;
32559  }
32560  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
32561}
32562
32563/*
32564** Make sure the page is marked as dirty. If it isn't dirty already,
32565** make it so.
32566*/
32567SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
32568  p->flags &= ~PGHDR_DONT_WRITE;
32569  assert( p->nRef>0 );
32570  if( 0==(p->flags & PGHDR_DIRTY) ){
32571    p->flags |= PGHDR_DIRTY;
32572    pcacheAddToDirtyList( p);
32573  }
32574}
32575
32576/*
32577** Make sure the page is marked as clean. If it isn't clean already,
32578** make it so.
32579*/
32580SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
32581  if( (p->flags & PGHDR_DIRTY) ){
32582    pcacheRemoveFromDirtyList(p);
32583    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
32584    if( p->nRef==0 ){
32585      pcacheUnpin(p);
32586    }
32587  }
32588}
32589
32590/*
32591** Make every page in the cache clean.
32592*/
32593SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
32594  PgHdr *p;
32595  while( (p = pCache->pDirty)!=0 ){
32596    sqlite3PcacheMakeClean(p);
32597  }
32598}
32599
32600/*
32601** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
32602*/
32603SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
32604  PgHdr *p;
32605  for(p=pCache->pDirty; p; p=p->pDirtyNext){
32606    p->flags &= ~PGHDR_NEED_SYNC;
32607  }
32608  pCache->pSynced = pCache->pDirtyTail;
32609}
32610
32611/*
32612** Change the page number of page p to newPgno.
32613*/
32614SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
32615  PCache *pCache = p->pCache;
32616  assert( p->nRef>0 );
32617  assert( newPgno>0 );
32618  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
32619  p->pgno = newPgno;
32620  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
32621    pcacheRemoveFromDirtyList(p);
32622    pcacheAddToDirtyList(p);
32623  }
32624}
32625
32626/*
32627** Drop every cache entry whose page number is greater than "pgno". The
32628** caller must ensure that there are no outstanding references to any pages
32629** other than page 1 with a page number greater than pgno.
32630**
32631** If there is a reference to page 1 and the pgno parameter passed to this
32632** function is 0, then the data area associated with page 1 is zeroed, but
32633** the page object is not dropped.
32634*/
32635SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
32636  if( pCache->pCache ){
32637    PgHdr *p;
32638    PgHdr *pNext;
32639    for(p=pCache->pDirty; p; p=pNext){
32640      pNext = p->pDirtyNext;
32641      /* This routine never gets call with a positive pgno except right
32642      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
32643      ** it must be that pgno==0.
32644      */
32645      assert( p->pgno>0 );
32646      if( ALWAYS(p->pgno>pgno) ){
32647        assert( p->flags&PGHDR_DIRTY );
32648        sqlite3PcacheMakeClean(p);
32649      }
32650    }
32651    if( pgno==0 && pCache->pPage1 ){
32652      memset(pCache->pPage1->pData, 0, pCache->szPage);
32653      pgno = 1;
32654    }
32655    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
32656  }
32657}
32658
32659/*
32660** Close a cache.
32661*/
32662SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
32663  if( pCache->pCache ){
32664    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32665  }
32666}
32667
32668/*
32669** Discard the contents of the cache.
32670*/
32671SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
32672  sqlite3PcacheTruncate(pCache, 0);
32673}
32674
32675/*
32676** Merge two lists of pages connected by pDirty and in pgno order.
32677** Do not both fixing the pDirtyPrev pointers.
32678*/
32679static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
32680  PgHdr result, *pTail;
32681  pTail = &result;
32682  while( pA && pB ){
32683    if( pA->pgno<pB->pgno ){
32684      pTail->pDirty = pA;
32685      pTail = pA;
32686      pA = pA->pDirty;
32687    }else{
32688      pTail->pDirty = pB;
32689      pTail = pB;
32690      pB = pB->pDirty;
32691    }
32692  }
32693  if( pA ){
32694    pTail->pDirty = pA;
32695  }else if( pB ){
32696    pTail->pDirty = pB;
32697  }else{
32698    pTail->pDirty = 0;
32699  }
32700  return result.pDirty;
32701}
32702
32703/*
32704** Sort the list of pages in accending order by pgno.  Pages are
32705** connected by pDirty pointers.  The pDirtyPrev pointers are
32706** corrupted by this sort.
32707**
32708** Since there cannot be more than 2^31 distinct pages in a database,
32709** there cannot be more than 31 buckets required by the merge sorter.
32710** One extra bucket is added to catch overflow in case something
32711** ever changes to make the previous sentence incorrect.
32712*/
32713#define N_SORT_BUCKET  32
32714static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
32715  PgHdr *a[N_SORT_BUCKET], *p;
32716  int i;
32717  memset(a, 0, sizeof(a));
32718  while( pIn ){
32719    p = pIn;
32720    pIn = p->pDirty;
32721    p->pDirty = 0;
32722    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
32723      if( a[i]==0 ){
32724        a[i] = p;
32725        break;
32726      }else{
32727        p = pcacheMergeDirtyList(a[i], p);
32728        a[i] = 0;
32729      }
32730    }
32731    if( NEVER(i==N_SORT_BUCKET-1) ){
32732      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
32733      ** the input list.  But that is impossible.
32734      */
32735      a[i] = pcacheMergeDirtyList(a[i], p);
32736    }
32737  }
32738  p = a[0];
32739  for(i=1; i<N_SORT_BUCKET; i++){
32740    p = pcacheMergeDirtyList(p, a[i]);
32741  }
32742  return p;
32743}
32744
32745/*
32746** Return a list of all dirty pages in the cache, sorted by page number.
32747*/
32748SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
32749  PgHdr *p;
32750  for(p=pCache->pDirty; p; p=p->pDirtyNext){
32751    p->pDirty = p->pDirtyNext;
32752  }
32753  return pcacheSortDirtyList(pCache->pDirty);
32754}
32755
32756/*
32757** Return the total number of referenced pages held by the cache.
32758*/
32759SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
32760  return pCache->nRef;
32761}
32762
32763/*
32764** Return the number of references to the page supplied as an argument.
32765*/
32766SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
32767  return p->nRef;
32768}
32769
32770/*
32771** Return the total number of pages in the cache.
32772*/
32773SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
32774  int nPage = 0;
32775  if( pCache->pCache ){
32776    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
32777  }
32778  return nPage;
32779}
32780
32781#ifdef SQLITE_TEST
32782/*
32783** Get the suggested cache-size value.
32784*/
32785SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
32786  return pCache->nMax;
32787}
32788#endif
32789
32790/*
32791** Set the suggested cache-size value.
32792*/
32793SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
32794  pCache->nMax = mxPage;
32795  if( pCache->pCache ){
32796    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
32797  }
32798}
32799
32800#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
32801/*
32802** For all dirty pages currently in the cache, invoke the specified
32803** callback. This is only used if the SQLITE_CHECK_PAGES macro is
32804** defined.
32805*/
32806SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
32807  PgHdr *pDirty;
32808  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
32809    xIter(pDirty);
32810  }
32811}
32812#endif
32813
32814/************** End of pcache.c **********************************************/
32815/************** Begin file pcache1.c *****************************************/
32816/*
32817** 2008 November 05
32818**
32819** The author disclaims copyright to this source code.  In place of
32820** a legal notice, here is a blessing:
32821**
32822**    May you do good and not evil.
32823**    May you find forgiveness for yourself and forgive others.
32824**    May you share freely, never taking more than you give.
32825**
32826*************************************************************************
32827**
32828** This file implements the default page cache implementation (the
32829** sqlite3_pcache interface). It also contains part of the implementation
32830** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
32831** If the default page cache implementation is overriden, then neither of
32832** these two features are available.
32833*/
32834
32835
32836typedef struct PCache1 PCache1;
32837typedef struct PgHdr1 PgHdr1;
32838typedef struct PgFreeslot PgFreeslot;
32839
32840/* Pointers to structures of this type are cast and returned as
32841** opaque sqlite3_pcache* handles
32842*/
32843struct PCache1 {
32844  /* Cache configuration parameters. Page size (szPage) and the purgeable
32845  ** flag (bPurgeable) are set when the cache is created. nMax may be
32846  ** modified at any time by a call to the pcache1CacheSize() method.
32847  ** The global mutex must be held when accessing nMax.
32848  */
32849  int szPage;                         /* Size of allocated pages in bytes */
32850  int bPurgeable;                     /* True if cache is purgeable */
32851  unsigned int nMin;                  /* Minimum number of pages reserved */
32852  unsigned int nMax;                  /* Configured "cache_size" value */
32853
32854  /* Hash table of all pages. The following variables may only be accessed
32855  ** when the accessor is holding the global mutex (see pcache1EnterMutex()
32856  ** and pcache1LeaveMutex()).
32857  */
32858  unsigned int nRecyclable;           /* Number of pages in the LRU list */
32859  unsigned int nPage;                 /* Total number of pages in apHash */
32860  unsigned int nHash;                 /* Number of slots in apHash[] */
32861  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
32862
32863  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
32864};
32865
32866/*
32867** Each cache entry is represented by an instance of the following
32868** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
32869** directly before this structure in memory (see the PGHDR1_TO_PAGE()
32870** macro below).
32871*/
32872struct PgHdr1 {
32873  unsigned int iKey;             /* Key value (page number) */
32874  PgHdr1 *pNext;                 /* Next in hash table chain */
32875  PCache1 *pCache;               /* Cache that currently owns this page */
32876  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
32877  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
32878};
32879
32880/*
32881** Free slots in the allocator used to divide up the buffer provided using
32882** the SQLITE_CONFIG_PAGECACHE mechanism.
32883*/
32884struct PgFreeslot {
32885  PgFreeslot *pNext;  /* Next free slot */
32886};
32887
32888/*
32889** Global data used by this cache.
32890*/
32891static SQLITE_WSD struct PCacheGlobal {
32892  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
32893
32894  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
32895  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
32896  int nCurrentPage;                   /* Number of purgeable pages allocated */
32897  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
32898
32899  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
32900  int szSlot;                         /* Size of each free slot */
32901  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
32902  PgFreeslot *pFree;                  /* Free page blocks */
32903  int isInit;                         /* True if initialized */
32904} pcache1_g;
32905
32906/*
32907** All code in this file should access the global structure above via the
32908** alias "pcache1". This ensures that the WSD emulation is used when
32909** compiling for systems that do not support real WSD.
32910*/
32911#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
32912
32913/*
32914** When a PgHdr1 structure is allocated, the associated PCache1.szPage
32915** bytes of data are located directly before it in memory (i.e. the total
32916** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
32917** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
32918** an argument and returns a pointer to the associated block of szPage
32919** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
32920** a pointer to a block of szPage bytes of data and the return value is
32921** a pointer to the associated PgHdr1 structure.
32922**
32923**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
32924*/
32925#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
32926#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
32927
32928/*
32929** Macros to enter and leave the global LRU mutex.
32930*/
32931#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
32932#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
32933
32934/******************************************************************************/
32935/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
32936
32937/*
32938** This function is called during initialization if a static buffer is
32939** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
32940** verb to sqlite3_config(). Parameter pBuf points to an allocation large
32941** enough to contain 'n' buffers of 'sz' bytes each.
32942*/
32943SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
32944  if( pcache1.isInit ){
32945    PgFreeslot *p;
32946    sz = ROUNDDOWN8(sz);
32947    pcache1.szSlot = sz;
32948    pcache1.pStart = pBuf;
32949    pcache1.pFree = 0;
32950    while( n-- ){
32951      p = (PgFreeslot*)pBuf;
32952      p->pNext = pcache1.pFree;
32953      pcache1.pFree = p;
32954      pBuf = (void*)&((char*)pBuf)[sz];
32955    }
32956    pcache1.pEnd = pBuf;
32957  }
32958}
32959
32960/*
32961** Malloc function used within this file to allocate space from the buffer
32962** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
32963** such buffer exists or there is no space left in it, this function falls
32964** back to sqlite3Malloc().
32965*/
32966static void *pcache1Alloc(int nByte){
32967  void *p;
32968  assert( sqlite3_mutex_held(pcache1.mutex) );
32969  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
32970  if( nByte<=pcache1.szSlot && pcache1.pFree ){
32971    assert( pcache1.isInit );
32972    p = (PgHdr1 *)pcache1.pFree;
32973    pcache1.pFree = pcache1.pFree->pNext;
32974    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
32975  }else{
32976
32977    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
32978    ** global pcache mutex and unlock the pager-cache object pCache. This is
32979    ** so that if the attempt to allocate a new buffer causes the the
32980    ** configured soft-heap-limit to be breached, it will be possible to
32981    ** reclaim memory from this pager-cache.
32982    */
32983    pcache1LeaveMutex();
32984    p = sqlite3Malloc(nByte);
32985    pcache1EnterMutex();
32986    if( p ){
32987      int sz = sqlite3MallocSize(p);
32988      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
32989    }
32990    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
32991  }
32992  return p;
32993}
32994
32995/*
32996** Free an allocated buffer obtained from pcache1Alloc().
32997*/
32998static void pcache1Free(void *p){
32999  assert( sqlite3_mutex_held(pcache1.mutex) );
33000  if( p==0 ) return;
33001  if( p>=pcache1.pStart && p<pcache1.pEnd ){
33002    PgFreeslot *pSlot;
33003    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
33004    pSlot = (PgFreeslot*)p;
33005    pSlot->pNext = pcache1.pFree;
33006    pcache1.pFree = pSlot;
33007  }else{
33008    int iSize;
33009    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33010    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33011    iSize = sqlite3MallocSize(p);
33012    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
33013    sqlite3_free(p);
33014  }
33015}
33016
33017#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33018/*
33019** Return the size of a pache allocation
33020*/
33021static int pcache1MemSize(void *p){
33022  assert( sqlite3_mutex_held(pcache1.mutex) );
33023  if( p>=pcache1.pStart && p<pcache1.pEnd ){
33024    return pcache1.szSlot;
33025  }else{
33026    int iSize;
33027    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33028    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33029    iSize = sqlite3MallocSize(p);
33030    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33031    return iSize;
33032  }
33033}
33034#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33035
33036/*
33037** Allocate a new page object initially associated with cache pCache.
33038*/
33039static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
33040  int nByte = sizeof(PgHdr1) + pCache->szPage;
33041  void *pPg = pcache1Alloc(nByte);
33042  PgHdr1 *p;
33043  if( pPg ){
33044    p = PAGE_TO_PGHDR1(pCache, pPg);
33045    if( pCache->bPurgeable ){
33046      pcache1.nCurrentPage++;
33047    }
33048  }else{
33049    p = 0;
33050  }
33051  return p;
33052}
33053
33054/*
33055** Free a page object allocated by pcache1AllocPage().
33056**
33057** The pointer is allowed to be NULL, which is prudent.  But it turns out
33058** that the current implementation happens to never call this routine
33059** with a NULL pointer, so we mark the NULL test with ALWAYS().
33060*/
33061static void pcache1FreePage(PgHdr1 *p){
33062  if( ALWAYS(p) ){
33063    if( p->pCache->bPurgeable ){
33064      pcache1.nCurrentPage--;
33065    }
33066    pcache1Free(PGHDR1_TO_PAGE(p));
33067  }
33068}
33069
33070/*
33071** Malloc function used by SQLite to obtain space from the buffer configured
33072** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
33073** exists, this function falls back to sqlite3Malloc().
33074*/
33075SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
33076  void *p;
33077  pcache1EnterMutex();
33078  p = pcache1Alloc(sz);
33079  pcache1LeaveMutex();
33080  return p;
33081}
33082
33083/*
33084** Free an allocated buffer obtained from sqlite3PageMalloc().
33085*/
33086SQLITE_PRIVATE void sqlite3PageFree(void *p){
33087  pcache1EnterMutex();
33088  pcache1Free(p);
33089  pcache1LeaveMutex();
33090}
33091
33092/******************************************************************************/
33093/******** General Implementation Functions ************************************/
33094
33095/*
33096** This function is used to resize the hash table used by the cache passed
33097** as the first argument.
33098**
33099** The global mutex must be held when this function is called.
33100*/
33101static int pcache1ResizeHash(PCache1 *p){
33102  PgHdr1 **apNew;
33103  unsigned int nNew;
33104  unsigned int i;
33105
33106  assert( sqlite3_mutex_held(pcache1.mutex) );
33107
33108  nNew = p->nHash*2;
33109  if( nNew<256 ){
33110    nNew = 256;
33111  }
33112
33113  pcache1LeaveMutex();
33114  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
33115  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
33116  if( p->nHash ){ sqlite3EndBenignMalloc(); }
33117  pcache1EnterMutex();
33118  if( apNew ){
33119    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
33120    for(i=0; i<p->nHash; i++){
33121      PgHdr1 *pPage;
33122      PgHdr1 *pNext = p->apHash[i];
33123      while( (pPage = pNext)!=0 ){
33124        unsigned int h = pPage->iKey % nNew;
33125        pNext = pPage->pNext;
33126        pPage->pNext = apNew[h];
33127        apNew[h] = pPage;
33128      }
33129    }
33130    sqlite3_free(p->apHash);
33131    p->apHash = apNew;
33132    p->nHash = nNew;
33133  }
33134
33135  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
33136}
33137
33138/*
33139** This function is used internally to remove the page pPage from the
33140** global LRU list, if is part of it. If pPage is not part of the global
33141** LRU list, then this function is a no-op.
33142**
33143** The global mutex must be held when this function is called.
33144*/
33145static void pcache1PinPage(PgHdr1 *pPage){
33146  assert( sqlite3_mutex_held(pcache1.mutex) );
33147  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
33148    if( pPage->pLruPrev ){
33149      pPage->pLruPrev->pLruNext = pPage->pLruNext;
33150    }
33151    if( pPage->pLruNext ){
33152      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
33153    }
33154    if( pcache1.pLruHead==pPage ){
33155      pcache1.pLruHead = pPage->pLruNext;
33156    }
33157    if( pcache1.pLruTail==pPage ){
33158      pcache1.pLruTail = pPage->pLruPrev;
33159    }
33160    pPage->pLruNext = 0;
33161    pPage->pLruPrev = 0;
33162    pPage->pCache->nRecyclable--;
33163  }
33164}
33165
33166
33167/*
33168** Remove the page supplied as an argument from the hash table
33169** (PCache1.apHash structure) that it is currently stored in.
33170**
33171** The global mutex must be held when this function is called.
33172*/
33173static void pcache1RemoveFromHash(PgHdr1 *pPage){
33174  unsigned int h;
33175  PCache1 *pCache = pPage->pCache;
33176  PgHdr1 **pp;
33177
33178  h = pPage->iKey % pCache->nHash;
33179  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
33180  *pp = (*pp)->pNext;
33181
33182  pCache->nPage--;
33183}
33184
33185/*
33186** If there are currently more than pcache.nMaxPage pages allocated, try
33187** to recycle pages to reduce the number allocated to pcache.nMaxPage.
33188*/
33189static void pcache1EnforceMaxPage(void){
33190  assert( sqlite3_mutex_held(pcache1.mutex) );
33191  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
33192    PgHdr1 *p = pcache1.pLruTail;
33193    pcache1PinPage(p);
33194    pcache1RemoveFromHash(p);
33195    pcache1FreePage(p);
33196  }
33197}
33198
33199/*
33200** Discard all pages from cache pCache with a page number (key value)
33201** greater than or equal to iLimit. Any pinned pages that meet this
33202** criteria are unpinned before they are discarded.
33203**
33204** The global mutex must be held when this function is called.
33205*/
33206static void pcache1TruncateUnsafe(
33207  PCache1 *pCache,
33208  unsigned int iLimit
33209){
33210  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
33211  unsigned int h;
33212  assert( sqlite3_mutex_held(pcache1.mutex) );
33213  for(h=0; h<pCache->nHash; h++){
33214    PgHdr1 **pp = &pCache->apHash[h];
33215    PgHdr1 *pPage;
33216    while( (pPage = *pp)!=0 ){
33217      if( pPage->iKey>=iLimit ){
33218        pCache->nPage--;
33219        *pp = pPage->pNext;
33220        pcache1PinPage(pPage);
33221        pcache1FreePage(pPage);
33222      }else{
33223        pp = &pPage->pNext;
33224        TESTONLY( nPage++; )
33225      }
33226    }
33227  }
33228  assert( pCache->nPage==nPage );
33229}
33230
33231/******************************************************************************/
33232/******** sqlite3_pcache Methods **********************************************/
33233
33234/*
33235** Implementation of the sqlite3_pcache.xInit method.
33236*/
33237static int pcache1Init(void *NotUsed){
33238  UNUSED_PARAMETER(NotUsed);
33239  assert( pcache1.isInit==0 );
33240  memset(&pcache1, 0, sizeof(pcache1));
33241  if( sqlite3GlobalConfig.bCoreMutex ){
33242    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
33243  }
33244  pcache1.isInit = 1;
33245  return SQLITE_OK;
33246}
33247
33248/*
33249** Implementation of the sqlite3_pcache.xShutdown method.
33250** Note that the static mutex allocated in xInit does
33251** not need to be freed.
33252*/
33253static void pcache1Shutdown(void *NotUsed){
33254  UNUSED_PARAMETER(NotUsed);
33255  assert( pcache1.isInit!=0 );
33256  memset(&pcache1, 0, sizeof(pcache1));
33257}
33258
33259/*
33260** Implementation of the sqlite3_pcache.xCreate method.
33261**
33262** Allocate a new cache.
33263*/
33264static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
33265  PCache1 *pCache;
33266
33267  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
33268  if( pCache ){
33269    memset(pCache, 0, sizeof(PCache1));
33270    pCache->szPage = szPage;
33271    pCache->bPurgeable = (bPurgeable ? 1 : 0);
33272    if( bPurgeable ){
33273      pCache->nMin = 10;
33274      pcache1EnterMutex();
33275      pcache1.nMinPage += pCache->nMin;
33276      pcache1LeaveMutex();
33277    }
33278  }
33279  return (sqlite3_pcache *)pCache;
33280}
33281
33282/*
33283** Implementation of the sqlite3_pcache.xCachesize method.
33284**
33285** Configure the cache_size limit for a cache.
33286*/
33287static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
33288  PCache1 *pCache = (PCache1 *)p;
33289  if( pCache->bPurgeable ){
33290    pcache1EnterMutex();
33291    pcache1.nMaxPage += (nMax - pCache->nMax);
33292    pCache->nMax = nMax;
33293    pcache1EnforceMaxPage();
33294    pcache1LeaveMutex();
33295  }
33296}
33297
33298/*
33299** Implementation of the sqlite3_pcache.xPagecount method.
33300*/
33301static int pcache1Pagecount(sqlite3_pcache *p){
33302  int n;
33303  pcache1EnterMutex();
33304  n = ((PCache1 *)p)->nPage;
33305  pcache1LeaveMutex();
33306  return n;
33307}
33308
33309/*
33310** Implementation of the sqlite3_pcache.xFetch method.
33311**
33312** Fetch a page by key value.
33313**
33314** Whether or not a new page may be allocated by this function depends on
33315** the value of the createFlag argument.  0 means do not allocate a new
33316** page.  1 means allocate a new page if space is easily available.  2
33317** means to try really hard to allocate a new page.
33318**
33319** For a non-purgeable cache (a cache used as the storage for an in-memory
33320** database) there is really no difference between createFlag 1 and 2.  So
33321** the calling function (pcache.c) will never have a createFlag of 1 on
33322** a non-purgable cache.
33323**
33324** There are three different approaches to obtaining space for a page,
33325** depending on the value of parameter createFlag (which may be 0, 1 or 2).
33326**
33327**   1. Regardless of the value of createFlag, the cache is searched for a
33328**      copy of the requested page. If one is found, it is returned.
33329**
33330**   2. If createFlag==0 and the page is not already in the cache, NULL is
33331**      returned.
33332**
33333**   3. If createFlag is 1, and the page is not already in the cache,
33334**      and if either of the following are true, return NULL:
33335**
33336**       (a) the number of pages pinned by the cache is greater than
33337**           PCache1.nMax, or
33338**       (b) the number of pages pinned by the cache is greater than
33339**           the sum of nMax for all purgeable caches, less the sum of
33340**           nMin for all other purgeable caches.
33341**
33342**   4. If none of the first three conditions apply and the cache is marked
33343**      as purgeable, and if one of the following is true:
33344**
33345**       (a) The number of pages allocated for the cache is already
33346**           PCache1.nMax, or
33347**
33348**       (b) The number of pages allocated for all purgeable caches is
33349**           already equal to or greater than the sum of nMax for all
33350**           purgeable caches,
33351**
33352**      then attempt to recycle a page from the LRU list. If it is the right
33353**      size, return the recycled buffer. Otherwise, free the buffer and
33354**      proceed to step 5.
33355**
33356**   5. Otherwise, allocate and return a new page buffer.
33357*/
33358static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
33359  unsigned int nPinned;
33360  PCache1 *pCache = (PCache1 *)p;
33361  PgHdr1 *pPage = 0;
33362
33363  assert( pCache->bPurgeable || createFlag!=1 );
33364  pcache1EnterMutex();
33365  if( createFlag==1 ) sqlite3BeginBenignMalloc();
33366
33367  /* Search the hash table for an existing entry. */
33368  if( pCache->nHash>0 ){
33369    unsigned int h = iKey % pCache->nHash;
33370    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
33371  }
33372
33373  if( pPage || createFlag==0 ){
33374    pcache1PinPage(pPage);
33375    goto fetch_out;
33376  }
33377
33378  /* Step 3 of header comment. */
33379  nPinned = pCache->nPage - pCache->nRecyclable;
33380  if( createFlag==1 && (
33381        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33382     || nPinned>=(pCache->nMax * 9 / 10)
33383  )){
33384    goto fetch_out;
33385  }
33386
33387  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
33388    goto fetch_out;
33389  }
33390
33391  /* Step 4. Try to recycle a page buffer if appropriate. */
33392  if( pCache->bPurgeable && pcache1.pLruTail && (
33393     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
33394  )){
33395    pPage = pcache1.pLruTail;
33396    pcache1RemoveFromHash(pPage);
33397    pcache1PinPage(pPage);
33398    if( pPage->pCache->szPage!=pCache->szPage ){
33399      pcache1FreePage(pPage);
33400      pPage = 0;
33401    }else{
33402      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
33403    }
33404  }
33405
33406  /* Step 5. If a usable page buffer has still not been found,
33407  ** attempt to allocate a new one.
33408  */
33409  if( !pPage ){
33410    pPage = pcache1AllocPage(pCache);
33411  }
33412
33413  if( pPage ){
33414    unsigned int h = iKey % pCache->nHash;
33415    pCache->nPage++;
33416    pPage->iKey = iKey;
33417    pPage->pNext = pCache->apHash[h];
33418    pPage->pCache = pCache;
33419    pPage->pLruPrev = 0;
33420    pPage->pLruNext = 0;
33421    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
33422    pCache->apHash[h] = pPage;
33423  }
33424
33425fetch_out:
33426  if( pPage && iKey>pCache->iMaxKey ){
33427    pCache->iMaxKey = iKey;
33428  }
33429  if( createFlag==1 ) sqlite3EndBenignMalloc();
33430  pcache1LeaveMutex();
33431  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
33432}
33433
33434
33435/*
33436** Implementation of the sqlite3_pcache.xUnpin method.
33437**
33438** Mark a page as unpinned (eligible for asynchronous recycling).
33439*/
33440static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
33441  PCache1 *pCache = (PCache1 *)p;
33442  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33443
33444  assert( pPage->pCache==pCache );
33445  pcache1EnterMutex();
33446
33447  /* It is an error to call this function if the page is already
33448  ** part of the global LRU list.
33449  */
33450  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
33451  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
33452
33453  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
33454    pcache1RemoveFromHash(pPage);
33455    pcache1FreePage(pPage);
33456  }else{
33457    /* Add the page to the global LRU list. Normally, the page is added to
33458    ** the head of the list (last page to be recycled). However, if the
33459    ** reuseUnlikely flag passed to this function is true, the page is added
33460    ** to the tail of the list (first page to be recycled).
33461    */
33462    if( pcache1.pLruHead ){
33463      pcache1.pLruHead->pLruPrev = pPage;
33464      pPage->pLruNext = pcache1.pLruHead;
33465      pcache1.pLruHead = pPage;
33466    }else{
33467      pcache1.pLruTail = pPage;
33468      pcache1.pLruHead = pPage;
33469    }
33470    pCache->nRecyclable++;
33471  }
33472
33473  pcache1LeaveMutex();
33474}
33475
33476/*
33477** Implementation of the sqlite3_pcache.xRekey method.
33478*/
33479static void pcache1Rekey(
33480  sqlite3_pcache *p,
33481  void *pPg,
33482  unsigned int iOld,
33483  unsigned int iNew
33484){
33485  PCache1 *pCache = (PCache1 *)p;
33486  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33487  PgHdr1 **pp;
33488  unsigned int h;
33489  assert( pPage->iKey==iOld );
33490  assert( pPage->pCache==pCache );
33491
33492  pcache1EnterMutex();
33493
33494  h = iOld%pCache->nHash;
33495  pp = &pCache->apHash[h];
33496  while( (*pp)!=pPage ){
33497    pp = &(*pp)->pNext;
33498  }
33499  *pp = pPage->pNext;
33500
33501  h = iNew%pCache->nHash;
33502  pPage->iKey = iNew;
33503  pPage->pNext = pCache->apHash[h];
33504  pCache->apHash[h] = pPage;
33505  if( iNew>pCache->iMaxKey ){
33506    pCache->iMaxKey = iNew;
33507  }
33508
33509  pcache1LeaveMutex();
33510}
33511
33512/*
33513** Implementation of the sqlite3_pcache.xTruncate method.
33514**
33515** Discard all unpinned pages in the cache with a page number equal to
33516** or greater than parameter iLimit. Any pinned pages with a page number
33517** equal to or greater than iLimit are implicitly unpinned.
33518*/
33519static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
33520  PCache1 *pCache = (PCache1 *)p;
33521  pcache1EnterMutex();
33522  if( iLimit<=pCache->iMaxKey ){
33523    pcache1TruncateUnsafe(pCache, iLimit);
33524    pCache->iMaxKey = iLimit-1;
33525  }
33526  pcache1LeaveMutex();
33527}
33528
33529/*
33530** Implementation of the sqlite3_pcache.xDestroy method.
33531**
33532** Destroy a cache allocated using pcache1Create().
33533*/
33534static void pcache1Destroy(sqlite3_pcache *p){
33535  PCache1 *pCache = (PCache1 *)p;
33536  pcache1EnterMutex();
33537  pcache1TruncateUnsafe(pCache, 0);
33538  pcache1.nMaxPage -= pCache->nMax;
33539  pcache1.nMinPage -= pCache->nMin;
33540  pcache1EnforceMaxPage();
33541  pcache1LeaveMutex();
33542  sqlite3_free(pCache->apHash);
33543  sqlite3_free(pCache);
33544}
33545
33546/*
33547** This function is called during initialization (sqlite3_initialize()) to
33548** install the default pluggable cache module, assuming the user has not
33549** already provided an alternative.
33550*/
33551SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
33552  static const sqlite3_pcache_methods defaultMethods = {
33553    0,                       /* pArg */
33554    pcache1Init,             /* xInit */
33555    pcache1Shutdown,         /* xShutdown */
33556    pcache1Create,           /* xCreate */
33557    pcache1Cachesize,        /* xCachesize */
33558    pcache1Pagecount,        /* xPagecount */
33559    pcache1Fetch,            /* xFetch */
33560    pcache1Unpin,            /* xUnpin */
33561    pcache1Rekey,            /* xRekey */
33562    pcache1Truncate,         /* xTruncate */
33563    pcache1Destroy           /* xDestroy */
33564  };
33565  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
33566}
33567
33568#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33569/*
33570** This function is called to free superfluous dynamically allocated memory
33571** held by the pager system. Memory in use by any SQLite pager allocated
33572** by the current thread may be sqlite3_free()ed.
33573**
33574** nReq is the number of bytes of memory required. Once this much has
33575** been released, the function returns. The return value is the total number
33576** of bytes of memory released.
33577*/
33578SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
33579  int nFree = 0;
33580  if( pcache1.pStart==0 ){
33581    PgHdr1 *p;
33582    pcache1EnterMutex();
33583    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
33584      nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
33585      pcache1PinPage(p);
33586      pcache1RemoveFromHash(p);
33587      pcache1FreePage(p);
33588    }
33589    pcache1LeaveMutex();
33590  }
33591  return nFree;
33592}
33593#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33594
33595#ifdef SQLITE_TEST
33596/*
33597** This function is used by test procedures to inspect the internal state
33598** of the global cache.
33599*/
33600SQLITE_PRIVATE void sqlite3PcacheStats(
33601  int *pnCurrent,      /* OUT: Total number of pages cached */
33602  int *pnMax,          /* OUT: Global maximum cache size */
33603  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
33604  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
33605){
33606  PgHdr1 *p;
33607  int nRecyclable = 0;
33608  for(p=pcache1.pLruHead; p; p=p->pLruNext){
33609    nRecyclable++;
33610  }
33611  *pnCurrent = pcache1.nCurrentPage;
33612  *pnMax = pcache1.nMaxPage;
33613  *pnMin = pcache1.nMinPage;
33614  *pnRecyclable = nRecyclable;
33615}
33616#endif
33617
33618/************** End of pcache1.c *********************************************/
33619/************** Begin file rowset.c ******************************************/
33620/*
33621** 2008 December 3
33622**
33623** The author disclaims copyright to this source code.  In place of
33624** a legal notice, here is a blessing:
33625**
33626**    May you do good and not evil.
33627**    May you find forgiveness for yourself and forgive others.
33628**    May you share freely, never taking more than you give.
33629**
33630*************************************************************************
33631**
33632** This module implements an object we call a "RowSet".
33633**
33634** The RowSet object is a collection of rowids.  Rowids
33635** are inserted into the RowSet in an arbitrary order.  Inserts
33636** can be intermixed with tests to see if a given rowid has been
33637** previously inserted into the RowSet.
33638**
33639** After all inserts are finished, it is possible to extract the
33640** elements of the RowSet in sorted order.  Once this extraction
33641** process has started, no new elements may be inserted.
33642**
33643** Hence, the primitive operations for a RowSet are:
33644**
33645**    CREATE
33646**    INSERT
33647**    TEST
33648**    SMALLEST
33649**    DESTROY
33650**
33651** The CREATE and DESTROY primitives are the constructor and destructor,
33652** obviously.  The INSERT primitive adds a new element to the RowSet.
33653** TEST checks to see if an element is already in the RowSet.  SMALLEST
33654** extracts the least value from the RowSet.
33655**
33656** The INSERT primitive might allocate additional memory.  Memory is
33657** allocated in chunks so most INSERTs do no allocation.  There is an
33658** upper bound on the size of allocated memory.  No memory is freed
33659** until DESTROY.
33660**
33661** The TEST primitive includes a "batch" number.  The TEST primitive
33662** will only see elements that were inserted before the last change
33663** in the batch number.  In other words, if an INSERT occurs between
33664** two TESTs where the TESTs have the same batch nubmer, then the
33665** value added by the INSERT will not be visible to the second TEST.
33666** The initial batch number is zero, so if the very first TEST contains
33667** a non-zero batch number, it will see all prior INSERTs.
33668**
33669** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
33670** that is attempted.
33671**
33672** The cost of an INSERT is roughly constant.  (Sometime new memory
33673** has to be allocated on an INSERT.)  The cost of a TEST with a new
33674** batch number is O(NlogN) where N is the number of elements in the RowSet.
33675** The cost of a TEST using the same batch number is O(logN).  The cost
33676** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
33677** primitives are constant time.  The cost of DESTROY is O(N).
33678**
33679** There is an added cost of O(N) when switching between TEST and
33680** SMALLEST primitives.
33681*/
33682
33683
33684/*
33685** Target size for allocation chunks.
33686*/
33687#define ROWSET_ALLOCATION_SIZE 1024
33688
33689/*
33690** The number of rowset entries per allocation chunk.
33691*/
33692#define ROWSET_ENTRY_PER_CHUNK  \
33693                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
33694
33695/*
33696** Each entry in a RowSet is an instance of the following object.
33697*/
33698struct RowSetEntry {
33699  i64 v;                        /* ROWID value for this entry */
33700  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
33701  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
33702};
33703
33704/*
33705** RowSetEntry objects are allocated in large chunks (instances of the
33706** following structure) to reduce memory allocation overhead.  The
33707** chunks are kept on a linked list so that they can be deallocated
33708** when the RowSet is destroyed.
33709*/
33710struct RowSetChunk {
33711  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
33712  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
33713};
33714
33715/*
33716** A RowSet in an instance of the following structure.
33717**
33718** A typedef of this structure if found in sqliteInt.h.
33719*/
33720struct RowSet {
33721  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
33722  sqlite3 *db;                   /* The database connection */
33723  struct RowSetEntry *pEntry;    /* List of entries using pRight */
33724  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
33725  struct RowSetEntry *pFresh;    /* Source of new entry objects */
33726  struct RowSetEntry *pTree;     /* Binary tree of entries */
33727  u16 nFresh;                    /* Number of objects on pFresh */
33728  u8 isSorted;                   /* True if pEntry is sorted */
33729  u8 iBatch;                     /* Current insert batch */
33730};
33731
33732/*
33733** Turn bulk memory into a RowSet object.  N bytes of memory
33734** are available at pSpace.  The db pointer is used as a memory context
33735** for any subsequent allocations that need to occur.
33736** Return a pointer to the new RowSet object.
33737**
33738** It must be the case that N is sufficient to make a Rowset.  If not
33739** an assertion fault occurs.
33740**
33741** If N is larger than the minimum, use the surplus as an initial
33742** allocation of entries available to be filled.
33743*/
33744SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
33745  RowSet *p;
33746  assert( N >= ROUND8(sizeof(*p)) );
33747  p = pSpace;
33748  p->pChunk = 0;
33749  p->db = db;
33750  p->pEntry = 0;
33751  p->pLast = 0;
33752  p->pTree = 0;
33753  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
33754  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
33755  p->isSorted = 1;
33756  p->iBatch = 0;
33757  return p;
33758}
33759
33760/*
33761** Deallocate all chunks from a RowSet.  This frees all memory that
33762** the RowSet has allocated over its lifetime.  This routine is
33763** the destructor for the RowSet.
33764*/
33765SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
33766  struct RowSetChunk *pChunk, *pNextChunk;
33767  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
33768    pNextChunk = pChunk->pNextChunk;
33769    sqlite3DbFree(p->db, pChunk);
33770  }
33771  p->pChunk = 0;
33772  p->nFresh = 0;
33773  p->pEntry = 0;
33774  p->pLast = 0;
33775  p->pTree = 0;
33776  p->isSorted = 1;
33777}
33778
33779/*
33780** Insert a new value into a RowSet.
33781**
33782** The mallocFailed flag of the database connection is set if a
33783** memory allocation fails.
33784*/
33785SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
33786  struct RowSetEntry *pEntry;  /* The new entry */
33787  struct RowSetEntry *pLast;   /* The last prior entry */
33788  assert( p!=0 );
33789  if( p->nFresh==0 ){
33790    struct RowSetChunk *pNew;
33791    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
33792    if( pNew==0 ){
33793      return;
33794    }
33795    pNew->pNextChunk = p->pChunk;
33796    p->pChunk = pNew;
33797    p->pFresh = pNew->aEntry;
33798    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
33799  }
33800  pEntry = p->pFresh++;
33801  p->nFresh--;
33802  pEntry->v = rowid;
33803  pEntry->pRight = 0;
33804  pLast = p->pLast;
33805  if( pLast ){
33806    if( p->isSorted && rowid<=pLast->v ){
33807      p->isSorted = 0;
33808    }
33809    pLast->pRight = pEntry;
33810  }else{
33811    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
33812    p->pEntry = pEntry;
33813  }
33814  p->pLast = pEntry;
33815}
33816
33817/*
33818** Merge two lists of RowSetEntry objects.  Remove duplicates.
33819**
33820** The input lists are connected via pRight pointers and are
33821** assumed to each already be in sorted order.
33822*/
33823static struct RowSetEntry *rowSetMerge(
33824  struct RowSetEntry *pA,    /* First sorted list to be merged */
33825  struct RowSetEntry *pB     /* Second sorted list to be merged */
33826){
33827  struct RowSetEntry head;
33828  struct RowSetEntry *pTail;
33829
33830  pTail = &head;
33831  while( pA && pB ){
33832    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33833    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
33834    if( pA->v<pB->v ){
33835      pTail->pRight = pA;
33836      pA = pA->pRight;
33837      pTail = pTail->pRight;
33838    }else if( pB->v<pA->v ){
33839      pTail->pRight = pB;
33840      pB = pB->pRight;
33841      pTail = pTail->pRight;
33842    }else{
33843      pA = pA->pRight;
33844    }
33845  }
33846  if( pA ){
33847    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
33848    pTail->pRight = pA;
33849  }else{
33850    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
33851    pTail->pRight = pB;
33852  }
33853  return head.pRight;
33854}
33855
33856/*
33857** Sort all elements on the pEntry list of the RowSet into ascending order.
33858*/
33859static void rowSetSort(RowSet *p){
33860  unsigned int i;
33861  struct RowSetEntry *pEntry;
33862  struct RowSetEntry *aBucket[40];
33863
33864  assert( p->isSorted==0 );
33865  memset(aBucket, 0, sizeof(aBucket));
33866  while( p->pEntry ){
33867    pEntry = p->pEntry;
33868    p->pEntry = pEntry->pRight;
33869    pEntry->pRight = 0;
33870    for(i=0; aBucket[i]; i++){
33871      pEntry = rowSetMerge(aBucket[i], pEntry);
33872      aBucket[i] = 0;
33873    }
33874    aBucket[i] = pEntry;
33875  }
33876  pEntry = 0;
33877  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
33878    pEntry = rowSetMerge(pEntry, aBucket[i]);
33879  }
33880  p->pEntry = pEntry;
33881  p->pLast = 0;
33882  p->isSorted = 1;
33883}
33884
33885
33886/*
33887** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
33888** Convert this tree into a linked list connected by the pRight pointers
33889** and return pointers to the first and last elements of the new list.
33890*/
33891static void rowSetTreeToList(
33892  struct RowSetEntry *pIn,         /* Root of the input tree */
33893  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
33894  struct RowSetEntry **ppLast      /* Write tail of the output list here */
33895){
33896  assert( pIn!=0 );
33897  if( pIn->pLeft ){
33898    struct RowSetEntry *p;
33899    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
33900    p->pRight = pIn;
33901  }else{
33902    *ppFirst = pIn;
33903  }
33904  if( pIn->pRight ){
33905    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
33906  }else{
33907    *ppLast = pIn;
33908  }
33909  assert( (*ppLast)->pRight==0 );
33910}
33911
33912
33913/*
33914** Convert a sorted list of elements (connected by pRight) into a binary
33915** tree with depth of iDepth.  A depth of 1 means the tree contains a single
33916** node taken from the head of *ppList.  A depth of 2 means a tree with
33917** three nodes.  And so forth.
33918**
33919** Use as many entries from the input list as required and update the
33920** *ppList to point to the unused elements of the list.  If the input
33921** list contains too few elements, then construct an incomplete tree
33922** and leave *ppList set to NULL.
33923**
33924** Return a pointer to the root of the constructed binary tree.
33925*/
33926static struct RowSetEntry *rowSetNDeepTree(
33927  struct RowSetEntry **ppList,
33928  int iDepth
33929){
33930  struct RowSetEntry *p;         /* Root of the new tree */
33931  struct RowSetEntry *pLeft;     /* Left subtree */
33932  if( *ppList==0 ){
33933    return 0;
33934  }
33935  if( iDepth==1 ){
33936    p = *ppList;
33937    *ppList = p->pRight;
33938    p->pLeft = p->pRight = 0;
33939    return p;
33940  }
33941  pLeft = rowSetNDeepTree(ppList, iDepth-1);
33942  p = *ppList;
33943  if( p==0 ){
33944    return pLeft;
33945  }
33946  p->pLeft = pLeft;
33947  *ppList = p->pRight;
33948  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
33949  return p;
33950}
33951
33952/*
33953** Convert a sorted list of elements into a binary tree. Make the tree
33954** as deep as it needs to be in order to contain the entire list.
33955*/
33956static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
33957  int iDepth;           /* Depth of the tree so far */
33958  struct RowSetEntry *p;       /* Current tree root */
33959  struct RowSetEntry *pLeft;   /* Left subtree */
33960
33961  assert( pList!=0 );
33962  p = pList;
33963  pList = p->pRight;
33964  p->pLeft = p->pRight = 0;
33965  for(iDepth=1; pList; iDepth++){
33966    pLeft = p;
33967    p = pList;
33968    pList = p->pRight;
33969    p->pLeft = pLeft;
33970    p->pRight = rowSetNDeepTree(&pList, iDepth);
33971  }
33972  return p;
33973}
33974
33975/*
33976** Convert the list in p->pEntry into a sorted list if it is not
33977** sorted already.  If there is a binary tree on p->pTree, then
33978** convert it into a list too and merge it into the p->pEntry list.
33979*/
33980static void rowSetToList(RowSet *p){
33981  if( !p->isSorted ){
33982    rowSetSort(p);
33983  }
33984  if( p->pTree ){
33985    struct RowSetEntry *pHead, *pTail;
33986    rowSetTreeToList(p->pTree, &pHead, &pTail);
33987    p->pTree = 0;
33988    p->pEntry = rowSetMerge(p->pEntry, pHead);
33989  }
33990}
33991
33992/*
33993** Extract the smallest element from the RowSet.
33994** Write the element into *pRowid.  Return 1 on success.  Return
33995** 0 if the RowSet is already empty.
33996**
33997** After this routine has been called, the sqlite3RowSetInsert()
33998** routine may not be called again.
33999*/
34000SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
34001  rowSetToList(p);
34002  if( p->pEntry ){
34003    *pRowid = p->pEntry->v;
34004    p->pEntry = p->pEntry->pRight;
34005    if( p->pEntry==0 ){
34006      sqlite3RowSetClear(p);
34007    }
34008    return 1;
34009  }else{
34010    return 0;
34011  }
34012}
34013
34014/*
34015** Check to see if element iRowid was inserted into the the rowset as
34016** part of any insert batch prior to iBatch.  Return 1 or 0.
34017*/
34018SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
34019  struct RowSetEntry *p;
34020  if( iBatch!=pRowSet->iBatch ){
34021    if( pRowSet->pEntry ){
34022      rowSetToList(pRowSet);
34023      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
34024      pRowSet->pEntry = 0;
34025      pRowSet->pLast = 0;
34026    }
34027    pRowSet->iBatch = iBatch;
34028  }
34029  p = pRowSet->pTree;
34030  while( p ){
34031    if( p->v<iRowid ){
34032      p = p->pRight;
34033    }else if( p->v>iRowid ){
34034      p = p->pLeft;
34035    }else{
34036      return 1;
34037    }
34038  }
34039  return 0;
34040}
34041
34042/************** End of rowset.c **********************************************/
34043/************** Begin file pager.c *******************************************/
34044/*
34045** 2001 September 15
34046**
34047** The author disclaims copyright to this source code.  In place of
34048** a legal notice, here is a blessing:
34049**
34050**    May you do good and not evil.
34051**    May you find forgiveness for yourself and forgive others.
34052**    May you share freely, never taking more than you give.
34053**
34054*************************************************************************
34055** This is the implementation of the page cache subsystem or "pager".
34056**
34057** The pager is used to access a database disk file.  It implements
34058** atomic commit and rollback through the use of a journal file that
34059** is separate from the database file.  The pager also implements file
34060** locking to prevent two processes from writing the same database
34061** file simultaneously, or one process from reading the database while
34062** another is writing.
34063*/
34064#ifndef SQLITE_OMIT_DISKIO
34065/************** Include wal.h in the middle of pager.c ***********************/
34066/************** Begin file wal.h *********************************************/
34067/*
34068** 2010 February 1
34069**
34070** The author disclaims copyright to this source code.  In place of
34071** a legal notice, here is a blessing:
34072**
34073**    May you do good and not evil.
34074**    May you find forgiveness for yourself and forgive others.
34075**    May you share freely, never taking more than you give.
34076**
34077*************************************************************************
34078** This header file defines the interface to the write-ahead logging
34079** system. Refer to the comments below and the header comment attached to
34080** the implementation of each function in log.c for further details.
34081*/
34082
34083#ifndef _WAL_H_
34084#define _WAL_H_
34085
34086
34087#ifdef SQLITE_OMIT_WAL
34088# define sqlite3WalOpen(x,y,z)                 0
34089# define sqlite3WalClose(w,x,y,z)              0
34090# define sqlite3WalBeginReadTransaction(y,z)   0
34091# define sqlite3WalEndReadTransaction(z)
34092# define sqlite3WalRead(v,w,x,y,z)             0
34093# define sqlite3WalDbsize(y)                   0
34094# define sqlite3WalBeginWriteTransaction(y)    0
34095# define sqlite3WalEndWriteTransaction(x)      0
34096# define sqlite3WalUndo(x,y,z)                 0
34097# define sqlite3WalSavepoint(y,z)
34098# define sqlite3WalSavepointUndo(y,z)          0
34099# define sqlite3WalFrames(u,v,w,x,y,z)         0
34100# define sqlite3WalCheckpoint(u,v,w,x)         0
34101# define sqlite3WalCallback(z)                 0
34102# define sqlite3WalExclusiveMode(y,z)          0
34103#else
34104
34105#define WAL_SAVEPOINT_NDATA 4
34106
34107/* Connection to a write-ahead log (WAL) file.
34108** There is one object of this type for each pager.
34109*/
34110typedef struct Wal Wal;
34111
34112/* Open and close a connection to a write-ahead log. */
34113SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, Wal**);
34114SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
34115
34116/* Used by readers to open (lock) and close (unlock) a snapshot.  A
34117** snapshot is like a read-transaction.  It is the state of the database
34118** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
34119** preserves the current state even if the other threads or processes
34120** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
34121** transaction and releases the lock.
34122*/
34123SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
34124SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
34125
34126/* Read a page from the write-ahead log, if it is present. */
34127SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
34128
34129/* If the WAL is not empty, return the size of the database. */
34130SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
34131
34132/* Obtain or release the WRITER lock. */
34133SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
34134SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
34135
34136/* Undo any frames written (but not committed) to the log */
34137SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
34138
34139/* Return an integer that records the current (uncommitted) write
34140** position in the WAL */
34141SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
34142
34143/* Move the write position of the WAL back to iFrame.  Called in
34144** response to a ROLLBACK TO command. */
34145SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
34146
34147/* Write a frame or frames to the log. */
34148SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
34149
34150/* Copy pages from the log to the database file */
34151SQLITE_PRIVATE int sqlite3WalCheckpoint(
34152  Wal *pWal,                      /* Write-ahead log connection */
34153  int sync_flags,                 /* Flags to sync db file with (or 0) */
34154  int nBuf,                       /* Size of buffer nBuf */
34155  u8 *zBuf                        /* Temporary buffer to use */
34156);
34157
34158/* Return the value to pass to a sqlite3_wal_hook callback, the
34159** number of frames in the WAL at the point of the last commit since
34160** sqlite3WalCallback() was called.  If no commits have occurred since
34161** the last call, then return 0.
34162*/
34163SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
34164
34165/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
34166** by the pager layer on the database file.
34167*/
34168SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
34169
34170#endif /* ifndef SQLITE_OMIT_WAL */
34171#endif /* _WAL_H_ */
34172
34173/************** End of wal.h *************************************************/
34174/************** Continuing where we left off in pager.c **********************/
34175
34176
34177/******************* NOTES ON THE DESIGN OF THE PAGER ************************
34178**
34179** This comment block describes invariants that hold when using a rollback
34180** journal.  These invariants do not apply for journal_mode=WAL,
34181** journal_mode=MEMORY, or journal_mode=OFF.
34182**
34183** Within this comment block, a page is deemed to have been synced
34184** automatically as soon as it is written when PRAGMA synchronous=OFF.
34185** Otherwise, the page is not synced until the xSync method of the VFS
34186** is called successfully on the file containing the page.
34187**
34188** Definition:  A page of the database file is said to be "overwriteable" if
34189** one or more of the following are true about the page:
34190**
34191**     (a)  The original content of the page as it was at the beginning of
34192**          the transaction has been written into the rollback journal and
34193**          synced.
34194**
34195**     (b)  The page was a freelist leaf page at the start of the transaction.
34196**
34197**     (c)  The page number is greater than the largest page that existed in
34198**          the database file at the start of the transaction.
34199**
34200** (1) A page of the database file is never overwritten unless one of the
34201**     following are true:
34202**
34203**     (a) The page and all other pages on the same sector are overwriteable.
34204**
34205**     (b) The atomic page write optimization is enabled, and the entire
34206**         transaction other than the update of the transaction sequence
34207**         number consists of a single page change.
34208**
34209** (2) The content of a page written into the rollback journal exactly matches
34210**     both the content in the database when the rollback journal was written
34211**     and the content in the database at the beginning of the current
34212**     transaction.
34213**
34214** (3) Writes to the database file are an integer multiple of the page size
34215**     in length and are aligned on a page boundary.
34216**
34217** (4) Reads from the database file are either aligned on a page boundary and
34218**     an integer multiple of the page size in length or are taken from the
34219**     first 100 bytes of the database file.
34220**
34221** (5) All writes to the database file are synced prior to the rollback journal
34222**     being deleted, truncated, or zeroed.
34223**
34224** (6) If a master journal file is used, then all writes to the database file
34225**     are synced prior to the master journal being deleted.
34226**
34227** Definition: Two databases (or the same database at two points it time)
34228** are said to be "logically equivalent" if they give the same answer to
34229** all queries.  Note in particular the the content of freelist leaf
34230** pages can be changed arbitarily without effecting the logical equivalence
34231** of the database.
34232**
34233** (7) At any time, if any subset, including the empty set and the total set,
34234**     of the unsynced changes to a rollback journal are removed and the
34235**     journal is rolled back, the resulting database file will be logical
34236**     equivalent to the database file at the beginning of the transaction.
34237**
34238** (8) When a transaction is rolled back, the xTruncate method of the VFS
34239**     is called to restore the database file to the same size it was at
34240**     the beginning of the transaction.  (In some VFSes, the xTruncate
34241**     method is a no-op, but that does not change the fact the SQLite will
34242**     invoke it.)
34243**
34244** (9) Whenever the database file is modified, at least one bit in the range
34245**     of bytes from 24 through 39 inclusive will be changed prior to releasing
34246**     the EXCLUSIVE lock, thus signaling other connections on the same
34247**     database to flush their caches.
34248**
34249** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
34250**      than one billion transactions.
34251**
34252** (11) A database file is well-formed at the beginning and at the conclusion
34253**      of every transaction.
34254**
34255** (12) An EXCLUSIVE lock is held on the database file when writing to
34256**      the database file.
34257**
34258** (13) A SHARED lock is held on the database file while reading any
34259**      content out of the database file.
34260**
34261******************************************************************************/
34262
34263/*
34264** Macros for troubleshooting.  Normally turned off
34265*/
34266#if 0
34267int sqlite3PagerTrace=1;  /* True to enable tracing */
34268#define sqlite3DebugPrintf printf
34269#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
34270#else
34271#define PAGERTRACE(X)
34272#endif
34273
34274/*
34275** The following two macros are used within the PAGERTRACE() macros above
34276** to print out file-descriptors.
34277**
34278** PAGERID() takes a pointer to a Pager struct as its argument. The
34279** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
34280** struct as its argument.
34281*/
34282#define PAGERID(p) ((int)(p->fd))
34283#define FILEHANDLEID(fd) ((int)fd)
34284
34285/*
34286** The Pager.eState variable stores the current 'state' of a pager. A
34287** pager may be in any one of the seven states shown in the following
34288** state diagram.
34289**
34290**                            OPEN <------+------+
34291**                              |         |      |
34292**                              V         |      |
34293**               +---------> READER-------+      |
34294**               |              |                |
34295**               |              V                |
34296**               |<-------WRITER_LOCKED------> ERROR
34297**               |              |                ^
34298**               |              V                |
34299**               |<------WRITER_CACHEMOD-------->|
34300**               |              |                |
34301**               |              V                |
34302**               |<-------WRITER_DBMOD---------->|
34303**               |              |                |
34304**               |              V                |
34305**               +<------WRITER_FINISHED-------->+
34306**
34307**
34308** List of state transitions and the C [function] that performs each:
34309**
34310**   OPEN              -> READER              [sqlite3PagerSharedLock]
34311**   READER            -> OPEN                [pager_unlock]
34312**
34313**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
34314**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
34315**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
34316**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
34317**   WRITER_***        -> READER              [pager_end_transaction]
34318**
34319**   WRITER_***        -> ERROR               [pager_error]
34320**   ERROR             -> OPEN                [pager_unlock]
34321**
34322**
34323**  OPEN:
34324**
34325**    The pager starts up in this state. Nothing is guaranteed in this
34326**    state - the file may or may not be locked and the database size is
34327**    unknown. The database may not be read or written.
34328**
34329**    * No read or write transaction is active.
34330**    * Any lock, or no lock at all, may be held on the database file.
34331**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
34332**
34333**  READER:
34334**
34335**    In this state all the requirements for reading the database in
34336**    rollback (non-WAL) mode are met. Unless the pager is (or recently
34337**    was) in exclusive-locking mode, a user-level read transaction is
34338**    open. The database size is known in this state.
34339**
34340**    A connection running with locking_mode=normal enters this state when
34341**    it opens a read-transaction on the database and returns to state
34342**    OPEN after the read-transaction is completed. However a connection
34343**    running in locking_mode=exclusive (including temp databases) remains in
34344**    this state even after the read-transaction is closed. The only way
34345**    a locking_mode=exclusive connection can transition from READER to OPEN
34346**    is via the ERROR state (see below).
34347**
34348**    * A read transaction may be active (but a write-transaction cannot).
34349**    * A SHARED or greater lock is held on the database file.
34350**    * The dbSize variable may be trusted (even if a user-level read
34351**      transaction is not active). The dbOrigSize and dbFileSize variables
34352**      may not be trusted at this point.
34353**    * If the database is a WAL database, then the WAL connection is open.
34354**    * Even if a read-transaction is not open, it is guaranteed that
34355**      there is no hot-journal in the file-system.
34356**
34357**  WRITER_LOCKED:
34358**
34359**    The pager moves to this state from READER when a write-transaction
34360**    is first opened on the database. In WRITER_LOCKED state, all locks
34361**    required to start a write-transaction are held, but no actual
34362**    modifications to the cache or database have taken place.
34363**
34364**    In rollback mode, a RESERVED or (if the transaction was opened with
34365**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
34366**    moving to this state, but the journal file is not written to or opened
34367**    to in this state. If the transaction is committed or rolled back while
34368**    in WRITER_LOCKED state, all that is required is to unlock the database
34369**    file.
34370**
34371**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
34372**    If the connection is running with locking_mode=exclusive, an attempt
34373**    is made to obtain an EXCLUSIVE lock on the database file.
34374**
34375**    * A write transaction is active.
34376**    * If the connection is open in rollback-mode, a RESERVED or greater
34377**      lock is held on the database file.
34378**    * If the connection is open in WAL-mode, a WAL write transaction
34379**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
34380**      called).
34381**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
34382**    * The contents of the pager cache have not been modified.
34383**    * The journal file may or may not be open.
34384**    * Nothing (not even the first header) has been written to the journal.
34385**
34386**  WRITER_CACHEMOD:
34387**
34388**    A pager moves from WRITER_LOCKED state to this state when a page is
34389**    first modified by the upper layer. In rollback mode the journal file
34390**    is opened (if it is not already open) and a header written to the
34391**    start of it. The database file on disk has not been modified.
34392**
34393**    * A write transaction is active.
34394**    * A RESERVED or greater lock is held on the database file.
34395**    * The journal file is open and the first header has been written
34396**      to it, but the header has not been synced to disk.
34397**    * The contents of the page cache have been modified.
34398**
34399**  WRITER_DBMOD:
34400**
34401**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
34402**    when it modifies the contents of the database file. WAL connections
34403**    never enter this state (since they do not modify the database file,
34404**    just the log file).
34405**
34406**    * A write transaction is active.
34407**    * An EXCLUSIVE or greater lock is held on the database file.
34408**    * The journal file is open and the first header has been written
34409**      and synced to disk.
34410**    * The contents of the page cache have been modified (and possibly
34411**      written to disk).
34412**
34413**  WRITER_FINISHED:
34414**
34415**    It is not possible for a WAL connection to enter this state.
34416**
34417**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
34418**    state after the entire transaction has been successfully written into the
34419**    database file. In this state the transaction may be committed simply
34420**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
34421**    not possible to modify the database further. At this point, the upper
34422**    layer must either commit or rollback the transaction.
34423**
34424**    * A write transaction is active.
34425**    * An EXCLUSIVE or greater lock is held on the database file.
34426**    * All writing and syncing of journal and database data has finished.
34427**      If no error occured, all that remains is to finalize the journal to
34428**      commit the transaction. If an error did occur, the caller will need
34429**      to rollback the transaction.
34430**
34431**  ERROR:
34432**
34433**    The ERROR state is entered when an IO or disk-full error (including
34434**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
34435**    difficult to be sure that the in-memory pager state (cache contents,
34436**    db size etc.) are consistent with the contents of the file-system.
34437**
34438**    Temporary pager files may enter the ERROR state, but in-memory pagers
34439**    cannot.
34440**
34441**    For example, if an IO error occurs while performing a rollback,
34442**    the contents of the page-cache may be left in an inconsistent state.
34443**    At this point it would be dangerous to change back to READER state
34444**    (as usually happens after a rollback). Any subsequent readers might
34445**    report database corruption (due to the inconsistent cache), and if
34446**    they upgrade to writers, they may inadvertently corrupt the database
34447**    file. To avoid this hazard, the pager switches into the ERROR state
34448**    instead of READER following such an error.
34449**
34450**    Once it has entered the ERROR state, any attempt to use the pager
34451**    to read or write data returns an error. Eventually, once all
34452**    outstanding transactions have been abandoned, the pager is able to
34453**    transition back to OPEN state, discarding the contents of the
34454**    page-cache and any other in-memory state at the same time. Everything
34455**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
34456**    when a read-transaction is next opened on the pager (transitioning
34457**    the pager into READER state). At that point the system has recovered
34458**    from the error.
34459**
34460**    Specifically, the pager jumps into the ERROR state if:
34461**
34462**      1. An error occurs while attempting a rollback. This happens in
34463**         function sqlite3PagerRollback().
34464**
34465**      2. An error occurs while attempting to finalize a journal file
34466**         following a commit in function sqlite3PagerCommitPhaseTwo().
34467**
34468**      3. An error occurs while attempting to write to the journal or
34469**         database file in function pagerStress() in order to free up
34470**         memory.
34471**
34472**    In other cases, the error is returned to the b-tree layer. The b-tree
34473**    layer then attempts a rollback operation. If the error condition
34474**    persists, the pager enters the ERROR state via condition (1) above.
34475**
34476**    Condition (3) is necessary because it can be triggered by a read-only
34477**    statement executed within a transaction. In this case, if the error
34478**    code were simply returned to the user, the b-tree layer would not
34479**    automatically attempt a rollback, as it assumes that an error in a
34480**    read-only statement cannot leave the pager in an internally inconsistent
34481**    state.
34482**
34483**    * The Pager.errCode variable is set to something other than SQLITE_OK.
34484**    * There are one or more outstanding references to pages (after the
34485**      last reference is dropped the pager should move back to OPEN state).
34486**    * The pager is not an in-memory pager.
34487**
34488**
34489** Notes:
34490**
34491**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
34492**     connection is open in WAL mode. A WAL connection is always in one
34493**     of the first four states.
34494**
34495**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
34496**     state. There are two exceptions: immediately after exclusive-mode has
34497**     been turned on (and before any read or write transactions are
34498**     executed), and when the pager is leaving the "error state".
34499**
34500**   * See also: assert_pager_state().
34501*/
34502#define PAGER_OPEN                  0
34503#define PAGER_READER                1
34504#define PAGER_WRITER_LOCKED         2
34505#define PAGER_WRITER_CACHEMOD       3
34506#define PAGER_WRITER_DBMOD          4
34507#define PAGER_WRITER_FINISHED       5
34508#define PAGER_ERROR                 6
34509
34510/*
34511** The Pager.eLock variable is almost always set to one of the
34512** following locking-states, according to the lock currently held on
34513** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
34514** This variable is kept up to date as locks are taken and released by
34515** the pagerLockDb() and pagerUnlockDb() wrappers.
34516**
34517** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
34518** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
34519** the operation was successful. In these circumstances pagerLockDb() and
34520** pagerUnlockDb() take a conservative approach - eLock is always updated
34521** when unlocking the file, and only updated when locking the file if the
34522** VFS call is successful. This way, the Pager.eLock variable may be set
34523** to a less exclusive (lower) value than the lock that is actually held
34524** at the system level, but it is never set to a more exclusive value.
34525**
34526** This is usually safe. If an xUnlock fails or appears to fail, there may
34527** be a few redundant xLock() calls or a lock may be held for longer than
34528** required, but nothing really goes wrong.
34529**
34530** The exception is when the database file is unlocked as the pager moves
34531** from ERROR to OPEN state. At this point there may be a hot-journal file
34532** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
34533** transition, by the same pager or any other). If the call to xUnlock()
34534** fails at this point and the pager is left holding an EXCLUSIVE lock, this
34535** can confuse the call to xCheckReservedLock() call made later as part
34536** of hot-journal detection.
34537**
34538** xCheckReservedLock() is defined as returning true "if there is a RESERVED
34539** lock held by this process or any others". So xCheckReservedLock may
34540** return true because the caller itself is holding an EXCLUSIVE lock (but
34541** doesn't know it because of a previous error in xUnlock). If this happens
34542** a hot-journal may be mistaken for a journal being created by an active
34543** transaction in another process, causing SQLite to read from the database
34544** without rolling it back.
34545**
34546** To work around this, if a call to xUnlock() fails when unlocking the
34547** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
34548** is only changed back to a real locking state after a successful call
34549** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
34550** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
34551** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
34552** lock on the database file before attempting to roll it back. See function
34553** PagerSharedLock() for more detail.
34554**
34555** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
34556** PAGER_OPEN state.
34557*/
34558#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
34559
34560/*
34561** A macro used for invoking the codec if there is one
34562*/
34563#ifdef SQLITE_HAS_CODEC
34564# define CODEC1(P,D,N,X,E) \
34565    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
34566# define CODEC2(P,D,N,X,E,O) \
34567    if( P->xCodec==0 ){ O=(char*)D; }else \
34568    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
34569#else
34570# define CODEC1(P,D,N,X,E)   /* NO-OP */
34571# define CODEC2(P,D,N,X,E,O) O=(char*)D
34572#endif
34573
34574/*
34575** The maximum allowed sector size. 64KiB. If the xSectorsize() method
34576** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
34577** This could conceivably cause corruption following a power failure on
34578** such a system. This is currently an undocumented limit.
34579*/
34580#define MAX_SECTOR_SIZE 0x10000
34581
34582/*
34583** An instance of the following structure is allocated for each active
34584** savepoint and statement transaction in the system. All such structures
34585** are stored in the Pager.aSavepoint[] array, which is allocated and
34586** resized using sqlite3Realloc().
34587**
34588** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
34589** set to 0. If a journal-header is written into the main journal while
34590** the savepoint is active, then iHdrOffset is set to the byte offset
34591** immediately following the last journal record written into the main
34592** journal before the journal-header. This is required during savepoint
34593** rollback (see pagerPlaybackSavepoint()).
34594*/
34595typedef struct PagerSavepoint PagerSavepoint;
34596struct PagerSavepoint {
34597  i64 iOffset;                 /* Starting offset in main journal */
34598  i64 iHdrOffset;              /* See above */
34599  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
34600  Pgno nOrig;                  /* Original number of pages in file */
34601  Pgno iSubRec;                /* Index of first record in sub-journal */
34602#ifndef SQLITE_OMIT_WAL
34603  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
34604#endif
34605};
34606
34607/*
34608** A open page cache is an instance of struct Pager. A description of
34609** some of the more important member variables follows:
34610**
34611** eState
34612**
34613**   The current 'state' of the pager object. See the comment and state
34614**   diagram above for a description of the pager state.
34615**
34616** eLock
34617**
34618**   For a real on-disk database, the current lock held on the database file -
34619**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
34620**
34621**   For a temporary or in-memory database (neither of which require any
34622**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
34623**   databases always have Pager.exclusiveMode==1, this tricks the pager
34624**   logic into thinking that it already has all the locks it will ever
34625**   need (and no reason to release them).
34626**
34627**   In some (obscure) circumstances, this variable may also be set to
34628**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
34629**   details.
34630**
34631** changeCountDone
34632**
34633**   This boolean variable is used to make sure that the change-counter
34634**   (the 4-byte header field at byte offset 24 of the database file) is
34635**   not updated more often than necessary.
34636**
34637**   It is set to true when the change-counter field is updated, which
34638**   can only happen if an exclusive lock is held on the database file.
34639**   It is cleared (set to false) whenever an exclusive lock is
34640**   relinquished on the database file. Each time a transaction is committed,
34641**   The changeCountDone flag is inspected. If it is true, the work of
34642**   updating the change-counter is omitted for the current transaction.
34643**
34644**   This mechanism means that when running in exclusive mode, a connection
34645**   need only update the change-counter once, for the first transaction
34646**   committed.
34647**
34648** setMaster
34649**
34650**   When PagerCommitPhaseOne() is called to commit a transaction, it may
34651**   (or may not) specify a master-journal name to be written into the
34652**   journal file before it is synced to disk.
34653**
34654**   Whether or not a journal file contains a master-journal pointer affects
34655**   the way in which the journal file is finalized after the transaction is
34656**   committed or rolled back when running in "journal_mode=PERSIST" mode.
34657**   If a journal file does not contain a master-journal pointer, it is
34658**   finalized by overwriting the first journal header with zeroes. If
34659**   it does contain a master-journal pointer the journal file is finalized
34660**   by truncating it to zero bytes, just as if the connection were
34661**   running in "journal_mode=truncate" mode.
34662**
34663**   Journal files that contain master journal pointers cannot be finalized
34664**   simply by overwriting the first journal-header with zeroes, as the
34665**   master journal pointer could interfere with hot-journal rollback of any
34666**   subsequently interrupted transaction that reuses the journal file.
34667**
34668**   The flag is cleared as soon as the journal file is finalized (either
34669**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
34670**   journal file from being successfully finalized, the setMaster flag
34671**   is cleared anyway (and the pager will move to ERROR state).
34672**
34673** doNotSpill, doNotSyncSpill
34674**
34675**   These two boolean variables control the behaviour of cache-spills
34676**   (calls made by the pcache module to the pagerStress() routine to
34677**   write cached data to the file-system in order to free up memory).
34678**
34679**   When doNotSpill is non-zero, writing to the database from pagerStress()
34680**   is disabled altogether. This is done in a very obscure case that
34681**   comes up during savepoint rollback that requires the pcache module
34682**   to allocate a new page to prevent the journal file from being written
34683**   while it is being traversed by code in pager_playback().
34684**
34685**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
34686**   is permitted, but syncing the journal file is not. This flag is set
34687**   by sqlite3PagerWrite() when the file-system sector-size is larger than
34688**   the database page-size in order to prevent a journal sync from happening
34689**   in between the journalling of two pages on the same sector.
34690**
34691** subjInMemory
34692**
34693**   This is a boolean variable. If true, then any required sub-journal
34694**   is opened as an in-memory journal file. If false, then in-memory
34695**   sub-journals are only used for in-memory pager files.
34696**
34697**   This variable is updated by the upper layer each time a new
34698**   write-transaction is opened.
34699**
34700** dbSize, dbOrigSize, dbFileSize
34701**
34702**   Variable dbSize is set to the number of pages in the database file.
34703**   It is valid in PAGER_READER and higher states (all states except for
34704**   OPEN and ERROR).
34705**
34706**   dbSize is set based on the size of the database file, which may be
34707**   larger than the size of the database (the value stored at offset
34708**   28 of the database header by the btree). If the size of the file
34709**   is not an integer multiple of the page-size, the value stored in
34710**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
34711**   Except, any file that is greater than 0 bytes in size is considered
34712**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
34713**   to dbSize==1).
34714**
34715**   During a write-transaction, if pages with page-numbers greater than
34716**   dbSize are modified in the cache, dbSize is updated accordingly.
34717**   Similarly, if the database is truncated using PagerTruncateImage(),
34718**   dbSize is updated.
34719**
34720**   Variables dbOrigSize and dbFileSize are valid in states
34721**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
34722**   variable at the start of the transaction. It is used during rollback,
34723**   and to determine whether or not pages need to be journalled before
34724**   being modified.
34725**
34726**   Throughout a write-transaction, dbFileSize contains the size of
34727**   the file on disk in pages. It is set to a copy of dbSize when the
34728**   write-transaction is first opened, and updated when VFS calls are made
34729**   to write or truncate the database file on disk.
34730**
34731**   The only reason the dbFileSize variable is required is to suppress
34732**   unnecessary calls to xTruncate() after committing a transaction. If,
34733**   when a transaction is committed, the dbFileSize variable indicates
34734**   that the database file is larger than the database image (Pager.dbSize),
34735**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
34736**   to measure the database file on disk, and then truncates it if required.
34737**   dbFileSize is not used when rolling back a transaction. In this case
34738**   pager_truncate() is called unconditionally (which means there may be
34739**   a call to xFilesize() that is not strictly required). In either case,
34740**   pager_truncate() may cause the file to become smaller or larger.
34741**
34742** dbHintSize
34743**
34744**   The dbHintSize variable is used to limit the number of calls made to
34745**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
34746**
34747**   dbHintSize is set to a copy of the dbSize variable when a
34748**   write-transaction is opened (at the same time as dbFileSize and
34749**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
34750**   dbHintSize is increased to the number of pages that correspond to the
34751**   size-hint passed to the method call. See pager_write_pagelist() for
34752**   details.
34753**
34754** errCode
34755**
34756**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
34757**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
34758**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
34759**   sub-codes.
34760*/
34761struct Pager {
34762  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
34763  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
34764  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
34765  u8 useJournal;              /* Use a rollback journal on this file */
34766  u8 noReadlock;              /* Do not bother to obtain readlocks */
34767  u8 noSync;                  /* Do not sync the journal if true */
34768  u8 fullSync;                /* Do extra syncs of the journal for robustness */
34769  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
34770  u8 tempFile;                /* zFilename is a temporary file */
34771  u8 readOnly;                /* True for a read-only database */
34772  u8 memDb;                   /* True to inhibit all file I/O */
34773
34774  /**************************************************************************
34775  ** The following block contains those class members that change during
34776  ** routine opertion.  Class members not in this block are either fixed
34777  ** when the pager is first created or else only change when there is a
34778  ** significant mode change (such as changing the page_size, locking_mode,
34779  ** or the journal_mode).  From another view, these class members describe
34780  ** the "state" of the pager, while other class members describe the
34781  ** "configuration" of the pager.
34782  */
34783  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
34784  u8 eLock;                   /* Current lock held on database file */
34785  u8 changeCountDone;         /* Set after incrementing the change-counter */
34786  u8 setMaster;               /* True if a m-j name has been written to jrnl */
34787  u8 doNotSpill;              /* Do not spill the cache when non-zero */
34788  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
34789  u8 subjInMemory;            /* True to use in-memory sub-journals */
34790  Pgno dbSize;                /* Number of pages in the database */
34791  Pgno dbOrigSize;            /* dbSize before the current transaction */
34792  Pgno dbFileSize;            /* Number of pages in the database file */
34793  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
34794  int errCode;                /* One of several kinds of errors */
34795  int nRec;                   /* Pages journalled since last j-header written */
34796  u32 cksumInit;              /* Quasi-random value added to every checksum */
34797  u32 nSubRec;                /* Number of records written to sub-journal */
34798  Bitvec *pInJournal;         /* One bit for each page in the database file */
34799  sqlite3_file *fd;           /* File descriptor for database */
34800  sqlite3_file *jfd;          /* File descriptor for main journal */
34801  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
34802  i64 journalOff;             /* Current write offset in the journal file */
34803  i64 journalHdr;             /* Byte offset to previous journal header */
34804  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
34805  PagerSavepoint *aSavepoint; /* Array of active savepoints */
34806  int nSavepoint;             /* Number of elements in aSavepoint[] */
34807  char dbFileVers[16];        /* Changes whenever database file changes */
34808  /*
34809  ** End of the routinely-changing class members
34810  ***************************************************************************/
34811
34812  u16 nExtra;                 /* Add this many bytes to each in-memory page */
34813  i16 nReserve;               /* Number of unused bytes at end of each page */
34814  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
34815  u32 sectorSize;             /* Assumed sector size during rollback */
34816  int pageSize;               /* Number of bytes in a page */
34817  Pgno mxPgno;                /* Maximum allowed size of the database */
34818  i64 journalSizeLimit;       /* Size limit for persistent journal files */
34819  char *zFilename;            /* Name of the database file */
34820  char *zJournal;             /* Name of the journal file */
34821  int (*xBusyHandler)(void*); /* Function to call when busy */
34822  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
34823#ifdef SQLITE_TEST
34824  int nHit, nMiss;            /* Cache hits and missing */
34825  int nRead, nWrite;          /* Database pages read/written */
34826#endif
34827  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
34828#ifdef SQLITE_HAS_CODEC
34829  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
34830  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
34831  void (*xCodecFree)(void*);             /* Destructor for the codec */
34832  void *pCodec;               /* First argument to xCodec... methods */
34833#endif
34834  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
34835  PCache *pPCache;            /* Pointer to page cache object */
34836#ifndef SQLITE_OMIT_WAL
34837  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
34838  char *zWal;                 /* File name for write-ahead log */
34839#endif
34840};
34841
34842/*
34843** The following global variables hold counters used for
34844** testing purposes only.  These variables do not exist in
34845** a non-testing build.  These variables are not thread-safe.
34846*/
34847#ifdef SQLITE_TEST
34848SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
34849SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
34850SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
34851# define PAGER_INCR(v)  v++
34852#else
34853# define PAGER_INCR(v)
34854#endif
34855
34856
34857
34858/*
34859** Journal files begin with the following magic string.  The data
34860** was obtained from /dev/random.  It is used only as a sanity check.
34861**
34862** Since version 2.8.0, the journal format contains additional sanity
34863** checking information.  If the power fails while the journal is being
34864** written, semi-random garbage data might appear in the journal
34865** file after power is restored.  If an attempt is then made
34866** to roll the journal back, the database could be corrupted.  The additional
34867** sanity checking data is an attempt to discover the garbage in the
34868** journal and ignore it.
34869**
34870** The sanity checking information for the new journal format consists
34871** of a 32-bit checksum on each page of data.  The checksum covers both
34872** the page number and the pPager->pageSize bytes of data for the page.
34873** This cksum is initialized to a 32-bit random value that appears in the
34874** journal file right after the header.  The random initializer is important,
34875** because garbage data that appears at the end of a journal is likely
34876** data that was once in other files that have now been deleted.  If the
34877** garbage data came from an obsolete journal file, the checksums might
34878** be correct.  But by initializing the checksum to random value which
34879** is different for every journal, we minimize that risk.
34880*/
34881static const unsigned char aJournalMagic[] = {
34882  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
34883};
34884
34885/*
34886** The size of the of each page record in the journal is given by
34887** the following macro.
34888*/
34889#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
34890
34891/*
34892** The journal header size for this pager. This is usually the same
34893** size as a single disk sector. See also setSectorSize().
34894*/
34895#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
34896
34897/*
34898** The macro MEMDB is true if we are dealing with an in-memory database.
34899** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
34900** the value of MEMDB will be a constant and the compiler will optimize
34901** out code that would never execute.
34902*/
34903#ifdef SQLITE_OMIT_MEMORYDB
34904# define MEMDB 0
34905#else
34906# define MEMDB pPager->memDb
34907#endif
34908
34909/*
34910** The maximum legal page number is (2^31 - 1).
34911*/
34912#define PAGER_MAX_PGNO 2147483647
34913
34914/*
34915** The argument to this macro is a file descriptor (type sqlite3_file*).
34916** Return 0 if it is not open, or non-zero (but not 1) if it is.
34917**
34918** This is so that expressions can be written as:
34919**
34920**   if( isOpen(pPager->jfd) ){ ...
34921**
34922** instead of
34923**
34924**   if( pPager->jfd->pMethods ){ ...
34925*/
34926#define isOpen(pFd) ((pFd)->pMethods)
34927
34928/*
34929** Return true if this pager uses a write-ahead log instead of the usual
34930** rollback journal. Otherwise false.
34931*/
34932#ifndef SQLITE_OMIT_WAL
34933static int pagerUseWal(Pager *pPager){
34934  return (pPager->pWal!=0);
34935}
34936#else
34937# define pagerUseWal(x) 0
34938# define pagerRollbackWal(x) 0
34939# define pagerWalFrames(v,w,x,y,z) 0
34940# define pagerOpenWalIfPresent(z) SQLITE_OK
34941# define pagerBeginReadTransaction(z) SQLITE_OK
34942#endif
34943
34944#ifndef NDEBUG
34945/*
34946** Usage:
34947**
34948**   assert( assert_pager_state(pPager) );
34949**
34950** This function runs many asserts to try to find inconsistencies in
34951** the internal state of the Pager object.
34952*/
34953static int assert_pager_state(Pager *p){
34954  Pager *pPager = p;
34955
34956  /* State must be valid. */
34957  assert( p->eState==PAGER_OPEN
34958       || p->eState==PAGER_READER
34959       || p->eState==PAGER_WRITER_LOCKED
34960       || p->eState==PAGER_WRITER_CACHEMOD
34961       || p->eState==PAGER_WRITER_DBMOD
34962       || p->eState==PAGER_WRITER_FINISHED
34963       || p->eState==PAGER_ERROR
34964  );
34965
34966  /* Regardless of the current state, a temp-file connection always behaves
34967  ** as if it has an exclusive lock on the database file. It never updates
34968  ** the change-counter field, so the changeCountDone flag is always set.
34969  */
34970  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
34971  assert( p->tempFile==0 || pPager->changeCountDone );
34972
34973  /* If the useJournal flag is clear, the journal-mode must be "OFF".
34974  ** And if the journal-mode is "OFF", the journal file must not be open.
34975  */
34976  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
34977  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
34978
34979  /* Check that MEMDB implies noSync. And an in-memory journal. Since
34980  ** this means an in-memory pager performs no IO at all, it cannot encounter
34981  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
34982  ** a journal file. (although the in-memory journal implementation may
34983  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
34984  ** is therefore not possible for an in-memory pager to enter the ERROR
34985  ** state.
34986  */
34987  if( MEMDB ){
34988    assert( p->noSync );
34989    assert( p->journalMode==PAGER_JOURNALMODE_OFF
34990         || p->journalMode==PAGER_JOURNALMODE_MEMORY
34991    );
34992    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
34993    assert( pagerUseWal(p)==0 );
34994  }
34995
34996  /* If changeCountDone is set, a RESERVED lock or greater must be held
34997  ** on the file.
34998  */
34999  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
35000  assert( p->eLock!=PENDING_LOCK );
35001
35002  switch( p->eState ){
35003    case PAGER_OPEN:
35004      assert( !MEMDB );
35005      assert( pPager->errCode==SQLITE_OK );
35006      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
35007      break;
35008
35009    case PAGER_READER:
35010      assert( pPager->errCode==SQLITE_OK );
35011      assert( p->eLock!=UNKNOWN_LOCK );
35012      assert( p->eLock>=SHARED_LOCK || p->noReadlock );
35013      break;
35014
35015    case PAGER_WRITER_LOCKED:
35016      assert( p->eLock!=UNKNOWN_LOCK );
35017      assert( pPager->errCode==SQLITE_OK );
35018      if( !pagerUseWal(pPager) ){
35019        assert( p->eLock>=RESERVED_LOCK );
35020      }
35021      assert( pPager->dbSize==pPager->dbOrigSize );
35022      assert( pPager->dbOrigSize==pPager->dbFileSize );
35023      assert( pPager->dbOrigSize==pPager->dbHintSize );
35024      assert( pPager->setMaster==0 );
35025      break;
35026
35027    case PAGER_WRITER_CACHEMOD:
35028      assert( p->eLock!=UNKNOWN_LOCK );
35029      assert( pPager->errCode==SQLITE_OK );
35030      if( !pagerUseWal(pPager) ){
35031        /* It is possible that if journal_mode=wal here that neither the
35032        ** journal file nor the WAL file are open. This happens during
35033        ** a rollback transaction that switches from journal_mode=off
35034        ** to journal_mode=wal.
35035        */
35036        assert( p->eLock>=RESERVED_LOCK );
35037        assert( isOpen(p->jfd)
35038             || p->journalMode==PAGER_JOURNALMODE_OFF
35039             || p->journalMode==PAGER_JOURNALMODE_WAL
35040        );
35041      }
35042      assert( pPager->dbOrigSize==pPager->dbFileSize );
35043      assert( pPager->dbOrigSize==pPager->dbHintSize );
35044      break;
35045
35046    case PAGER_WRITER_DBMOD:
35047      assert( p->eLock==EXCLUSIVE_LOCK );
35048      assert( pPager->errCode==SQLITE_OK );
35049      assert( !pagerUseWal(pPager) );
35050      assert( p->eLock>=EXCLUSIVE_LOCK );
35051      assert( isOpen(p->jfd)
35052           || p->journalMode==PAGER_JOURNALMODE_OFF
35053           || p->journalMode==PAGER_JOURNALMODE_WAL
35054      );
35055      assert( pPager->dbOrigSize<=pPager->dbHintSize );
35056      break;
35057
35058    case PAGER_WRITER_FINISHED:
35059      assert( p->eLock==EXCLUSIVE_LOCK );
35060      assert( pPager->errCode==SQLITE_OK );
35061      assert( !pagerUseWal(pPager) );
35062      assert( isOpen(p->jfd)
35063           || p->journalMode==PAGER_JOURNALMODE_OFF
35064           || p->journalMode==PAGER_JOURNALMODE_WAL
35065      );
35066      break;
35067
35068    case PAGER_ERROR:
35069      /* There must be at least one outstanding reference to the pager if
35070      ** in ERROR state. Otherwise the pager should have already dropped
35071      ** back to OPEN state.
35072      */
35073      assert( pPager->errCode!=SQLITE_OK );
35074      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
35075      break;
35076  }
35077
35078  return 1;
35079}
35080
35081/*
35082** Return a pointer to a human readable string in a static buffer
35083** containing the state of the Pager object passed as an argument. This
35084** is intended to be used within debuggers. For example, as an alternative
35085** to "print *pPager" in gdb:
35086**
35087** (gdb) printf "%s", print_pager_state(pPager)
35088*/
35089static char *print_pager_state(Pager *p){
35090  static char zRet[1024];
35091
35092  sqlite3_snprintf(1024, zRet,
35093      "Filename:      %s\n"
35094      "State:         %s errCode=%d\n"
35095      "Lock:          %s\n"
35096      "Locking mode:  locking_mode=%s\n"
35097      "Journal mode:  journal_mode=%s\n"
35098      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
35099      "Journal:       journalOff=%lld journalHdr=%lld\n"
35100      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
35101      , p->zFilename
35102      , p->eState==PAGER_OPEN            ? "OPEN" :
35103        p->eState==PAGER_READER          ? "READER" :
35104        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
35105        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
35106        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
35107        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
35108        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
35109      , (int)p->errCode
35110      , p->eLock==NO_LOCK         ? "NO_LOCK" :
35111        p->eLock==RESERVED_LOCK   ? "RESERVED" :
35112        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
35113        p->eLock==SHARED_LOCK     ? "SHARED" :
35114        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
35115      , p->exclusiveMode ? "exclusive" : "normal"
35116      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
35117        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
35118        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
35119        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
35120        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
35121        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
35122      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
35123      , p->journalOff, p->journalHdr
35124      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
35125  );
35126
35127  return zRet;
35128}
35129#endif
35130
35131/*
35132** Return true if it is necessary to write page *pPg into the sub-journal.
35133** A page needs to be written into the sub-journal if there exists one
35134** or more open savepoints for which:
35135**
35136**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
35137**   * The bit corresponding to the page-number is not set in
35138**     PagerSavepoint.pInSavepoint.
35139*/
35140static int subjRequiresPage(PgHdr *pPg){
35141  Pgno pgno = pPg->pgno;
35142  Pager *pPager = pPg->pPager;
35143  int i;
35144  for(i=0; i<pPager->nSavepoint; i++){
35145    PagerSavepoint *p = &pPager->aSavepoint[i];
35146    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
35147      return 1;
35148    }
35149  }
35150  return 0;
35151}
35152
35153/*
35154** Return true if the page is already in the journal file.
35155*/
35156static int pageInJournal(PgHdr *pPg){
35157  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
35158}
35159
35160/*
35161** Read a 32-bit integer from the given file descriptor.  Store the integer
35162** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
35163** error code is something goes wrong.
35164**
35165** All values are stored on disk as big-endian.
35166*/
35167static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
35168  unsigned char ac[4];
35169  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
35170  if( rc==SQLITE_OK ){
35171    *pRes = sqlite3Get4byte(ac);
35172  }
35173  return rc;
35174}
35175
35176/*
35177** Write a 32-bit integer into a string buffer in big-endian byte order.
35178*/
35179#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
35180
35181
35182/*
35183** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
35184** on success or an error code is something goes wrong.
35185*/
35186static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
35187  char ac[4];
35188  put32bits(ac, val);
35189  return sqlite3OsWrite(fd, ac, 4, offset);
35190}
35191
35192/*
35193** Unlock the database file to level eLock, which must be either NO_LOCK
35194** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
35195** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
35196**
35197** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
35198** called, do not modify it. See the comment above the #define of
35199** UNKNOWN_LOCK for an explanation of this.
35200*/
35201static int pagerUnlockDb(Pager *pPager, int eLock){
35202  int rc = SQLITE_OK;
35203
35204  assert( !pPager->exclusiveMode );
35205  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
35206  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
35207  if( isOpen(pPager->fd) ){
35208    assert( pPager->eLock>=eLock );
35209    rc = sqlite3OsUnlock(pPager->fd, eLock);
35210    if( pPager->eLock!=UNKNOWN_LOCK ){
35211      pPager->eLock = (u8)eLock;
35212    }
35213    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
35214  }
35215  return rc;
35216}
35217
35218/*
35219** Lock the database file to level eLock, which must be either SHARED_LOCK,
35220** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
35221** Pager.eLock variable to the new locking state.
35222**
35223** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
35224** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
35225** See the comment above the #define of UNKNOWN_LOCK for an explanation
35226** of this.
35227*/
35228static int pagerLockDb(Pager *pPager, int eLock){
35229  int rc = SQLITE_OK;
35230
35231  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
35232  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
35233    rc = sqlite3OsLock(pPager->fd, eLock);
35234    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
35235      pPager->eLock = (u8)eLock;
35236      IOTRACE(("LOCK %p %d\n", pPager, eLock))
35237    }
35238  }
35239  return rc;
35240}
35241
35242/*
35243** This function determines whether or not the atomic-write optimization
35244** can be used with this pager. The optimization can be used if:
35245**
35246**  (a) the value returned by OsDeviceCharacteristics() indicates that
35247**      a database page may be written atomically, and
35248**  (b) the value returned by OsSectorSize() is less than or equal
35249**      to the page size.
35250**
35251** The optimization is also always enabled for temporary files. It is
35252** an error to call this function if pPager is opened on an in-memory
35253** database.
35254**
35255** If the optimization cannot be used, 0 is returned. If it can be used,
35256** then the value returned is the size of the journal file when it
35257** contains rollback data for exactly one page.
35258*/
35259#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35260static int jrnlBufferSize(Pager *pPager){
35261  assert( !MEMDB );
35262  if( !pPager->tempFile ){
35263    int dc;                           /* Device characteristics */
35264    int nSector;                      /* Sector size */
35265    int szPage;                       /* Page size */
35266
35267    assert( isOpen(pPager->fd) );
35268    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
35269    nSector = pPager->sectorSize;
35270    szPage = pPager->pageSize;
35271
35272    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
35273    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
35274    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
35275      return 0;
35276    }
35277  }
35278
35279  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
35280}
35281#endif
35282
35283/*
35284** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
35285** on the cache using a hash function.  This is used for testing
35286** and debugging only.
35287*/
35288#ifdef SQLITE_CHECK_PAGES
35289/*
35290** Return a 32-bit hash of the page data for pPage.
35291*/
35292static u32 pager_datahash(int nByte, unsigned char *pData){
35293  u32 hash = 0;
35294  int i;
35295  for(i=0; i<nByte; i++){
35296    hash = (hash*1039) + pData[i];
35297  }
35298  return hash;
35299}
35300static u32 pager_pagehash(PgHdr *pPage){
35301  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
35302}
35303static void pager_set_pagehash(PgHdr *pPage){
35304  pPage->pageHash = pager_pagehash(pPage);
35305}
35306
35307/*
35308** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
35309** is defined, and NDEBUG is not defined, an assert() statement checks
35310** that the page is either dirty or still matches the calculated page-hash.
35311*/
35312#define CHECK_PAGE(x) checkPage(x)
35313static void checkPage(PgHdr *pPg){
35314  Pager *pPager = pPg->pPager;
35315  assert( pPager->eState!=PAGER_ERROR );
35316  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
35317}
35318
35319#else
35320#define pager_datahash(X,Y)  0
35321#define pager_pagehash(X)  0
35322#define pager_set_pagehash(X)
35323#define CHECK_PAGE(x)
35324#endif  /* SQLITE_CHECK_PAGES */
35325
35326/*
35327** When this is called the journal file for pager pPager must be open.
35328** This function attempts to read a master journal file name from the
35329** end of the file and, if successful, copies it into memory supplied
35330** by the caller. See comments above writeMasterJournal() for the format
35331** used to store a master journal file name at the end of a journal file.
35332**
35333** zMaster must point to a buffer of at least nMaster bytes allocated by
35334** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
35335** enough space to write the master journal name). If the master journal
35336** name in the journal is longer than nMaster bytes (including a
35337** nul-terminator), then this is handled as if no master journal name
35338** were present in the journal.
35339**
35340** If a master journal file name is present at the end of the journal
35341** file, then it is copied into the buffer pointed to by zMaster. A
35342** nul-terminator byte is appended to the buffer following the master
35343** journal file name.
35344**
35345** If it is determined that no master journal file name is present
35346** zMaster[0] is set to 0 and SQLITE_OK returned.
35347**
35348** If an error occurs while reading from the journal file, an SQLite
35349** error code is returned.
35350*/
35351static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
35352  int rc;                    /* Return code */
35353  u32 len;                   /* Length in bytes of master journal name */
35354  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
35355  u32 cksum;                 /* MJ checksum value read from journal */
35356  u32 u;                     /* Unsigned loop counter */
35357  unsigned char aMagic[8];   /* A buffer to hold the magic header */
35358  zMaster[0] = '\0';
35359
35360  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
35361   || szJ<16
35362   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
35363   || len>=nMaster
35364   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
35365   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
35366   || memcmp(aMagic, aJournalMagic, 8)
35367   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
35368  ){
35369    return rc;
35370  }
35371
35372  /* See if the checksum matches the master journal name */
35373  for(u=0; u<len; u++){
35374    cksum -= zMaster[u];
35375  }
35376  if( cksum ){
35377    /* If the checksum doesn't add up, then one or more of the disk sectors
35378    ** containing the master journal filename is corrupted. This means
35379    ** definitely roll back, so just return SQLITE_OK and report a (nul)
35380    ** master-journal filename.
35381    */
35382    len = 0;
35383  }
35384  zMaster[len] = '\0';
35385
35386  return SQLITE_OK;
35387}
35388
35389/*
35390** Return the offset of the sector boundary at or immediately
35391** following the value in pPager->journalOff, assuming a sector
35392** size of pPager->sectorSize bytes.
35393**
35394** i.e for a sector size of 512:
35395**
35396**   Pager.journalOff          Return value
35397**   ---------------------------------------
35398**   0                         0
35399**   512                       512
35400**   100                       512
35401**   2000                      2048
35402**
35403*/
35404static i64 journalHdrOffset(Pager *pPager){
35405  i64 offset = 0;
35406  i64 c = pPager->journalOff;
35407  if( c ){
35408    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
35409  }
35410  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
35411  assert( offset>=c );
35412  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
35413  return offset;
35414}
35415
35416/*
35417** The journal file must be open when this function is called.
35418**
35419** This function is a no-op if the journal file has not been written to
35420** within the current transaction (i.e. if Pager.journalOff==0).
35421**
35422** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
35423** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
35424** zero the 28-byte header at the start of the journal file. In either case,
35425** if the pager is not in no-sync mode, sync the journal file immediately
35426** after writing or truncating it.
35427**
35428** If Pager.journalSizeLimit is set to a positive, non-zero value, and
35429** following the truncation or zeroing described above the size of the
35430** journal file in bytes is larger than this value, then truncate the
35431** journal file to Pager.journalSizeLimit bytes. The journal file does
35432** not need to be synced following this operation.
35433**
35434** If an IO error occurs, abandon processing and return the IO error code.
35435** Otherwise, return SQLITE_OK.
35436*/
35437static int zeroJournalHdr(Pager *pPager, int doTruncate){
35438  int rc = SQLITE_OK;                               /* Return code */
35439  assert( isOpen(pPager->jfd) );
35440  if( pPager->journalOff ){
35441    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
35442
35443    IOTRACE(("JZEROHDR %p\n", pPager))
35444    if( doTruncate || iLimit==0 ){
35445      rc = sqlite3OsTruncate(pPager->jfd, 0);
35446    }else{
35447      static const char zeroHdr[28] = {0};
35448      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
35449    }
35450    if( rc==SQLITE_OK && !pPager->noSync ){
35451      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
35452    }
35453
35454    /* At this point the transaction is committed but the write lock
35455    ** is still held on the file. If there is a size limit configured for
35456    ** the persistent journal and the journal file currently consumes more
35457    ** space than that limit allows for, truncate it now. There is no need
35458    ** to sync the file following this operation.
35459    */
35460    if( rc==SQLITE_OK && iLimit>0 ){
35461      i64 sz;
35462      rc = sqlite3OsFileSize(pPager->jfd, &sz);
35463      if( rc==SQLITE_OK && sz>iLimit ){
35464        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
35465      }
35466    }
35467  }
35468  return rc;
35469}
35470
35471/*
35472** The journal file must be open when this routine is called. A journal
35473** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
35474** current location.
35475**
35476** The format for the journal header is as follows:
35477** - 8 bytes: Magic identifying journal format.
35478** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
35479** - 4 bytes: Random number used for page hash.
35480** - 4 bytes: Initial database page count.
35481** - 4 bytes: Sector size used by the process that wrote this journal.
35482** - 4 bytes: Database page size.
35483**
35484** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
35485*/
35486static int writeJournalHdr(Pager *pPager){
35487  int rc = SQLITE_OK;                 /* Return code */
35488  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
35489  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
35490  u32 nWrite;                         /* Bytes of header sector written */
35491  int ii;                             /* Loop counter */
35492
35493  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
35494
35495  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
35496    nHeader = JOURNAL_HDR_SZ(pPager);
35497  }
35498
35499  /* If there are active savepoints and any of them were created
35500  ** since the most recent journal header was written, update the
35501  ** PagerSavepoint.iHdrOffset fields now.
35502  */
35503  for(ii=0; ii<pPager->nSavepoint; ii++){
35504    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
35505      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
35506    }
35507  }
35508
35509  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
35510
35511  /*
35512  ** Write the nRec Field - the number of page records that follow this
35513  ** journal header. Normally, zero is written to this value at this time.
35514  ** After the records are added to the journal (and the journal synced,
35515  ** if in full-sync mode), the zero is overwritten with the true number
35516  ** of records (see syncJournal()).
35517  **
35518  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
35519  ** reading the journal this value tells SQLite to assume that the
35520  ** rest of the journal file contains valid page records. This assumption
35521  ** is dangerous, as if a failure occurred whilst writing to the journal
35522  ** file it may contain some garbage data. There are two scenarios
35523  ** where this risk can be ignored:
35524  **
35525  **   * When the pager is in no-sync mode. Corruption can follow a
35526  **     power failure in this case anyway.
35527  **
35528  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
35529  **     that garbage data is never appended to the journal file.
35530  */
35531  assert( isOpen(pPager->fd) || pPager->noSync );
35532  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
35533   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
35534  ){
35535    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
35536    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
35537  }else{
35538    memset(zHeader, 0, sizeof(aJournalMagic)+4);
35539  }
35540
35541  /* The random check-hash initialiser */
35542  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
35543  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
35544  /* The initial database size */
35545  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
35546  /* The assumed sector size for this process */
35547  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
35548
35549  /* The page size */
35550  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
35551
35552  /* Initializing the tail of the buffer is not necessary.  Everything
35553  ** works find if the following memset() is omitted.  But initializing
35554  ** the memory prevents valgrind from complaining, so we are willing to
35555  ** take the performance hit.
35556  */
35557  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
35558         nHeader-(sizeof(aJournalMagic)+20));
35559
35560  /* In theory, it is only necessary to write the 28 bytes that the
35561  ** journal header consumes to the journal file here. Then increment the
35562  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
35563  ** record is written to the following sector (leaving a gap in the file
35564  ** that will be implicitly filled in by the OS).
35565  **
35566  ** However it has been discovered that on some systems this pattern can
35567  ** be significantly slower than contiguously writing data to the file,
35568  ** even if that means explicitly writing data to the block of
35569  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
35570  ** is done.
35571  **
35572  ** The loop is required here in case the sector-size is larger than the
35573  ** database page size. Since the zHeader buffer is only Pager.pageSize
35574  ** bytes in size, more than one call to sqlite3OsWrite() may be required
35575  ** to populate the entire journal header sector.
35576  */
35577  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
35578    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
35579    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
35580    assert( pPager->journalHdr <= pPager->journalOff );
35581    pPager->journalOff += nHeader;
35582  }
35583
35584  return rc;
35585}
35586
35587/*
35588** The journal file must be open when this is called. A journal header file
35589** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
35590** file. The current location in the journal file is given by
35591** pPager->journalOff. See comments above function writeJournalHdr() for
35592** a description of the journal header format.
35593**
35594** If the header is read successfully, *pNRec is set to the number of
35595** page records following this header and *pDbSize is set to the size of the
35596** database before the transaction began, in pages. Also, pPager->cksumInit
35597** is set to the value read from the journal header. SQLITE_OK is returned
35598** in this case.
35599**
35600** If the journal header file appears to be corrupted, SQLITE_DONE is
35601** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
35602** cannot be read from the journal file an error code is returned.
35603*/
35604static int readJournalHdr(
35605  Pager *pPager,               /* Pager object */
35606  int isHot,
35607  i64 journalSize,             /* Size of the open journal file in bytes */
35608  u32 *pNRec,                  /* OUT: Value read from the nRec field */
35609  u32 *pDbSize                 /* OUT: Value of original database size field */
35610){
35611  int rc;                      /* Return code */
35612  unsigned char aMagic[8];     /* A buffer to hold the magic header */
35613  i64 iHdrOff;                 /* Offset of journal header being read */
35614
35615  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
35616
35617  /* Advance Pager.journalOff to the start of the next sector. If the
35618  ** journal file is too small for there to be a header stored at this
35619  ** point, return SQLITE_DONE.
35620  */
35621  pPager->journalOff = journalHdrOffset(pPager);
35622  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
35623    return SQLITE_DONE;
35624  }
35625  iHdrOff = pPager->journalOff;
35626
35627  /* Read in the first 8 bytes of the journal header. If they do not match
35628  ** the  magic string found at the start of each journal header, return
35629  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
35630  ** proceed.
35631  */
35632  if( isHot || iHdrOff!=pPager->journalHdr ){
35633    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
35634    if( rc ){
35635      return rc;
35636    }
35637    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
35638      return SQLITE_DONE;
35639    }
35640  }
35641
35642  /* Read the first three 32-bit fields of the journal header: The nRec
35643  ** field, the checksum-initializer and the database size at the start
35644  ** of the transaction. Return an error code if anything goes wrong.
35645  */
35646  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
35647   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
35648   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
35649  ){
35650    return rc;
35651  }
35652
35653  if( pPager->journalOff==0 ){
35654    u32 iPageSize;               /* Page-size field of journal header */
35655    u32 iSectorSize;             /* Sector-size field of journal header */
35656
35657    /* Read the page-size and sector-size journal header fields. */
35658    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
35659     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
35660    ){
35661      return rc;
35662    }
35663
35664    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
35665    ** journal header to zero. In this case, assume that the Pager.pageSize
35666    ** variable is already set to the correct page size.
35667    */
35668    if( iPageSize==0 ){
35669      iPageSize = pPager->pageSize;
35670    }
35671
35672    /* Check that the values read from the page-size and sector-size fields
35673    ** are within range. To be 'in range', both values need to be a power
35674    ** of two greater than or equal to 512 or 32, and not greater than their
35675    ** respective compile time maximum limits.
35676    */
35677    if( iPageSize<512                  || iSectorSize<32
35678     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
35679     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
35680    ){
35681      /* If the either the page-size or sector-size in the journal-header is
35682      ** invalid, then the process that wrote the journal-header must have
35683      ** crashed before the header was synced. In this case stop reading
35684      ** the journal file here.
35685      */
35686      return SQLITE_DONE;
35687    }
35688
35689    /* Update the page-size to match the value read from the journal.
35690    ** Use a testcase() macro to make sure that malloc failure within
35691    ** PagerSetPagesize() is tested.
35692    */
35693    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
35694    testcase( rc!=SQLITE_OK );
35695
35696    /* Update the assumed sector-size to match the value used by
35697    ** the process that created this journal. If this journal was
35698    ** created by a process other than this one, then this routine
35699    ** is being called from within pager_playback(). The local value
35700    ** of Pager.sectorSize is restored at the end of that routine.
35701    */
35702    pPager->sectorSize = iSectorSize;
35703  }
35704
35705  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
35706  return rc;
35707}
35708
35709
35710/*
35711** Write the supplied master journal name into the journal file for pager
35712** pPager at the current location. The master journal name must be the last
35713** thing written to a journal file. If the pager is in full-sync mode, the
35714** journal file descriptor is advanced to the next sector boundary before
35715** anything is written. The format is:
35716**
35717**   + 4 bytes: PAGER_MJ_PGNO.
35718**   + N bytes: Master journal filename in utf-8.
35719**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
35720**   + 4 bytes: Master journal name checksum.
35721**   + 8 bytes: aJournalMagic[].
35722**
35723** The master journal page checksum is the sum of the bytes in the master
35724** journal name, where each byte is interpreted as a signed 8-bit integer.
35725**
35726** If zMaster is a NULL pointer (occurs for a single database transaction),
35727** this call is a no-op.
35728*/
35729static int writeMasterJournal(Pager *pPager, const char *zMaster){
35730  int rc;                          /* Return code */
35731  int nMaster;                     /* Length of string zMaster */
35732  i64 iHdrOff;                     /* Offset of header in journal file */
35733  i64 jrnlSize;                    /* Size of journal file on disk */
35734  u32 cksum = 0;                   /* Checksum of string zMaster */
35735
35736  assert( pPager->setMaster==0 );
35737  assert( !pagerUseWal(pPager) );
35738
35739  if( !zMaster
35740   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
35741   || pPager->journalMode==PAGER_JOURNALMODE_OFF
35742  ){
35743    return SQLITE_OK;
35744  }
35745  pPager->setMaster = 1;
35746  assert( isOpen(pPager->jfd) );
35747  assert( pPager->journalHdr <= pPager->journalOff );
35748
35749  /* Calculate the length in bytes and the checksum of zMaster */
35750  for(nMaster=0; zMaster[nMaster]; nMaster++){
35751    cksum += zMaster[nMaster];
35752  }
35753
35754  /* If in full-sync mode, advance to the next disk sector before writing
35755  ** the master journal name. This is in case the previous page written to
35756  ** the journal has already been synced.
35757  */
35758  if( pPager->fullSync ){
35759    pPager->journalOff = journalHdrOffset(pPager);
35760  }
35761  iHdrOff = pPager->journalOff;
35762
35763  /* Write the master journal data to the end of the journal file. If
35764  ** an error occurs, return the error code to the caller.
35765  */
35766  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
35767   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
35768   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
35769   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
35770   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
35771  ){
35772    return rc;
35773  }
35774  pPager->journalOff += (nMaster+20);
35775
35776  /* If the pager is in peristent-journal mode, then the physical
35777  ** journal-file may extend past the end of the master-journal name
35778  ** and 8 bytes of magic data just written to the file. This is
35779  ** dangerous because the code to rollback a hot-journal file
35780  ** will not be able to find the master-journal name to determine
35781  ** whether or not the journal is hot.
35782  **
35783  ** Easiest thing to do in this scenario is to truncate the journal
35784  ** file to the required size.
35785  */
35786  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
35787   && jrnlSize>pPager->journalOff
35788  ){
35789    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
35790  }
35791  return rc;
35792}
35793
35794/*
35795** Find a page in the hash table given its page number. Return
35796** a pointer to the page or NULL if the requested page is not
35797** already in memory.
35798*/
35799static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
35800  PgHdr *p;                         /* Return value */
35801
35802  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
35803  ** fail, since no attempt to allocate dynamic memory will be made.
35804  */
35805  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
35806  return p;
35807}
35808
35809/*
35810** Discard the entire contents of the in-memory page-cache.
35811*/
35812static void pager_reset(Pager *pPager){
35813  sqlite3BackupRestart(pPager->pBackup);
35814  sqlite3PcacheClear(pPager->pPCache);
35815}
35816
35817/*
35818** Free all structures in the Pager.aSavepoint[] array and set both
35819** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
35820** if it is open and the pager is not in exclusive mode.
35821*/
35822static void releaseAllSavepoints(Pager *pPager){
35823  int ii;               /* Iterator for looping through Pager.aSavepoint */
35824  for(ii=0; ii<pPager->nSavepoint; ii++){
35825    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
35826  }
35827  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
35828    sqlite3OsClose(pPager->sjfd);
35829  }
35830  sqlite3_free(pPager->aSavepoint);
35831  pPager->aSavepoint = 0;
35832  pPager->nSavepoint = 0;
35833  pPager->nSubRec = 0;
35834}
35835
35836/*
35837** Set the bit number pgno in the PagerSavepoint.pInSavepoint
35838** bitvecs of all open savepoints. Return SQLITE_OK if successful
35839** or SQLITE_NOMEM if a malloc failure occurs.
35840*/
35841static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
35842  int ii;                   /* Loop counter */
35843  int rc = SQLITE_OK;       /* Result code */
35844
35845  for(ii=0; ii<pPager->nSavepoint; ii++){
35846    PagerSavepoint *p = &pPager->aSavepoint[ii];
35847    if( pgno<=p->nOrig ){
35848      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
35849      testcase( rc==SQLITE_NOMEM );
35850      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35851    }
35852  }
35853  return rc;
35854}
35855
35856/*
35857** This function is a no-op if the pager is in exclusive mode and not
35858** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
35859** state.
35860**
35861** If the pager is not in exclusive-access mode, the database file is
35862** completely unlocked. If the file is unlocked and the file-system does
35863** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
35864** closed (if it is open).
35865**
35866** If the pager is in ERROR state when this function is called, the
35867** contents of the pager cache are discarded before switching back to
35868** the OPEN state. Regardless of whether the pager is in exclusive-mode
35869** or not, any journal file left in the file-system will be treated
35870** as a hot-journal and rolled back the next time a read-transaction
35871** is opened (by this or by any other connection).
35872*/
35873static void pager_unlock(Pager *pPager){
35874
35875  assert( pPager->eState==PAGER_READER
35876       || pPager->eState==PAGER_OPEN
35877       || pPager->eState==PAGER_ERROR
35878  );
35879
35880  sqlite3BitvecDestroy(pPager->pInJournal);
35881  pPager->pInJournal = 0;
35882  releaseAllSavepoints(pPager);
35883
35884  if( pagerUseWal(pPager) ){
35885    assert( !isOpen(pPager->jfd) );
35886    sqlite3WalEndReadTransaction(pPager->pWal);
35887    pPager->eState = PAGER_OPEN;
35888  }else if( !pPager->exclusiveMode ){
35889    int rc;                       /* Error code returned by pagerUnlockDb() */
35890    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
35891
35892    /* If the operating system support deletion of open files, then
35893    ** close the journal file when dropping the database lock.  Otherwise
35894    ** another connection with journal_mode=delete might delete the file
35895    ** out from under us.
35896    */
35897    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
35898    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
35899    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
35900    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
35901    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
35902    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
35903    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
35904     || 1!=(pPager->journalMode & 5)
35905    ){
35906      sqlite3OsClose(pPager->jfd);
35907    }
35908
35909    /* If the pager is in the ERROR state and the call to unlock the database
35910    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
35911    ** above the #define for UNKNOWN_LOCK for an explanation of why this
35912    ** is necessary.
35913    */
35914    rc = pagerUnlockDb(pPager, NO_LOCK);
35915    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
35916      pPager->eLock = UNKNOWN_LOCK;
35917    }
35918
35919    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
35920    ** without clearing the error code. This is intentional - the error
35921    ** code is cleared and the cache reset in the block below.
35922    */
35923    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
35924    pPager->changeCountDone = 0;
35925    pPager->eState = PAGER_OPEN;
35926  }
35927
35928  /* If Pager.errCode is set, the contents of the pager cache cannot be
35929  ** trusted. Now that there are no outstanding references to the pager,
35930  ** it can safely move back to PAGER_OPEN state. This happens in both
35931  ** normal and exclusive-locking mode.
35932  */
35933  if( pPager->errCode ){
35934    assert( !MEMDB );
35935    pager_reset(pPager);
35936    pPager->changeCountDone = pPager->tempFile;
35937    pPager->eState = PAGER_OPEN;
35938    pPager->errCode = SQLITE_OK;
35939  }
35940
35941  pPager->journalOff = 0;
35942  pPager->journalHdr = 0;
35943  pPager->setMaster = 0;
35944}
35945
35946/*
35947** This function is called whenever an IOERR or FULL error that requires
35948** the pager to transition into the ERROR state may ahve occurred.
35949** The first argument is a pointer to the pager structure, the second
35950** the error-code about to be returned by a pager API function. The
35951** value returned is a copy of the second argument to this function.
35952**
35953** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
35954** IOERR sub-codes, the pager enters the ERROR state and the error code
35955** is stored in Pager.errCode. While the pager remains in the ERROR state,
35956** all major API calls on the Pager will immediately return Pager.errCode.
35957**
35958** The ERROR state indicates that the contents of the pager-cache
35959** cannot be trusted. This state can be cleared by completely discarding
35960** the contents of the pager-cache. If a transaction was active when
35961** the persistent error occurred, then the rollback journal may need
35962** to be replayed to restore the contents of the database file (as if
35963** it were a hot-journal).
35964*/
35965static int pager_error(Pager *pPager, int rc){
35966  int rc2 = rc & 0xff;
35967  assert( rc==SQLITE_OK || !MEMDB );
35968  assert(
35969       pPager->errCode==SQLITE_FULL ||
35970       pPager->errCode==SQLITE_OK ||
35971       (pPager->errCode & 0xff)==SQLITE_IOERR
35972  );
35973  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
35974    pPager->errCode = rc;
35975    pPager->eState = PAGER_ERROR;
35976  }
35977  return rc;
35978}
35979
35980/*
35981** This routine ends a transaction. A transaction is usually ended by
35982** either a COMMIT or a ROLLBACK operation. This routine may be called
35983** after rollback of a hot-journal, or if an error occurs while opening
35984** the journal file or writing the very first journal-header of a
35985** database transaction.
35986**
35987** This routine is never called in PAGER_ERROR state. If it is called
35988** in PAGER_NONE or PAGER_SHARED state and the lock held is less
35989** exclusive than a RESERVED lock, it is a no-op.
35990**
35991** Otherwise, any active savepoints are released.
35992**
35993** If the journal file is open, then it is "finalized". Once a journal
35994** file has been finalized it is not possible to use it to roll back a
35995** transaction. Nor will it be considered to be a hot-journal by this
35996** or any other database connection. Exactly how a journal is finalized
35997** depends on whether or not the pager is running in exclusive mode and
35998** the current journal-mode (Pager.journalMode value), as follows:
35999**
36000**   journalMode==MEMORY
36001**     Journal file descriptor is simply closed. This destroys an
36002**     in-memory journal.
36003**
36004**   journalMode==TRUNCATE
36005**     Journal file is truncated to zero bytes in size.
36006**
36007**   journalMode==PERSIST
36008**     The first 28 bytes of the journal file are zeroed. This invalidates
36009**     the first journal header in the file, and hence the entire journal
36010**     file. An invalid journal file cannot be rolled back.
36011**
36012**   journalMode==DELETE
36013**     The journal file is closed and deleted using sqlite3OsDelete().
36014**
36015**     If the pager is running in exclusive mode, this method of finalizing
36016**     the journal file is never used. Instead, if the journalMode is
36017**     DELETE and the pager is in exclusive mode, the method described under
36018**     journalMode==PERSIST is used instead.
36019**
36020** After the journal is finalized, the pager moves to PAGER_READER state.
36021** If running in non-exclusive rollback mode, the lock on the file is
36022** downgraded to a SHARED_LOCK.
36023**
36024** SQLITE_OK is returned if no error occurs. If an error occurs during
36025** any of the IO operations to finalize the journal file or unlock the
36026** database then the IO error code is returned to the user. If the
36027** operation to finalize the journal file fails, then the code still
36028** tries to unlock the database file if not in exclusive mode. If the
36029** unlock operation fails as well, then the first error code related
36030** to the first error encountered (the journal finalization one) is
36031** returned.
36032*/
36033static int pager_end_transaction(Pager *pPager, int hasMaster){
36034  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
36035  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
36036
36037  /* Do nothing if the pager does not have an open write transaction
36038  ** or at least a RESERVED lock. This function may be called when there
36039  ** is no write-transaction active but a RESERVED or greater lock is
36040  ** held under two circumstances:
36041  **
36042  **   1. After a successful hot-journal rollback, it is called with
36043  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
36044  **
36045  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
36046  **      lock switches back to locking_mode=normal and then executes a
36047  **      read-transaction, this function is called with eState==PAGER_READER
36048  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
36049  */
36050  assert( assert_pager_state(pPager) );
36051  assert( pPager->eState!=PAGER_ERROR );
36052  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
36053    return SQLITE_OK;
36054  }
36055
36056  releaseAllSavepoints(pPager);
36057  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
36058  if( isOpen(pPager->jfd) ){
36059    assert( !pagerUseWal(pPager) );
36060
36061    /* Finalize the journal file. */
36062    if( sqlite3IsMemJournal(pPager->jfd) ){
36063      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36064      sqlite3OsClose(pPager->jfd);
36065    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
36066      if( pPager->journalOff==0 ){
36067        rc = SQLITE_OK;
36068      }else{
36069        rc = sqlite3OsTruncate(pPager->jfd, 0);
36070      }
36071      pPager->journalOff = 0;
36072    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36073      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
36074    ){
36075      rc = zeroJournalHdr(pPager, hasMaster);
36076      pPager->journalOff = 0;
36077    }else{
36078      /* This branch may be executed with Pager.journalMode==MEMORY if
36079      ** a hot-journal was just rolled back. In this case the journal
36080      ** file should be closed and deleted. If this connection writes to
36081      ** the database file, it will do so using an in-memory journal.
36082      */
36083      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
36084           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
36085           || pPager->journalMode==PAGER_JOURNALMODE_WAL
36086      );
36087      sqlite3OsClose(pPager->jfd);
36088      if( !pPager->tempFile ){
36089        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
36090      }
36091    }
36092  }
36093
36094#ifdef SQLITE_CHECK_PAGES
36095  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
36096  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
36097    PgHdr *p = pager_lookup(pPager, 1);
36098    if( p ){
36099      p->pageHash = 0;
36100      sqlite3PagerUnref(p);
36101    }
36102  }
36103#endif
36104
36105  sqlite3BitvecDestroy(pPager->pInJournal);
36106  pPager->pInJournal = 0;
36107  pPager->nRec = 0;
36108  sqlite3PcacheCleanAll(pPager->pPCache);
36109  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
36110
36111  if( pagerUseWal(pPager) ){
36112    /* Drop the WAL write-lock, if any. Also, if the connection was in
36113    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
36114    ** lock held on the database file.
36115    */
36116    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
36117    assert( rc2==SQLITE_OK );
36118  }
36119  if( !pPager->exclusiveMode
36120   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
36121  ){
36122    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
36123    pPager->changeCountDone = 0;
36124  }
36125  pPager->eState = PAGER_READER;
36126  pPager->setMaster = 0;
36127
36128  return (rc==SQLITE_OK?rc2:rc);
36129}
36130
36131/*
36132** Execute a rollback if a transaction is active and unlock the
36133** database file.
36134**
36135** If the pager has already entered the ERROR state, do not attempt
36136** the rollback at this time. Instead, pager_unlock() is called. The
36137** call to pager_unlock() will discard all in-memory pages, unlock
36138** the database file and move the pager back to OPEN state. If this
36139** means that there is a hot-journal left in the file-system, the next
36140** connection to obtain a shared lock on the pager (which may be this one)
36141** will roll it back.
36142**
36143** If the pager has not already entered the ERROR state, but an IO or
36144** malloc error occurs during a rollback, then this will itself cause
36145** the pager to enter the ERROR state. Which will be cleared by the
36146** call to pager_unlock(), as described above.
36147*/
36148static void pagerUnlockAndRollback(Pager *pPager){
36149  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
36150    assert( assert_pager_state(pPager) );
36151    if( pPager->eState>=PAGER_WRITER_LOCKED ){
36152      sqlite3BeginBenignMalloc();
36153      sqlite3PagerRollback(pPager);
36154      sqlite3EndBenignMalloc();
36155    }else if( !pPager->exclusiveMode ){
36156      assert( pPager->eState==PAGER_READER );
36157      pager_end_transaction(pPager, 0);
36158    }
36159  }
36160  pager_unlock(pPager);
36161}
36162
36163/*
36164** Parameter aData must point to a buffer of pPager->pageSize bytes
36165** of data. Compute and return a checksum based ont the contents of the
36166** page of data and the current value of pPager->cksumInit.
36167**
36168** This is not a real checksum. It is really just the sum of the
36169** random initial value (pPager->cksumInit) and every 200th byte
36170** of the page data, starting with byte offset (pPager->pageSize%200).
36171** Each byte is interpreted as an 8-bit unsigned integer.
36172**
36173** Changing the formula used to compute this checksum results in an
36174** incompatible journal file format.
36175**
36176** If journal corruption occurs due to a power failure, the most likely
36177** scenario is that one end or the other of the record will be changed.
36178** It is much less likely that the two ends of the journal record will be
36179** correct and the middle be corrupt.  Thus, this "checksum" scheme,
36180** though fast and simple, catches the mostly likely kind of corruption.
36181*/
36182static u32 pager_cksum(Pager *pPager, const u8 *aData){
36183  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
36184  int i = pPager->pageSize-200;          /* Loop counter */
36185  while( i>0 ){
36186    cksum += aData[i];
36187    i -= 200;
36188  }
36189  return cksum;
36190}
36191
36192/*
36193** Report the current page size and number of reserved bytes back
36194** to the codec.
36195*/
36196#ifdef SQLITE_HAS_CODEC
36197static void pagerReportSize(Pager *pPager){
36198  if( pPager->xCodecSizeChng ){
36199    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
36200                           (int)pPager->nReserve);
36201  }
36202}
36203#else
36204# define pagerReportSize(X)     /* No-op if we do not support a codec */
36205#endif
36206
36207/*
36208** Read a single page from either the journal file (if isMainJrnl==1) or
36209** from the sub-journal (if isMainJrnl==0) and playback that page.
36210** The page begins at offset *pOffset into the file. The *pOffset
36211** value is increased to the start of the next page in the journal.
36212**
36213** The main rollback journal uses checksums - the statement journal does
36214** not.
36215**
36216** If the page number of the page record read from the (sub-)journal file
36217** is greater than the current value of Pager.dbSize, then playback is
36218** skipped and SQLITE_OK is returned.
36219**
36220** If pDone is not NULL, then it is a record of pages that have already
36221** been played back.  If the page at *pOffset has already been played back
36222** (if the corresponding pDone bit is set) then skip the playback.
36223** Make sure the pDone bit corresponding to the *pOffset page is set
36224** prior to returning.
36225**
36226** If the page record is successfully read from the (sub-)journal file
36227** and played back, then SQLITE_OK is returned. If an IO error occurs
36228** while reading the record from the (sub-)journal file or while writing
36229** to the database file, then the IO error code is returned. If data
36230** is successfully read from the (sub-)journal file but appears to be
36231** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
36232** two circumstances:
36233**
36234**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
36235**   * If the record is being rolled back from the main journal file
36236**     and the checksum field does not match the record content.
36237**
36238** Neither of these two scenarios are possible during a savepoint rollback.
36239**
36240** If this is a savepoint rollback, then memory may have to be dynamically
36241** allocated by this function. If this is the case and an allocation fails,
36242** SQLITE_NOMEM is returned.
36243*/
36244static int pager_playback_one_page(
36245  Pager *pPager,                /* The pager being played back */
36246  i64 *pOffset,                 /* Offset of record to playback */
36247  Bitvec *pDone,                /* Bitvec of pages already played back */
36248  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
36249  int isSavepnt                 /* True for a savepoint rollback */
36250){
36251  int rc;
36252  PgHdr *pPg;                   /* An existing page in the cache */
36253  Pgno pgno;                    /* The page number of a page in journal */
36254  u32 cksum;                    /* Checksum used for sanity checking */
36255  char *aData;                  /* Temporary storage for the page */
36256  sqlite3_file *jfd;            /* The file descriptor for the journal file */
36257  int isSynced;                 /* True if journal page is synced */
36258
36259  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
36260  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
36261  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
36262  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
36263
36264  aData = pPager->pTmpSpace;
36265  assert( aData );         /* Temp storage must have already been allocated */
36266  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
36267
36268  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
36269  ** or savepoint rollback done at the request of the caller) or this is
36270  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
36271  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
36272  ** only reads from the main journal, not the sub-journal.
36273  */
36274  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
36275       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
36276  );
36277  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
36278
36279  /* Read the page number and page data from the journal or sub-journal
36280  ** file. Return an error code to the caller if an IO error occurs.
36281  */
36282  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
36283  rc = read32bits(jfd, *pOffset, &pgno);
36284  if( rc!=SQLITE_OK ) return rc;
36285  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
36286  if( rc!=SQLITE_OK ) return rc;
36287  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
36288
36289  /* Sanity checking on the page.  This is more important that I originally
36290  ** thought.  If a power failure occurs while the journal is being written,
36291  ** it could cause invalid data to be written into the journal.  We need to
36292  ** detect this invalid data (with high probability) and ignore it.
36293  */
36294  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
36295    assert( !isSavepnt );
36296    return SQLITE_DONE;
36297  }
36298  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
36299    return SQLITE_OK;
36300  }
36301  if( isMainJrnl ){
36302    rc = read32bits(jfd, (*pOffset)-4, &cksum);
36303    if( rc ) return rc;
36304    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
36305      return SQLITE_DONE;
36306    }
36307  }
36308
36309  /* If this page has already been played by before during the current
36310  ** rollback, then don't bother to play it back again.
36311  */
36312  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
36313    return rc;
36314  }
36315
36316  /* When playing back page 1, restore the nReserve setting
36317  */
36318  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
36319    pPager->nReserve = ((u8*)aData)[20];
36320    pagerReportSize(pPager);
36321  }
36322
36323  /* If the pager is in CACHEMOD state, then there must be a copy of this
36324  ** page in the pager cache. In this case just update the pager cache,
36325  ** not the database file. The page is left marked dirty in this case.
36326  **
36327  ** An exception to the above rule: If the database is in no-sync mode
36328  ** and a page is moved during an incremental vacuum then the page may
36329  ** not be in the pager cache. Later: if a malloc() or IO error occurs
36330  ** during a Movepage() call, then the page may not be in the cache
36331  ** either. So the condition described in the above paragraph is not
36332  ** assert()able.
36333  **
36334  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
36335  ** pager cache if it exists and the main file. The page is then marked
36336  ** not dirty. Since this code is only executed in PAGER_OPEN state for
36337  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
36338  ** if the pager is in OPEN state.
36339  **
36340  ** Ticket #1171:  The statement journal might contain page content that is
36341  ** different from the page content at the start of the transaction.
36342  ** This occurs when a page is changed prior to the start of a statement
36343  ** then changed again within the statement.  When rolling back such a
36344  ** statement we must not write to the original database unless we know
36345  ** for certain that original page contents are synced into the main rollback
36346  ** journal.  Otherwise, a power loss might leave modified data in the
36347  ** database file without an entry in the rollback journal that can
36348  ** restore the database to its original form.  Two conditions must be
36349  ** met before writing to the database files. (1) the database must be
36350  ** locked.  (2) we know that the original page content is fully synced
36351  ** in the main journal either because the page is not in cache or else
36352  ** the page is marked as needSync==0.
36353  **
36354  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
36355  ** is possible to fail a statement on a database that does not yet exist.
36356  ** Do not attempt to write if database file has never been opened.
36357  */
36358  if( pagerUseWal(pPager) ){
36359    pPg = 0;
36360  }else{
36361    pPg = pager_lookup(pPager, pgno);
36362  }
36363  assert( pPg || !MEMDB );
36364  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
36365  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
36366           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
36367           (isMainJrnl?"main-journal":"sub-journal")
36368  ));
36369  if( isMainJrnl ){
36370    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
36371  }else{
36372    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
36373  }
36374  if( isOpen(pPager->fd)
36375   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36376   && isSynced
36377  ){
36378    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
36379    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
36380    assert( !pagerUseWal(pPager) );
36381    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
36382    if( pgno>pPager->dbFileSize ){
36383      pPager->dbFileSize = pgno;
36384    }
36385    if( pPager->pBackup ){
36386      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
36387      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
36388      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
36389    }
36390  }else if( !isMainJrnl && pPg==0 ){
36391    /* If this is a rollback of a savepoint and data was not written to
36392    ** the database and the page is not in-memory, there is a potential
36393    ** problem. When the page is next fetched by the b-tree layer, it
36394    ** will be read from the database file, which may or may not be
36395    ** current.
36396    **
36397    ** There are a couple of different ways this can happen. All are quite
36398    ** obscure. When running in synchronous mode, this can only happen
36399    ** if the page is on the free-list at the start of the transaction, then
36400    ** populated, then moved using sqlite3PagerMovepage().
36401    **
36402    ** The solution is to add an in-memory page to the cache containing
36403    ** the data just read from the sub-journal. Mark the page as dirty
36404    ** and if the pager requires a journal-sync, then mark the page as
36405    ** requiring a journal-sync before it is written.
36406    */
36407    assert( isSavepnt );
36408    assert( pPager->doNotSpill==0 );
36409    pPager->doNotSpill++;
36410    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
36411    assert( pPager->doNotSpill==1 );
36412    pPager->doNotSpill--;
36413    if( rc!=SQLITE_OK ) return rc;
36414    pPg->flags &= ~PGHDR_NEED_READ;
36415    sqlite3PcacheMakeDirty(pPg);
36416  }
36417  if( pPg ){
36418    /* No page should ever be explicitly rolled back that is in use, except
36419    ** for page 1 which is held in use in order to keep the lock on the
36420    ** database active. However such a page may be rolled back as a result
36421    ** of an internal error resulting in an automatic call to
36422    ** sqlite3PagerRollback().
36423    */
36424    void *pData;
36425    pData = pPg->pData;
36426    memcpy(pData, (u8*)aData, pPager->pageSize);
36427    pPager->xReiniter(pPg);
36428    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
36429      /* If the contents of this page were just restored from the main
36430      ** journal file, then its content must be as they were when the
36431      ** transaction was first opened. In this case we can mark the page
36432      ** as clean, since there will be no need to write it out to the
36433      ** database.
36434      **
36435      ** There is one exception to this rule. If the page is being rolled
36436      ** back as part of a savepoint (or statement) rollback from an
36437      ** unsynced portion of the main journal file, then it is not safe
36438      ** to mark the page as clean. This is because marking the page as
36439      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
36440      ** already in the journal file (recorded in Pager.pInJournal) and
36441      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
36442      ** again within this transaction, it will be marked as dirty but
36443      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
36444      ** be written out into the database file before its journal file
36445      ** segment is synced. If a crash occurs during or following this,
36446      ** database corruption may ensue.
36447      */
36448      assert( !pagerUseWal(pPager) );
36449      sqlite3PcacheMakeClean(pPg);
36450    }
36451    pager_set_pagehash(pPg);
36452
36453    /* If this was page 1, then restore the value of Pager.dbFileVers.
36454    ** Do this before any decoding. */
36455    if( pgno==1 ){
36456      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
36457    }
36458
36459    /* Decode the page just read from disk */
36460    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
36461    sqlite3PcacheRelease(pPg);
36462  }
36463  return rc;
36464}
36465
36466/*
36467** Parameter zMaster is the name of a master journal file. A single journal
36468** file that referred to the master journal file has just been rolled back.
36469** This routine checks if it is possible to delete the master journal file,
36470** and does so if it is.
36471**
36472** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
36473** available for use within this function.
36474**
36475** When a master journal file is created, it is populated with the names
36476** of all of its child journals, one after another, formatted as utf-8
36477** encoded text. The end of each child journal file is marked with a
36478** nul-terminator byte (0x00). i.e. the entire contents of a master journal
36479** file for a transaction involving two databases might be:
36480**
36481**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
36482**
36483** A master journal file may only be deleted once all of its child
36484** journals have been rolled back.
36485**
36486** This function reads the contents of the master-journal file into
36487** memory and loops through each of the child journal names. For
36488** each child journal, it checks if:
36489**
36490**   * if the child journal exists, and if so
36491**   * if the child journal contains a reference to master journal
36492**     file zMaster
36493**
36494** If a child journal can be found that matches both of the criteria
36495** above, this function returns without doing anything. Otherwise, if
36496** no such child journal can be found, file zMaster is deleted from
36497** the file-system using sqlite3OsDelete().
36498**
36499** If an IO error within this function, an error code is returned. This
36500** function allocates memory by calling sqlite3Malloc(). If an allocation
36501** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
36502** occur, SQLITE_OK is returned.
36503**
36504** TODO: This function allocates a single block of memory to load
36505** the entire contents of the master journal file. This could be
36506** a couple of kilobytes or so - potentially larger than the page
36507** size.
36508*/
36509static int pager_delmaster(Pager *pPager, const char *zMaster){
36510  sqlite3_vfs *pVfs = pPager->pVfs;
36511  int rc;                   /* Return code */
36512  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
36513  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
36514  char *zMasterJournal = 0; /* Contents of master journal file */
36515  i64 nMasterJournal;       /* Size of master journal file */
36516  char *zJournal;           /* Pointer to one journal within MJ file */
36517  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
36518  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
36519
36520  /* Allocate space for both the pJournal and pMaster file descriptors.
36521  ** If successful, open the master journal file for reading.
36522  */
36523  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
36524  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
36525  if( !pMaster ){
36526    rc = SQLITE_NOMEM;
36527  }else{
36528    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
36529    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
36530  }
36531  if( rc!=SQLITE_OK ) goto delmaster_out;
36532
36533  /* Load the entire master journal file into space obtained from
36534  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
36535  ** sufficient space (in zMasterPtr) to hold the names of master
36536  ** journal files extracted from regular rollback-journals.
36537  */
36538  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
36539  if( rc!=SQLITE_OK ) goto delmaster_out;
36540  nMasterPtr = pVfs->mxPathname+1;
36541  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
36542  if( !zMasterJournal ){
36543    rc = SQLITE_NOMEM;
36544    goto delmaster_out;
36545  }
36546  zMasterPtr = &zMasterJournal[nMasterJournal+1];
36547  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
36548  if( rc!=SQLITE_OK ) goto delmaster_out;
36549  zMasterJournal[nMasterJournal] = 0;
36550
36551  zJournal = zMasterJournal;
36552  while( (zJournal-zMasterJournal)<nMasterJournal ){
36553    int exists;
36554    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
36555    if( rc!=SQLITE_OK ){
36556      goto delmaster_out;
36557    }
36558    if( exists ){
36559      /* One of the journals pointed to by the master journal exists.
36560      ** Open it and check if it points at the master journal. If
36561      ** so, return without deleting the master journal file.
36562      */
36563      int c;
36564      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
36565      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
36566      if( rc!=SQLITE_OK ){
36567        goto delmaster_out;
36568      }
36569
36570      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
36571      sqlite3OsClose(pJournal);
36572      if( rc!=SQLITE_OK ){
36573        goto delmaster_out;
36574      }
36575
36576      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
36577      if( c ){
36578        /* We have a match. Do not delete the master journal file. */
36579        goto delmaster_out;
36580      }
36581    }
36582    zJournal += (sqlite3Strlen30(zJournal)+1);
36583  }
36584
36585  sqlite3OsClose(pMaster);
36586  rc = sqlite3OsDelete(pVfs, zMaster, 0);
36587
36588delmaster_out:
36589  sqlite3_free(zMasterJournal);
36590  if( pMaster ){
36591    sqlite3OsClose(pMaster);
36592    assert( !isOpen(pJournal) );
36593    sqlite3_free(pMaster);
36594  }
36595  return rc;
36596}
36597
36598
36599/*
36600** This function is used to change the actual size of the database
36601** file in the file-system. This only happens when committing a transaction,
36602** or rolling back a transaction (including rolling back a hot-journal).
36603**
36604** If the main database file is not open, or the pager is not in either
36605** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
36606** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
36607** If the file on disk is currently larger than nPage pages, then use the VFS
36608** xTruncate() method to truncate it.
36609**
36610** Or, it might might be the case that the file on disk is smaller than
36611** nPage pages. Some operating system implementations can get confused if
36612** you try to truncate a file to some size that is larger than it
36613** currently is, so detect this case and write a single zero byte to
36614** the end of the new file instead.
36615**
36616** If successful, return SQLITE_OK. If an IO error occurs while modifying
36617** the database file, return the error code to the caller.
36618*/
36619static int pager_truncate(Pager *pPager, Pgno nPage){
36620  int rc = SQLITE_OK;
36621  assert( pPager->eState!=PAGER_ERROR );
36622  assert( pPager->eState!=PAGER_READER );
36623
36624  if( isOpen(pPager->fd)
36625   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36626  ){
36627    i64 currentSize, newSize;
36628    assert( pPager->eLock==EXCLUSIVE_LOCK );
36629    /* TODO: Is it safe to use Pager.dbFileSize here? */
36630    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
36631    newSize = pPager->pageSize*(i64)nPage;
36632    if( rc==SQLITE_OK && currentSize!=newSize ){
36633      if( currentSize>newSize ){
36634        rc = sqlite3OsTruncate(pPager->fd, newSize);
36635      }else{
36636        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
36637      }
36638      if( rc==SQLITE_OK ){
36639        pPager->dbFileSize = nPage;
36640      }
36641    }
36642  }
36643  return rc;
36644}
36645
36646/*
36647** Set the value of the Pager.sectorSize variable for the given
36648** pager based on the value returned by the xSectorSize method
36649** of the open database file. The sector size will be used used
36650** to determine the size and alignment of journal header and
36651** master journal pointers within created journal files.
36652**
36653** For temporary files the effective sector size is always 512 bytes.
36654**
36655** Otherwise, for non-temporary files, the effective sector size is
36656** the value returned by the xSectorSize() method rounded up to 32 if
36657** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
36658** is greater than MAX_SECTOR_SIZE.
36659*/
36660static void setSectorSize(Pager *pPager){
36661  assert( isOpen(pPager->fd) || pPager->tempFile );
36662
36663  if( !pPager->tempFile ){
36664    /* Sector size doesn't matter for temporary files. Also, the file
36665    ** may not have been opened yet, in which case the OsSectorSize()
36666    ** call will segfault.
36667    */
36668    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
36669  }
36670  if( pPager->sectorSize<32 ){
36671    pPager->sectorSize = 512;
36672  }
36673  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
36674    assert( MAX_SECTOR_SIZE>=512 );
36675    pPager->sectorSize = MAX_SECTOR_SIZE;
36676  }
36677}
36678
36679/*
36680** Playback the journal and thus restore the database file to
36681** the state it was in before we started making changes.
36682**
36683** The journal file format is as follows:
36684**
36685**  (1)  8 byte prefix.  A copy of aJournalMagic[].
36686**  (2)  4 byte big-endian integer which is the number of valid page records
36687**       in the journal.  If this value is 0xffffffff, then compute the
36688**       number of page records from the journal size.
36689**  (3)  4 byte big-endian integer which is the initial value for the
36690**       sanity checksum.
36691**  (4)  4 byte integer which is the number of pages to truncate the
36692**       database to during a rollback.
36693**  (5)  4 byte big-endian integer which is the sector size.  The header
36694**       is this many bytes in size.
36695**  (6)  4 byte big-endian integer which is the page size.
36696**  (7)  zero padding out to the next sector size.
36697**  (8)  Zero or more pages instances, each as follows:
36698**        +  4 byte page number.
36699**        +  pPager->pageSize bytes of data.
36700**        +  4 byte checksum
36701**
36702** When we speak of the journal header, we mean the first 7 items above.
36703** Each entry in the journal is an instance of the 8th item.
36704**
36705** Call the value from the second bullet "nRec".  nRec is the number of
36706** valid page entries in the journal.  In most cases, you can compute the
36707** value of nRec from the size of the journal file.  But if a power
36708** failure occurred while the journal was being written, it could be the
36709** case that the size of the journal file had already been increased but
36710** the extra entries had not yet made it safely to disk.  In such a case,
36711** the value of nRec computed from the file size would be too large.  For
36712** that reason, we always use the nRec value in the header.
36713**
36714** If the nRec value is 0xffffffff it means that nRec should be computed
36715** from the file size.  This value is used when the user selects the
36716** no-sync option for the journal.  A power failure could lead to corruption
36717** in this case.  But for things like temporary table (which will be
36718** deleted when the power is restored) we don't care.
36719**
36720** If the file opened as the journal file is not a well-formed
36721** journal file then all pages up to the first corrupted page are rolled
36722** back (or no pages if the journal header is corrupted). The journal file
36723** is then deleted and SQLITE_OK returned, just as if no corruption had
36724** been encountered.
36725**
36726** If an I/O or malloc() error occurs, the journal-file is not deleted
36727** and an error code is returned.
36728**
36729** The isHot parameter indicates that we are trying to rollback a journal
36730** that might be a hot journal.  Or, it could be that the journal is
36731** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
36732** If the journal really is hot, reset the pager cache prior rolling
36733** back any content.  If the journal is merely persistent, no reset is
36734** needed.
36735*/
36736static int pager_playback(Pager *pPager, int isHot){
36737  sqlite3_vfs *pVfs = pPager->pVfs;
36738  i64 szJ;                 /* Size of the journal file in bytes */
36739  u32 nRec;                /* Number of Records in the journal */
36740  u32 u;                   /* Unsigned loop counter */
36741  Pgno mxPg = 0;           /* Size of the original file in pages */
36742  int rc;                  /* Result code of a subroutine */
36743  int res = 1;             /* Value returned by sqlite3OsAccess() */
36744  char *zMaster = 0;       /* Name of master journal file if any */
36745  int needPagerReset;      /* True to reset page prior to first page rollback */
36746
36747  /* Figure out how many records are in the journal.  Abort early if
36748  ** the journal is empty.
36749  */
36750  assert( isOpen(pPager->jfd) );
36751  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
36752  if( rc!=SQLITE_OK ){
36753    goto end_playback;
36754  }
36755
36756  /* Read the master journal name from the journal, if it is present.
36757  ** If a master journal file name is specified, but the file is not
36758  ** present on disk, then the journal is not hot and does not need to be
36759  ** played back.
36760  **
36761  ** TODO: Technically the following is an error because it assumes that
36762  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
36763  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
36764  **  mxPathname is 512, which is the same as the minimum allowable value
36765  ** for pageSize.
36766  */
36767  zMaster = pPager->pTmpSpace;
36768  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
36769  if( rc==SQLITE_OK && zMaster[0] ){
36770    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
36771  }
36772  zMaster = 0;
36773  if( rc!=SQLITE_OK || !res ){
36774    goto end_playback;
36775  }
36776  pPager->journalOff = 0;
36777  needPagerReset = isHot;
36778
36779  /* This loop terminates either when a readJournalHdr() or
36780  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
36781  ** occurs.
36782  */
36783  while( 1 ){
36784    /* Read the next journal header from the journal file.  If there are
36785    ** not enough bytes left in the journal file for a complete header, or
36786    ** it is corrupted, then a process must have failed while writing it.
36787    ** This indicates nothing more needs to be rolled back.
36788    */
36789    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
36790    if( rc!=SQLITE_OK ){
36791      if( rc==SQLITE_DONE ){
36792        rc = SQLITE_OK;
36793      }
36794      goto end_playback;
36795    }
36796
36797    /* If nRec is 0xffffffff, then this journal was created by a process
36798    ** working in no-sync mode. This means that the rest of the journal
36799    ** file consists of pages, there are no more journal headers. Compute
36800    ** the value of nRec based on this assumption.
36801    */
36802    if( nRec==0xffffffff ){
36803      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
36804      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
36805    }
36806
36807    /* If nRec is 0 and this rollback is of a transaction created by this
36808    ** process and if this is the final header in the journal, then it means
36809    ** that this part of the journal was being filled but has not yet been
36810    ** synced to disk.  Compute the number of pages based on the remaining
36811    ** size of the file.
36812    **
36813    ** The third term of the test was added to fix ticket #2565.
36814    ** When rolling back a hot journal, nRec==0 always means that the next
36815    ** chunk of the journal contains zero pages to be rolled back.  But
36816    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
36817    ** the journal, it means that the journal might contain additional
36818    ** pages that need to be rolled back and that the number of pages
36819    ** should be computed based on the journal file size.
36820    */
36821    if( nRec==0 && !isHot &&
36822        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
36823      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
36824    }
36825
36826    /* If this is the first header read from the journal, truncate the
36827    ** database file back to its original size.
36828    */
36829    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
36830      rc = pager_truncate(pPager, mxPg);
36831      if( rc!=SQLITE_OK ){
36832        goto end_playback;
36833      }
36834      pPager->dbSize = mxPg;
36835    }
36836
36837    /* Copy original pages out of the journal and back into the
36838    ** database file and/or page cache.
36839    */
36840    for(u=0; u<nRec; u++){
36841      if( needPagerReset ){
36842        pager_reset(pPager);
36843        needPagerReset = 0;
36844      }
36845      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
36846      if( rc!=SQLITE_OK ){
36847        if( rc==SQLITE_DONE ){
36848          rc = SQLITE_OK;
36849          pPager->journalOff = szJ;
36850          break;
36851        }else if( rc==SQLITE_IOERR_SHORT_READ ){
36852          /* If the journal has been truncated, simply stop reading and
36853          ** processing the journal. This might happen if the journal was
36854          ** not completely written and synced prior to a crash.  In that
36855          ** case, the database should have never been written in the
36856          ** first place so it is OK to simply abandon the rollback. */
36857          rc = SQLITE_OK;
36858          goto end_playback;
36859        }else{
36860          /* If we are unable to rollback, quit and return the error
36861          ** code.  This will cause the pager to enter the error state
36862          ** so that no further harm will be done.  Perhaps the next
36863          ** process to come along will be able to rollback the database.
36864          */
36865          goto end_playback;
36866        }
36867      }
36868    }
36869  }
36870  /*NOTREACHED*/
36871  assert( 0 );
36872
36873end_playback:
36874  /* Following a rollback, the database file should be back in its original
36875  ** state prior to the start of the transaction, so invoke the
36876  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
36877  ** assertion that the transaction counter was modified.
36878  */
36879  assert(
36880    pPager->fd->pMethods==0 ||
36881    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
36882  );
36883
36884  /* If this playback is happening automatically as a result of an IO or
36885  ** malloc error that occurred after the change-counter was updated but
36886  ** before the transaction was committed, then the change-counter
36887  ** modification may just have been reverted. If this happens in exclusive
36888  ** mode, then subsequent transactions performed by the connection will not
36889  ** update the change-counter at all. This may lead to cache inconsistency
36890  ** problems for other processes at some point in the future. So, just
36891  ** in case this has happened, clear the changeCountDone flag now.
36892  */
36893  pPager->changeCountDone = pPager->tempFile;
36894
36895  if( rc==SQLITE_OK ){
36896    zMaster = pPager->pTmpSpace;
36897    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
36898    testcase( rc!=SQLITE_OK );
36899  }
36900  if( rc==SQLITE_OK && !pPager->noSync
36901   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36902  ){
36903    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36904  }
36905  if( rc==SQLITE_OK ){
36906    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
36907    testcase( rc!=SQLITE_OK );
36908  }
36909  if( rc==SQLITE_OK && zMaster[0] && res ){
36910    /* If there was a master journal and this routine will return success,
36911    ** see if it is possible to delete the master journal.
36912    */
36913    rc = pager_delmaster(pPager, zMaster);
36914    testcase( rc!=SQLITE_OK );
36915  }
36916
36917  /* The Pager.sectorSize variable may have been updated while rolling
36918  ** back a journal created by a process with a different sector size
36919  ** value. Reset it to the correct value for this process.
36920  */
36921  setSectorSize(pPager);
36922  return rc;
36923}
36924
36925
36926/*
36927** Read the content for page pPg out of the database file and into
36928** pPg->pData. A shared lock or greater must be held on the database
36929** file before this function is called.
36930**
36931** If page 1 is read, then the value of Pager.dbFileVers[] is set to
36932** the value read from the database file.
36933**
36934** If an IO error occurs, then the IO error is returned to the caller.
36935** Otherwise, SQLITE_OK is returned.
36936*/
36937static int readDbPage(PgHdr *pPg){
36938  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
36939  Pgno pgno = pPg->pgno;       /* Page number to read */
36940  int rc = SQLITE_OK;          /* Return code */
36941  int isInWal = 0;             /* True if page is in log file */
36942  int pgsz = pPager->pageSize; /* Number of bytes to read */
36943
36944  assert( pPager->eState>=PAGER_READER && !MEMDB );
36945  assert( isOpen(pPager->fd) );
36946
36947  if( NEVER(!isOpen(pPager->fd)) ){
36948    assert( pPager->tempFile );
36949    memset(pPg->pData, 0, pPager->pageSize);
36950    return SQLITE_OK;
36951  }
36952
36953  if( pagerUseWal(pPager) ){
36954    /* Try to pull the page from the write-ahead log. */
36955    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
36956  }
36957  if( rc==SQLITE_OK && !isInWal ){
36958    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
36959    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
36960    if( rc==SQLITE_IOERR_SHORT_READ ){
36961      rc = SQLITE_OK;
36962    }
36963  }
36964
36965  if( pgno==1 ){
36966    if( rc ){
36967      /* If the read is unsuccessful, set the dbFileVers[] to something
36968      ** that will never be a valid file version.  dbFileVers[] is a copy
36969      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
36970      ** zero or the size of the database in page. Bytes 32..35 and 35..39
36971      ** should be page numbers which are never 0xffffffff.  So filling
36972      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
36973      **
36974      ** For an encrypted database, the situation is more complex:  bytes
36975      ** 24..39 of the database are white noise.  But the probability of
36976      ** white noising equaling 16 bytes of 0xff is vanishingly small so
36977      ** we should still be ok.
36978      */
36979      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
36980    }else{
36981      u8 *dbFileVers = &((u8*)pPg->pData)[24];
36982      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
36983    }
36984  }
36985  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
36986
36987  PAGER_INCR(sqlite3_pager_readdb_count);
36988  PAGER_INCR(pPager->nRead);
36989  IOTRACE(("PGIN %p %d\n", pPager, pgno));
36990  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
36991               PAGERID(pPager), pgno, pager_pagehash(pPg)));
36992
36993  return rc;
36994}
36995
36996#ifndef SQLITE_OMIT_WAL
36997/*
36998** This function is invoked once for each page that has already been
36999** written into the log file when a WAL transaction is rolled back.
37000** Parameter iPg is the page number of said page. The pCtx argument
37001** is actually a pointer to the Pager structure.
37002**
37003** If page iPg is present in the cache, and has no outstanding references,
37004** it is discarded. Otherwise, if there are one or more outstanding
37005** references, the page content is reloaded from the database. If the
37006** attempt to reload content from the database is required and fails,
37007** return an SQLite error code. Otherwise, SQLITE_OK.
37008*/
37009static int pagerUndoCallback(void *pCtx, Pgno iPg){
37010  int rc = SQLITE_OK;
37011  Pager *pPager = (Pager *)pCtx;
37012  PgHdr *pPg;
37013
37014  pPg = sqlite3PagerLookup(pPager, iPg);
37015  if( pPg ){
37016    if( sqlite3PcachePageRefcount(pPg)==1 ){
37017      sqlite3PcacheDrop(pPg);
37018    }else{
37019      rc = readDbPage(pPg);
37020      if( rc==SQLITE_OK ){
37021        pPager->xReiniter(pPg);
37022      }
37023      sqlite3PagerUnref(pPg);
37024    }
37025  }
37026
37027  /* Normally, if a transaction is rolled back, any backup processes are
37028  ** updated as data is copied out of the rollback journal and into the
37029  ** database. This is not generally possible with a WAL database, as
37030  ** rollback involves simply truncating the log file. Therefore, if one
37031  ** or more frames have already been written to the log (and therefore
37032  ** also copied into the backup databases) as part of this transaction,
37033  ** the backups must be restarted.
37034  */
37035  sqlite3BackupRestart(pPager->pBackup);
37036
37037  return rc;
37038}
37039
37040/*
37041** This function is called to rollback a transaction on a WAL database.
37042*/
37043static int pagerRollbackWal(Pager *pPager){
37044  int rc;                         /* Return Code */
37045  PgHdr *pList;                   /* List of dirty pages to revert */
37046
37047  /* For all pages in the cache that are currently dirty or have already
37048  ** been written (but not committed) to the log file, do one of the
37049  ** following:
37050  **
37051  **   + Discard the cached page (if refcount==0), or
37052  **   + Reload page content from the database (if refcount>0).
37053  */
37054  pPager->dbSize = pPager->dbOrigSize;
37055  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
37056  pList = sqlite3PcacheDirtyList(pPager->pPCache);
37057  while( pList && rc==SQLITE_OK ){
37058    PgHdr *pNext = pList->pDirty;
37059    rc = pagerUndoCallback((void *)pPager, pList->pgno);
37060    pList = pNext;
37061  }
37062
37063  return rc;
37064}
37065
37066/*
37067** This function is a wrapper around sqlite3WalFrames(). As well as logging
37068** the contents of the list of pages headed by pList (connected by pDirty),
37069** this function notifies any active backup processes that the pages have
37070** changed.
37071*/
37072static int pagerWalFrames(
37073  Pager *pPager,                  /* Pager object */
37074  PgHdr *pList,                   /* List of frames to log */
37075  Pgno nTruncate,                 /* Database size after this commit */
37076  int isCommit,                   /* True if this is a commit */
37077  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
37078){
37079  int rc;                         /* Return code */
37080
37081  assert( pPager->pWal );
37082  rc = sqlite3WalFrames(pPager->pWal,
37083      pPager->pageSize, pList, nTruncate, isCommit, sync_flags
37084  );
37085  if( rc==SQLITE_OK && pPager->pBackup ){
37086    PgHdr *p;
37087    for(p=pList; p; p=p->pDirty){
37088      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
37089    }
37090  }
37091
37092#ifdef SQLITE_CHECK_PAGES
37093  {
37094    PgHdr *p;
37095    for(p=pList; p; p=p->pDirty) pager_set_pagehash(p);
37096  }
37097#endif
37098
37099  return rc;
37100}
37101
37102/*
37103** Begin a read transaction on the WAL.
37104**
37105** This routine used to be called "pagerOpenSnapshot()" because it essentially
37106** makes a snapshot of the database at the current point in time and preserves
37107** that snapshot for use by the reader in spite of concurrently changes by
37108** other writers or checkpointers.
37109*/
37110static int pagerBeginReadTransaction(Pager *pPager){
37111  int rc;                         /* Return code */
37112  int changed = 0;                /* True if cache must be reset */
37113
37114  assert( pagerUseWal(pPager) );
37115  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
37116
37117  /* sqlite3WalEndReadTransaction() was not called for the previous
37118  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
37119  ** are in locking_mode=NORMAL and EndRead() was previously called,
37120  ** the duplicate call is harmless.
37121  */
37122  sqlite3WalEndReadTransaction(pPager->pWal);
37123
37124  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37125  if( rc==SQLITE_OK && changed ){
37126    pager_reset(pPager);
37127  }
37128
37129  return rc;
37130}
37131
37132/*
37133** This function is called as part of the transition from PAGER_OPEN
37134** to PAGER_READER state to determine the size of the database file
37135** in pages (assuming the page size currently stored in Pager.pageSize).
37136**
37137** If no error occurs, SQLITE_OK is returned and the size of the database
37138** in pages is stored in *pnPage. Otherwise, an error code (perhaps
37139** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
37140*/
37141static int pagerPagecount(Pager *pPager, Pgno *pnPage){
37142  Pgno nPage;                     /* Value to return via *pnPage */
37143
37144  /* Query the WAL sub-system for the database size. The WalDbsize()
37145  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
37146  ** if the database size is not available. The database size is not
37147  ** available from the WAL sub-system if the log file is empty or
37148  ** contains no valid committed transactions.
37149  */
37150  assert( pPager->eState==PAGER_OPEN );
37151  assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37152  nPage = sqlite3WalDbsize(pPager->pWal);
37153
37154  /* If the database size was not available from the WAL sub-system,
37155  ** determine it based on the size of the database file. If the size
37156  ** of the database file is not an integer multiple of the page-size,
37157  ** round down to the nearest page. Except, any file larger than 0
37158  ** bytes in size is considered to contain at least one page.
37159  */
37160  if( nPage==0 ){
37161    i64 n = 0;                    /* Size of db file in bytes */
37162    assert( isOpen(pPager->fd) || pPager->tempFile );
37163    if( isOpen(pPager->fd) ){
37164      int rc = sqlite3OsFileSize(pPager->fd, &n);
37165      if( rc!=SQLITE_OK ){
37166        return rc;
37167      }
37168    }
37169    nPage = (Pgno)(n / pPager->pageSize);
37170    if( nPage==0 && n>0 ){
37171      nPage = 1;
37172    }
37173  }
37174
37175  /* If the current number of pages in the file is greater than the
37176  ** configured maximum pager number, increase the allowed limit so
37177  ** that the file can be read.
37178  */
37179  if( nPage>pPager->mxPgno ){
37180    pPager->mxPgno = (Pgno)nPage;
37181  }
37182
37183  *pnPage = nPage;
37184  return SQLITE_OK;
37185}
37186
37187
37188/*
37189** Check if the *-wal file that corresponds to the database opened by pPager
37190** exists if the database is not empy, or verify that the *-wal file does
37191** not exist (by deleting it) if the database file is empty.
37192**
37193** If the database is not empty and the *-wal file exists, open the pager
37194** in WAL mode.  If the database is empty or if no *-wal file exists and
37195** if no error occurs, make sure Pager.journalMode is not set to
37196** PAGER_JOURNALMODE_WAL.
37197**
37198** Return SQLITE_OK or an error code.
37199**
37200** The caller must hold a SHARED lock on the database file to call this
37201** function. Because an EXCLUSIVE lock on the db file is required to delete
37202** a WAL on a none-empty database, this ensures there is no race condition
37203** between the xAccess() below and an xDelete() being executed by some
37204** other connection.
37205*/
37206static int pagerOpenWalIfPresent(Pager *pPager){
37207  int rc = SQLITE_OK;
37208  assert( pPager->eState==PAGER_OPEN );
37209  assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37210
37211  if( !pPager->tempFile ){
37212    int isWal;                    /* True if WAL file exists */
37213    Pgno nPage;                   /* Size of the database file */
37214
37215    rc = pagerPagecount(pPager, &nPage);
37216    if( rc ) return rc;
37217    if( nPage==0 ){
37218      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
37219      isWal = 0;
37220    }else{
37221      rc = sqlite3OsAccess(
37222          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
37223      );
37224    }
37225    if( rc==SQLITE_OK ){
37226      if( isWal ){
37227        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
37228        rc = sqlite3PagerOpenWal(pPager, 0);
37229      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
37230        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
37231      }
37232    }
37233  }
37234  return rc;
37235}
37236#endif
37237
37238/*
37239** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
37240** the entire master journal file. The case pSavepoint==NULL occurs when
37241** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
37242** savepoint.
37243**
37244** When pSavepoint is not NULL (meaning a non-transaction savepoint is
37245** being rolled back), then the rollback consists of up to three stages,
37246** performed in the order specified:
37247**
37248**   * Pages are played back from the main journal starting at byte
37249**     offset PagerSavepoint.iOffset and continuing to
37250**     PagerSavepoint.iHdrOffset, or to the end of the main journal
37251**     file if PagerSavepoint.iHdrOffset is zero.
37252**
37253**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
37254**     back starting from the journal header immediately following
37255**     PagerSavepoint.iHdrOffset to the end of the main journal file.
37256**
37257**   * Pages are then played back from the sub-journal file, starting
37258**     with the PagerSavepoint.iSubRec and continuing to the end of
37259**     the journal file.
37260**
37261** Throughout the rollback process, each time a page is rolled back, the
37262** corresponding bit is set in a bitvec structure (variable pDone in the
37263** implementation below). This is used to ensure that a page is only
37264** rolled back the first time it is encountered in either journal.
37265**
37266** If pSavepoint is NULL, then pages are only played back from the main
37267** journal file. There is no need for a bitvec in this case.
37268**
37269** In either case, before playback commences the Pager.dbSize variable
37270** is reset to the value that it held at the start of the savepoint
37271** (or transaction). No page with a page-number greater than this value
37272** is played back. If one is encountered it is simply skipped.
37273*/
37274static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
37275  i64 szJ;                 /* Effective size of the main journal */
37276  i64 iHdrOff;             /* End of first segment of main-journal records */
37277  int rc = SQLITE_OK;      /* Return code */
37278  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
37279
37280  assert( pPager->eState!=PAGER_ERROR );
37281  assert( pPager->eState>=PAGER_WRITER_LOCKED );
37282
37283  /* Allocate a bitvec to use to store the set of pages rolled back */
37284  if( pSavepoint ){
37285    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
37286    if( !pDone ){
37287      return SQLITE_NOMEM;
37288    }
37289  }
37290
37291  /* Set the database size back to the value it was before the savepoint
37292  ** being reverted was opened.
37293  */
37294  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
37295  pPager->changeCountDone = pPager->tempFile;
37296
37297  if( !pSavepoint && pagerUseWal(pPager) ){
37298    return pagerRollbackWal(pPager);
37299  }
37300
37301  /* Use pPager->journalOff as the effective size of the main rollback
37302  ** journal.  The actual file might be larger than this in
37303  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
37304  ** past pPager->journalOff is off-limits to us.
37305  */
37306  szJ = pPager->journalOff;
37307  assert( pagerUseWal(pPager)==0 || szJ==0 );
37308
37309  /* Begin by rolling back records from the main journal starting at
37310  ** PagerSavepoint.iOffset and continuing to the next journal header.
37311  ** There might be records in the main journal that have a page number
37312  ** greater than the current database size (pPager->dbSize) but those
37313  ** will be skipped automatically.  Pages are added to pDone as they
37314  ** are played back.
37315  */
37316  if( pSavepoint && !pagerUseWal(pPager) ){
37317    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
37318    pPager->journalOff = pSavepoint->iOffset;
37319    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
37320      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
37321    }
37322    assert( rc!=SQLITE_DONE );
37323  }else{
37324    pPager->journalOff = 0;
37325  }
37326
37327  /* Continue rolling back records out of the main journal starting at
37328  ** the first journal header seen and continuing until the effective end
37329  ** of the main journal file.  Continue to skip out-of-range pages and
37330  ** continue adding pages rolled back to pDone.
37331  */
37332  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
37333    u32 ii;            /* Loop counter */
37334    u32 nJRec = 0;     /* Number of Journal Records */
37335    u32 dummy;
37336    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
37337    assert( rc!=SQLITE_DONE );
37338
37339    /*
37340    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
37341    ** test is related to ticket #2565.  See the discussion in the
37342    ** pager_playback() function for additional information.
37343    */
37344    if( nJRec==0
37345     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
37346    ){
37347      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
37348    }
37349    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
37350      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
37351    }
37352    assert( rc!=SQLITE_DONE );
37353  }
37354  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
37355
37356  /* Finally,  rollback pages from the sub-journal.  Page that were
37357  ** previously rolled back out of the main journal (and are hence in pDone)
37358  ** will be skipped.  Out-of-range pages are also skipped.
37359  */
37360  if( pSavepoint ){
37361    u32 ii;            /* Loop counter */
37362    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
37363
37364    if( pagerUseWal(pPager) ){
37365      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
37366    }
37367    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
37368      assert( offset==ii*(4+pPager->pageSize) );
37369      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
37370    }
37371    assert( rc!=SQLITE_DONE );
37372  }
37373
37374  sqlite3BitvecDestroy(pDone);
37375  if( rc==SQLITE_OK ){
37376    pPager->journalOff = szJ;
37377  }
37378
37379  return rc;
37380}
37381
37382/*
37383** Change the maximum number of in-memory pages that are allowed.
37384*/
37385SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
37386  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
37387}
37388
37389/*
37390** Adjust the robustness of the database to damage due to OS crashes
37391** or power failures by changing the number of syncs()s when writing
37392** the rollback journal.  There are three levels:
37393**
37394**    OFF       sqlite3OsSync() is never called.  This is the default
37395**              for temporary and transient files.
37396**
37397**    NORMAL    The journal is synced once before writes begin on the
37398**              database.  This is normally adequate protection, but
37399**              it is theoretically possible, though very unlikely,
37400**              that an inopertune power failure could leave the journal
37401**              in a state which would cause damage to the database
37402**              when it is rolled back.
37403**
37404**    FULL      The journal is synced twice before writes begin on the
37405**              database (with some additional information - the nRec field
37406**              of the journal header - being written in between the two
37407**              syncs).  If we assume that writing a
37408**              single disk sector is atomic, then this mode provides
37409**              assurance that the journal will not be corrupted to the
37410**              point of causing damage to the database during rollback.
37411**
37412** Numeric values associated with these states are OFF==1, NORMAL=2,
37413** and FULL=3.
37414*/
37415#ifndef SQLITE_OMIT_PAGER_PRAGMAS
37416SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
37417  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
37418  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
37419  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
37420}
37421#endif
37422
37423/*
37424** The following global variable is incremented whenever the library
37425** attempts to open a temporary file.  This information is used for
37426** testing and analysis only.
37427*/
37428#ifdef SQLITE_TEST
37429SQLITE_API int sqlite3_opentemp_count = 0;
37430#endif
37431
37432/*
37433** Open a temporary file.
37434**
37435** Write the file descriptor into *pFile. Return SQLITE_OK on success
37436** or some other error code if we fail. The OS will automatically
37437** delete the temporary file when it is closed.
37438**
37439** The flags passed to the VFS layer xOpen() call are those specified
37440** by parameter vfsFlags ORed with the following:
37441**
37442**     SQLITE_OPEN_READWRITE
37443**     SQLITE_OPEN_CREATE
37444**     SQLITE_OPEN_EXCLUSIVE
37445**     SQLITE_OPEN_DELETEONCLOSE
37446*/
37447static int pagerOpentemp(
37448  Pager *pPager,        /* The pager object */
37449  sqlite3_file *pFile,  /* Write the file descriptor here */
37450  int vfsFlags          /* Flags passed through to the VFS */
37451){
37452  int rc;               /* Return code */
37453
37454#ifdef SQLITE_TEST
37455  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
37456#endif
37457
37458  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
37459            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
37460  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
37461  assert( rc!=SQLITE_OK || isOpen(pFile) );
37462  return rc;
37463}
37464
37465/*
37466** Set the busy handler function.
37467**
37468** The pager invokes the busy-handler if sqlite3OsLock() returns
37469** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
37470** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
37471** lock. It does *not* invoke the busy handler when upgrading from
37472** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
37473** (which occurs during hot-journal rollback). Summary:
37474**
37475**   Transition                        | Invokes xBusyHandler
37476**   --------------------------------------------------------
37477**   NO_LOCK       -> SHARED_LOCK      | Yes
37478**   SHARED_LOCK   -> RESERVED_LOCK    | No
37479**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
37480**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
37481**
37482** If the busy-handler callback returns non-zero, the lock is
37483** retried. If it returns zero, then the SQLITE_BUSY error is
37484** returned to the caller of the pager API function.
37485*/
37486SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
37487  Pager *pPager,                       /* Pager object */
37488  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
37489  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
37490){
37491  pPager->xBusyHandler = xBusyHandler;
37492  pPager->pBusyHandlerArg = pBusyHandlerArg;
37493}
37494
37495/*
37496** Change the page size used by the Pager object. The new page size
37497** is passed in *pPageSize.
37498**
37499** If the pager is in the error state when this function is called, it
37500** is a no-op. The value returned is the error state error code (i.e.
37501** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
37502**
37503** Otherwise, if all of the following are true:
37504**
37505**   * the new page size (value of *pPageSize) is valid (a power
37506**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
37507**
37508**   * there are no outstanding page references, and
37509**
37510**   * the database is either not an in-memory database or it is
37511**     an in-memory database that currently consists of zero pages.
37512**
37513** then the pager object page size is set to *pPageSize.
37514**
37515** If the page size is changed, then this function uses sqlite3PagerMalloc()
37516** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
37517** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
37518** In all other cases, SQLITE_OK is returned.
37519**
37520** If the page size is not changed, either because one of the enumerated
37521** conditions above is not true, the pager was in error state when this
37522** function was called, or because the memory allocation attempt failed,
37523** then *pPageSize is set to the old, retained page size before returning.
37524*/
37525SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
37526  int rc = SQLITE_OK;
37527
37528  /* It is not possible to do a full assert_pager_state() here, as this
37529  ** function may be called from within PagerOpen(), before the state
37530  ** of the Pager object is internally consistent.
37531  **
37532  ** At one point this function returned an error if the pager was in
37533  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
37534  ** there is at least one outstanding page reference, this function
37535  ** is a no-op for that case anyhow.
37536  */
37537
37538  u32 pageSize = *pPageSize;
37539  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
37540  if( (pPager->memDb==0 || pPager->dbSize==0)
37541   && sqlite3PcacheRefCount(pPager->pPCache)==0
37542   && pageSize && pageSize!=(u32)pPager->pageSize
37543  ){
37544    char *pNew = NULL;             /* New temp space */
37545    i64 nByte = 0;
37546
37547    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
37548      rc = sqlite3OsFileSize(pPager->fd, &nByte);
37549    }
37550    if( rc==SQLITE_OK ){
37551      pNew = (char *)sqlite3PageMalloc(pageSize);
37552      if( !pNew ) rc = SQLITE_NOMEM;
37553    }
37554
37555    if( rc==SQLITE_OK ){
37556      pager_reset(pPager);
37557      pPager->dbSize = (Pgno)(nByte/pageSize);
37558      pPager->pageSize = pageSize;
37559      sqlite3PageFree(pPager->pTmpSpace);
37560      pPager->pTmpSpace = pNew;
37561      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
37562    }
37563  }
37564
37565  *pPageSize = pPager->pageSize;
37566  if( rc==SQLITE_OK ){
37567    if( nReserve<0 ) nReserve = pPager->nReserve;
37568    assert( nReserve>=0 && nReserve<1000 );
37569    pPager->nReserve = (i16)nReserve;
37570    pagerReportSize(pPager);
37571  }
37572  return rc;
37573}
37574
37575/*
37576** Return a pointer to the "temporary page" buffer held internally
37577** by the pager.  This is a buffer that is big enough to hold the
37578** entire content of a database page.  This buffer is used internally
37579** during rollback and will be overwritten whenever a rollback
37580** occurs.  But other modules are free to use it too, as long as
37581** no rollbacks are happening.
37582*/
37583SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
37584  return pPager->pTmpSpace;
37585}
37586
37587/*
37588** Attempt to set the maximum database page count if mxPage is positive.
37589** Make no changes if mxPage is zero or negative.  And never reduce the
37590** maximum page count below the current size of the database.
37591**
37592** Regardless of mxPage, return the current maximum page count.
37593*/
37594SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
37595  if( mxPage>0 ){
37596    pPager->mxPgno = mxPage;
37597  }
37598  if( pPager->eState!=PAGER_OPEN && pPager->mxPgno<pPager->dbSize ){
37599    pPager->mxPgno = pPager->dbSize;
37600  }
37601  return pPager->mxPgno;
37602}
37603
37604/*
37605** The following set of routines are used to disable the simulated
37606** I/O error mechanism.  These routines are used to avoid simulated
37607** errors in places where we do not care about errors.
37608**
37609** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
37610** and generate no code.
37611*/
37612#ifdef SQLITE_TEST
37613SQLITE_API extern int sqlite3_io_error_pending;
37614SQLITE_API extern int sqlite3_io_error_hit;
37615static int saved_cnt;
37616void disable_simulated_io_errors(void){
37617  saved_cnt = sqlite3_io_error_pending;
37618  sqlite3_io_error_pending = -1;
37619}
37620void enable_simulated_io_errors(void){
37621  sqlite3_io_error_pending = saved_cnt;
37622}
37623#else
37624# define disable_simulated_io_errors()
37625# define enable_simulated_io_errors()
37626#endif
37627
37628/*
37629** Read the first N bytes from the beginning of the file into memory
37630** that pDest points to.
37631**
37632** If the pager was opened on a transient file (zFilename==""), or
37633** opened on a file less than N bytes in size, the output buffer is
37634** zeroed and SQLITE_OK returned. The rationale for this is that this
37635** function is used to read database headers, and a new transient or
37636** zero sized database has a header than consists entirely of zeroes.
37637**
37638** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
37639** the error code is returned to the caller and the contents of the
37640** output buffer undefined.
37641*/
37642SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
37643  int rc = SQLITE_OK;
37644  memset(pDest, 0, N);
37645  assert( isOpen(pPager->fd) || pPager->tempFile );
37646
37647  /* This routine is only called by btree immediately after creating
37648  ** the Pager object.  There has not been an opportunity to transition
37649  ** to WAL mode yet.
37650  */
37651  assert( !pagerUseWal(pPager) );
37652
37653  if( isOpen(pPager->fd) ){
37654    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
37655    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
37656    if( rc==SQLITE_IOERR_SHORT_READ ){
37657      rc = SQLITE_OK;
37658    }
37659  }
37660  return rc;
37661}
37662
37663/*
37664** This function may only be called when a read-transaction is open on
37665** the pager. It returns the total number of pages in the database.
37666**
37667** However, if the file is between 1 and <page-size> bytes in size, then
37668** this is considered a 1 page file.
37669*/
37670SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
37671  assert( pPager->eState>=PAGER_READER );
37672  assert( pPager->eState!=PAGER_WRITER_FINISHED );
37673  *pnPage = (int)pPager->dbSize;
37674}
37675
37676
37677/*
37678** Try to obtain a lock of type locktype on the database file. If
37679** a similar or greater lock is already held, this function is a no-op
37680** (returning SQLITE_OK immediately).
37681**
37682** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
37683** the busy callback if the lock is currently not available. Repeat
37684** until the busy callback returns false or until the attempt to
37685** obtain the lock succeeds.
37686**
37687** Return SQLITE_OK on success and an error code if we cannot obtain
37688** the lock. If the lock is obtained successfully, set the Pager.state
37689** variable to locktype before returning.
37690*/
37691static int pager_wait_on_lock(Pager *pPager, int locktype){
37692  int rc;                              /* Return code */
37693
37694  /* Check that this is either a no-op (because the requested lock is
37695  ** already held, or one of the transistions that the busy-handler
37696  ** may be invoked during, according to the comment above
37697  ** sqlite3PagerSetBusyhandler().
37698  */
37699  assert( (pPager->eLock>=locktype)
37700       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
37701       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
37702  );
37703
37704  do {
37705    rc = pagerLockDb(pPager, locktype);
37706  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
37707  return rc;
37708}
37709
37710/*
37711** Function assertTruncateConstraint(pPager) checks that one of the
37712** following is true for all dirty pages currently in the page-cache:
37713**
37714**   a) The page number is less than or equal to the size of the
37715**      current database image, in pages, OR
37716**
37717**   b) if the page content were written at this time, it would not
37718**      be necessary to write the current content out to the sub-journal
37719**      (as determined by function subjRequiresPage()).
37720**
37721** If the condition asserted by this function were not true, and the
37722** dirty page were to be discarded from the cache via the pagerStress()
37723** routine, pagerStress() would not write the current page content to
37724** the database file. If a savepoint transaction were rolled back after
37725** this happened, the correct behaviour would be to restore the current
37726** content of the page. However, since this content is not present in either
37727** the database file or the portion of the rollback journal and
37728** sub-journal rolled back the content could not be restored and the
37729** database image would become corrupt. It is therefore fortunate that
37730** this circumstance cannot arise.
37731*/
37732#if defined(SQLITE_DEBUG)
37733static void assertTruncateConstraintCb(PgHdr *pPg){
37734  assert( pPg->flags&PGHDR_DIRTY );
37735  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
37736}
37737static void assertTruncateConstraint(Pager *pPager){
37738  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
37739}
37740#else
37741# define assertTruncateConstraint(pPager)
37742#endif
37743
37744/*
37745** Truncate the in-memory database file image to nPage pages. This
37746** function does not actually modify the database file on disk. It
37747** just sets the internal state of the pager object so that the
37748** truncation will be done when the current transaction is committed.
37749*/
37750SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
37751  assert( pPager->dbSize>=nPage );
37752  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
37753  pPager->dbSize = nPage;
37754  assertTruncateConstraint(pPager);
37755}
37756
37757
37758/*
37759** This function is called before attempting a hot-journal rollback. It
37760** syncs the journal file to disk, then sets pPager->journalHdr to the
37761** size of the journal file so that the pager_playback() routine knows
37762** that the entire journal file has been synced.
37763**
37764** Syncing a hot-journal to disk before attempting to roll it back ensures
37765** that if a power-failure occurs during the rollback, the process that
37766** attempts rollback following system recovery sees the same journal
37767** content as this process.
37768**
37769** If everything goes as planned, SQLITE_OK is returned. Otherwise,
37770** an SQLite error code.
37771*/
37772static int pagerSyncHotJournal(Pager *pPager){
37773  int rc = SQLITE_OK;
37774  if( !pPager->noSync ){
37775    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
37776  }
37777  if( rc==SQLITE_OK ){
37778    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
37779  }
37780  return rc;
37781}
37782
37783/*
37784** Shutdown the page cache.  Free all memory and close all files.
37785**
37786** If a transaction was in progress when this routine is called, that
37787** transaction is rolled back.  All outstanding pages are invalidated
37788** and their memory is freed.  Any attempt to use a page associated
37789** with this page cache after this function returns will likely
37790** result in a coredump.
37791**
37792** This function always succeeds. If a transaction is active an attempt
37793** is made to roll it back. If an error occurs during the rollback
37794** a hot journal may be left in the filesystem but no error is returned
37795** to the caller.
37796*/
37797SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
37798  u8 *pTmp = (u8 *)pPager->pTmpSpace;
37799
37800  disable_simulated_io_errors();
37801  sqlite3BeginBenignMalloc();
37802  /* pPager->errCode = 0; */
37803  pPager->exclusiveMode = 0;
37804#ifndef SQLITE_OMIT_WAL
37805  sqlite3WalClose(pPager->pWal,
37806    (pPager->noSync ? 0 : pPager->sync_flags),
37807    pPager->pageSize, pTmp
37808  );
37809  pPager->pWal = 0;
37810#endif
37811  pager_reset(pPager);
37812  if( MEMDB ){
37813    pager_unlock(pPager);
37814  }else{
37815    /* If it is open, sync the journal file before calling UnlockAndRollback.
37816    ** If this is not done, then an unsynced portion of the open journal
37817    ** file may be played back into the database. If a power failure occurs
37818    ** while this is happening, the database could become corrupt.
37819    **
37820    ** If an error occurs while trying to sync the journal, shift the pager
37821    ** into the ERROR state. This causes UnlockAndRollback to unlock the
37822    ** database and close the journal file without attempting to roll it
37823    ** back or finalize it. The next database user will have to do hot-journal
37824    ** rollback before accessing the database file.
37825    */
37826    if( isOpen(pPager->jfd) ){
37827      pager_error(pPager, pagerSyncHotJournal(pPager));
37828    }
37829    pagerUnlockAndRollback(pPager);
37830  }
37831  sqlite3EndBenignMalloc();
37832  enable_simulated_io_errors();
37833  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
37834  IOTRACE(("CLOSE %p\n", pPager))
37835  sqlite3OsClose(pPager->jfd);
37836  sqlite3OsClose(pPager->fd);
37837  sqlite3PageFree(pTmp);
37838  sqlite3PcacheClose(pPager->pPCache);
37839
37840#ifdef SQLITE_HAS_CODEC
37841  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
37842#endif
37843
37844  assert( !pPager->aSavepoint && !pPager->pInJournal );
37845  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
37846
37847  sqlite3_free(pPager);
37848  return SQLITE_OK;
37849}
37850
37851#if !defined(NDEBUG) || defined(SQLITE_TEST)
37852/*
37853** Return the page number for page pPg.
37854*/
37855SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
37856  return pPg->pgno;
37857}
37858#endif
37859
37860/*
37861** Increment the reference count for page pPg.
37862*/
37863SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
37864  sqlite3PcacheRef(pPg);
37865}
37866
37867/*
37868** Sync the journal. In other words, make sure all the pages that have
37869** been written to the journal have actually reached the surface of the
37870** disk and can be restored in the event of a hot-journal rollback.
37871**
37872** If the Pager.noSync flag is set, then this function is a no-op.
37873** Otherwise, the actions required depend on the journal-mode and the
37874** device characteristics of the the file-system, as follows:
37875**
37876**   * If the journal file is an in-memory journal file, no action need
37877**     be taken.
37878**
37879**   * Otherwise, if the device does not support the SAFE_APPEND property,
37880**     then the nRec field of the most recently written journal header
37881**     is updated to contain the number of journal records that have
37882**     been written following it. If the pager is operating in full-sync
37883**     mode, then the journal file is synced before this field is updated.
37884**
37885**   * If the device does not support the SEQUENTIAL property, then
37886**     journal file is synced.
37887**
37888** Or, in pseudo-code:
37889**
37890**   if( NOT <in-memory journal> ){
37891**     if( NOT SAFE_APPEND ){
37892**       if( <full-sync mode> ) xSync(<journal file>);
37893**       <update nRec field>
37894**     }
37895**     if( NOT SEQUENTIAL ) xSync(<journal file>);
37896**   }
37897**
37898** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
37899** page currently held in memory before returning SQLITE_OK. If an IO
37900** error is encountered, then the IO error code is returned to the caller.
37901*/
37902static int syncJournal(Pager *pPager, int newHdr){
37903  int rc;                         /* Return code */
37904
37905  assert( pPager->eState==PAGER_WRITER_CACHEMOD
37906       || pPager->eState==PAGER_WRITER_DBMOD
37907  );
37908  assert( assert_pager_state(pPager) );
37909  assert( !pagerUseWal(pPager) );
37910
37911  rc = sqlite3PagerExclusiveLock(pPager);
37912  if( rc!=SQLITE_OK ) return rc;
37913
37914  if( !pPager->noSync ){
37915    assert( !pPager->tempFile );
37916    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
37917      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
37918      assert( isOpen(pPager->jfd) );
37919
37920      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
37921        /* This block deals with an obscure problem. If the last connection
37922        ** that wrote to this database was operating in persistent-journal
37923        ** mode, then the journal file may at this point actually be larger
37924        ** than Pager.journalOff bytes. If the next thing in the journal
37925        ** file happens to be a journal-header (written as part of the
37926        ** previous connection's transaction), and a crash or power-failure
37927        ** occurs after nRec is updated but before this connection writes
37928        ** anything else to the journal file (or commits/rolls back its
37929        ** transaction), then SQLite may become confused when doing the
37930        ** hot-journal rollback following recovery. It may roll back all
37931        ** of this connections data, then proceed to rolling back the old,
37932        ** out-of-date data that follows it. Database corruption.
37933        **
37934        ** To work around this, if the journal file does appear to contain
37935        ** a valid header following Pager.journalOff, then write a 0x00
37936        ** byte to the start of it to prevent it from being recognized.
37937        **
37938        ** Variable iNextHdrOffset is set to the offset at which this
37939        ** problematic header will occur, if it exists. aMagic is used
37940        ** as a temporary buffer to inspect the first couple of bytes of
37941        ** the potential journal header.
37942        */
37943        i64 iNextHdrOffset;
37944        u8 aMagic[8];
37945        u8 zHeader[sizeof(aJournalMagic)+4];
37946
37947        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
37948        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
37949
37950        iNextHdrOffset = journalHdrOffset(pPager);
37951        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
37952        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
37953          static const u8 zerobyte = 0;
37954          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
37955        }
37956        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
37957          return rc;
37958        }
37959
37960        /* Write the nRec value into the journal file header. If in
37961        ** full-synchronous mode, sync the journal first. This ensures that
37962        ** all data has really hit the disk before nRec is updated to mark
37963        ** it as a candidate for rollback.
37964        **
37965        ** This is not required if the persistent media supports the
37966        ** SAFE_APPEND property. Because in this case it is not possible
37967        ** for garbage data to be appended to the file, the nRec field
37968        ** is populated with 0xFFFFFFFF when the journal header is written
37969        ** and never needs to be updated.
37970        */
37971        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37972          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
37973          IOTRACE(("JSYNC %p\n", pPager))
37974          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
37975          if( rc!=SQLITE_OK ) return rc;
37976        }
37977        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
37978        rc = sqlite3OsWrite(
37979            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
37980        );
37981        if( rc!=SQLITE_OK ) return rc;
37982      }
37983      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
37984        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
37985        IOTRACE(("JSYNC %p\n", pPager))
37986        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
37987          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
37988        );
37989        if( rc!=SQLITE_OK ) return rc;
37990      }
37991
37992      pPager->journalHdr = pPager->journalOff;
37993      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
37994        pPager->nRec = 0;
37995        rc = writeJournalHdr(pPager);
37996        if( rc!=SQLITE_OK ) return rc;
37997      }
37998    }else{
37999      pPager->journalHdr = pPager->journalOff;
38000    }
38001  }
38002
38003  /* Unless the pager is in noSync mode, the journal file was just
38004  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
38005  ** all pages.
38006  */
38007  sqlite3PcacheClearSyncFlags(pPager->pPCache);
38008  pPager->eState = PAGER_WRITER_DBMOD;
38009  assert( assert_pager_state(pPager) );
38010  return SQLITE_OK;
38011}
38012
38013/*
38014** The argument is the first in a linked list of dirty pages connected
38015** by the PgHdr.pDirty pointer. This function writes each one of the
38016** in-memory pages in the list to the database file. The argument may
38017** be NULL, representing an empty list. In this case this function is
38018** a no-op.
38019**
38020** The pager must hold at least a RESERVED lock when this function
38021** is called. Before writing anything to the database file, this lock
38022** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
38023** SQLITE_BUSY is returned and no data is written to the database file.
38024**
38025** If the pager is a temp-file pager and the actual file-system file
38026** is not yet open, it is created and opened before any data is
38027** written out.
38028**
38029** Once the lock has been upgraded and, if necessary, the file opened,
38030** the pages are written out to the database file in list order. Writing
38031** a page is skipped if it meets either of the following criteria:
38032**
38033**   * The page number is greater than Pager.dbSize, or
38034**   * The PGHDR_DONT_WRITE flag is set on the page.
38035**
38036** If writing out a page causes the database file to grow, Pager.dbFileSize
38037** is updated accordingly. If page 1 is written out, then the value cached
38038** in Pager.dbFileVers[] is updated to match the new value stored in
38039** the database file.
38040**
38041** If everything is successful, SQLITE_OK is returned. If an IO error
38042** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
38043** be obtained, SQLITE_BUSY is returned.
38044*/
38045static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
38046  int rc = SQLITE_OK;                  /* Return code */
38047
38048  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
38049  assert( !pagerUseWal(pPager) );
38050  assert( pPager->eState==PAGER_WRITER_DBMOD );
38051  assert( pPager->eLock==EXCLUSIVE_LOCK );
38052
38053  /* If the file is a temp-file has not yet been opened, open it now. It
38054  ** is not possible for rc to be other than SQLITE_OK if this branch
38055  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
38056  */
38057  if( !isOpen(pPager->fd) ){
38058    assert( pPager->tempFile && rc==SQLITE_OK );
38059    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
38060  }
38061
38062  /* Before the first write, give the VFS a hint of what the final
38063  ** file size will be.
38064  */
38065  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
38066  if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
38067    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
38068    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
38069    pPager->dbHintSize = pPager->dbSize;
38070  }
38071
38072  while( rc==SQLITE_OK && pList ){
38073    Pgno pgno = pList->pgno;
38074
38075    /* If there are dirty pages in the page cache with page numbers greater
38076    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
38077    ** make the file smaller (presumably by auto-vacuum code). Do not write
38078    ** any such pages to the file.
38079    **
38080    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
38081    ** set (set by sqlite3PagerDontWrite()).
38082    */
38083    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
38084      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
38085      char *pData;                                   /* Data to write */
38086
38087      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
38088
38089      /* Encode the database */
38090      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
38091
38092      /* Write out the page data. */
38093      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
38094
38095      /* If page 1 was just written, update Pager.dbFileVers to match
38096      ** the value now stored in the database file. If writing this
38097      ** page caused the database file to grow, update dbFileSize.
38098      */
38099      if( pgno==1 ){
38100        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
38101      }
38102      if( pgno>pPager->dbFileSize ){
38103        pPager->dbFileSize = pgno;
38104      }
38105
38106      /* Update any backup objects copying the contents of this pager. */
38107      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
38108
38109      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
38110                   PAGERID(pPager), pgno, pager_pagehash(pList)));
38111      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
38112      PAGER_INCR(sqlite3_pager_writedb_count);
38113      PAGER_INCR(pPager->nWrite);
38114    }else{
38115      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
38116    }
38117    pager_set_pagehash(pList);
38118    pList = pList->pDirty;
38119  }
38120
38121  return rc;
38122}
38123
38124/*
38125** Ensure that the sub-journal file is open. If it is already open, this
38126** function is a no-op.
38127**
38128** SQLITE_OK is returned if everything goes according to plan. An
38129** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
38130** fails.
38131*/
38132static int openSubJournal(Pager *pPager){
38133  int rc = SQLITE_OK;
38134  if( !isOpen(pPager->sjfd) ){
38135    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
38136      sqlite3MemJournalOpen(pPager->sjfd);
38137    }else{
38138      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
38139    }
38140  }
38141  return rc;
38142}
38143
38144/*
38145** Append a record of the current state of page pPg to the sub-journal.
38146** It is the callers responsibility to use subjRequiresPage() to check
38147** that it is really required before calling this function.
38148**
38149** If successful, set the bit corresponding to pPg->pgno in the bitvecs
38150** for all open savepoints before returning.
38151**
38152** This function returns SQLITE_OK if everything is successful, an IO
38153** error code if the attempt to write to the sub-journal fails, or
38154** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
38155** bitvec.
38156*/
38157static int subjournalPage(PgHdr *pPg){
38158  int rc = SQLITE_OK;
38159  Pager *pPager = pPg->pPager;
38160  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
38161
38162    /* Open the sub-journal, if it has not already been opened */
38163    assert( pPager->useJournal );
38164    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
38165    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
38166    assert( pagerUseWal(pPager)
38167         || pageInJournal(pPg)
38168         || pPg->pgno>pPager->dbOrigSize
38169    );
38170    rc = openSubJournal(pPager);
38171
38172    /* If the sub-journal was opened successfully (or was already open),
38173    ** write the journal record into the file.  */
38174    if( rc==SQLITE_OK ){
38175      void *pData = pPg->pData;
38176      i64 offset = pPager->nSubRec*(4+pPager->pageSize);
38177      char *pData2;
38178
38179      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38180      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
38181      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
38182      if( rc==SQLITE_OK ){
38183        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
38184      }
38185    }
38186  }
38187  if( rc==SQLITE_OK ){
38188    pPager->nSubRec++;
38189    assert( pPager->nSavepoint>0 );
38190    rc = addToSavepointBitvecs(pPager, pPg->pgno);
38191  }
38192  return rc;
38193}
38194
38195/*
38196** This function is called by the pcache layer when it has reached some
38197** soft memory limit. The first argument is a pointer to a Pager object
38198** (cast as a void*). The pager is always 'purgeable' (not an in-memory
38199** database). The second argument is a reference to a page that is
38200** currently dirty but has no outstanding references. The page
38201** is always associated with the Pager object passed as the first
38202** argument.
38203**
38204** The job of this function is to make pPg clean by writing its contents
38205** out to the database file, if possible. This may involve syncing the
38206** journal file.
38207**
38208** If successful, sqlite3PcacheMakeClean() is called on the page and
38209** SQLITE_OK returned. If an IO error occurs while trying to make the
38210** page clean, the IO error code is returned. If the page cannot be
38211** made clean for some other reason, but no error occurs, then SQLITE_OK
38212** is returned by sqlite3PcacheMakeClean() is not called.
38213*/
38214static int pagerStress(void *p, PgHdr *pPg){
38215  Pager *pPager = (Pager *)p;
38216  int rc = SQLITE_OK;
38217
38218  assert( pPg->pPager==pPager );
38219  assert( pPg->flags&PGHDR_DIRTY );
38220
38221  /* The doNotSyncSpill flag is set during times when doing a sync of
38222  ** journal (and adding a new header) is not allowed.  This occurs
38223  ** during calls to sqlite3PagerWrite() while trying to journal multiple
38224  ** pages belonging to the same sector.
38225  **
38226  ** The doNotSpill flag inhibits all cache spilling regardless of whether
38227  ** or not a sync is required.  This is set during a rollback.
38228  **
38229  ** Spilling is also prohibited when in an error state since that could
38230  ** lead to database corruption.   In the current implementaton it
38231  ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
38232  ** while in the error state, hence it is impossible for this routine to
38233  ** be called in the error state.  Nevertheless, we include a NEVER()
38234  ** test for the error state as a safeguard against future changes.
38235  */
38236  if( NEVER(pPager->errCode) ) return SQLITE_OK;
38237  if( pPager->doNotSpill ) return SQLITE_OK;
38238  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
38239    return SQLITE_OK;
38240  }
38241
38242  pPg->pDirty = 0;
38243  if( pagerUseWal(pPager) ){
38244    /* Write a single frame for this page to the log. */
38245    if( subjRequiresPage(pPg) ){
38246      rc = subjournalPage(pPg);
38247    }
38248    if( rc==SQLITE_OK ){
38249      rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
38250    }
38251  }else{
38252
38253    /* Sync the journal file if required. */
38254    if( pPg->flags&PGHDR_NEED_SYNC
38255     || pPager->eState==PAGER_WRITER_CACHEMOD
38256    ){
38257      rc = syncJournal(pPager, 1);
38258    }
38259
38260    /* If the page number of this page is larger than the current size of
38261    ** the database image, it may need to be written to the sub-journal.
38262    ** This is because the call to pager_write_pagelist() below will not
38263    ** actually write data to the file in this case.
38264    **
38265    ** Consider the following sequence of events:
38266    **
38267    **   BEGIN;
38268    **     <journal page X>
38269    **     <modify page X>
38270    **     SAVEPOINT sp;
38271    **       <shrink database file to Y pages>
38272    **       pagerStress(page X)
38273    **     ROLLBACK TO sp;
38274    **
38275    ** If (X>Y), then when pagerStress is called page X will not be written
38276    ** out to the database file, but will be dropped from the cache. Then,
38277    ** following the "ROLLBACK TO sp" statement, reading page X will read
38278    ** data from the database file. This will be the copy of page X as it
38279    ** was when the transaction started, not as it was when "SAVEPOINT sp"
38280    ** was executed.
38281    **
38282    ** The solution is to write the current data for page X into the
38283    ** sub-journal file now (if it is not already there), so that it will
38284    ** be restored to its current value when the "ROLLBACK TO sp" is
38285    ** executed.
38286    */
38287    if( NEVER(
38288        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
38289    ) ){
38290      rc = subjournalPage(pPg);
38291    }
38292
38293    /* Write the contents of the page out to the database file. */
38294    if( rc==SQLITE_OK ){
38295      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
38296      rc = pager_write_pagelist(pPager, pPg);
38297    }
38298  }
38299
38300  /* Mark the page as clean. */
38301  if( rc==SQLITE_OK ){
38302    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
38303    sqlite3PcacheMakeClean(pPg);
38304  }
38305
38306  return pager_error(pPager, rc);
38307}
38308
38309
38310/*
38311** Allocate and initialize a new Pager object and put a pointer to it
38312** in *ppPager. The pager should eventually be freed by passing it
38313** to sqlite3PagerClose().
38314**
38315** The zFilename argument is the path to the database file to open.
38316** If zFilename is NULL then a randomly-named temporary file is created
38317** and used as the file to be cached. Temporary files are be deleted
38318** automatically when they are closed. If zFilename is ":memory:" then
38319** all information is held in cache. It is never written to disk.
38320** This can be used to implement an in-memory database.
38321**
38322** The nExtra parameter specifies the number of bytes of space allocated
38323** along with each page reference. This space is available to the user
38324** via the sqlite3PagerGetExtra() API.
38325**
38326** The flags argument is used to specify properties that affect the
38327** operation of the pager. It should be passed some bitwise combination
38328** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
38329**
38330** The vfsFlags parameter is a bitmask to pass to the flags parameter
38331** of the xOpen() method of the supplied VFS when opening files.
38332**
38333** If the pager object is allocated and the specified file opened
38334** successfully, SQLITE_OK is returned and *ppPager set to point to
38335** the new pager object. If an error occurs, *ppPager is set to NULL
38336** and error code returned. This function may return SQLITE_NOMEM
38337** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
38338** various SQLITE_IO_XXX errors.
38339*/
38340SQLITE_PRIVATE int sqlite3PagerOpen(
38341  sqlite3_vfs *pVfs,       /* The virtual file system to use */
38342  Pager **ppPager,         /* OUT: Return the Pager structure here */
38343  const char *zFilename,   /* Name of the database file to open */
38344  int nExtra,              /* Extra bytes append to each in-memory page */
38345  int flags,               /* flags controlling this file */
38346  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
38347  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
38348){
38349  u8 *pPtr;
38350  Pager *pPager = 0;       /* Pager object to allocate and return */
38351  int rc = SQLITE_OK;      /* Return code */
38352  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
38353  int memDb = 0;           /* True if this is an in-memory file */
38354  int readOnly = 0;        /* True if this is a read-only file */
38355  int journalFileSize;     /* Bytes to allocate for each journal fd */
38356  char *zPathname = 0;     /* Full path to database file */
38357  int nPathname = 0;       /* Number of bytes in zPathname */
38358  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
38359  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
38360  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
38361  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
38362
38363  /* Figure out how much space is required for each journal file-handle
38364  ** (there are two of them, the main journal and the sub-journal). This
38365  ** is the maximum space required for an in-memory journal file handle
38366  ** and a regular journal file-handle. Note that a "regular journal-handle"
38367  ** may be a wrapper capable of caching the first portion of the journal
38368  ** file in memory to implement the atomic-write optimization (see
38369  ** source file journal.c).
38370  */
38371  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
38372    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
38373  }else{
38374    journalFileSize = ROUND8(sqlite3MemJournalSize());
38375  }
38376
38377  /* Set the output variable to NULL in case an error occurs. */
38378  *ppPager = 0;
38379
38380  /* Compute and store the full pathname in an allocated buffer pointed
38381  ** to by zPathname, length nPathname. Or, if this is a temporary file,
38382  ** leave both nPathname and zPathname set to 0.
38383  */
38384  if( zFilename && zFilename[0] ){
38385    nPathname = pVfs->mxPathname+1;
38386    zPathname = sqlite3Malloc(nPathname*2);
38387    if( zPathname==0 ){
38388      return SQLITE_NOMEM;
38389    }
38390#ifndef SQLITE_OMIT_MEMORYDB
38391    if( strcmp(zFilename,":memory:")==0 ){
38392      memDb = 1;
38393      zPathname[0] = 0;
38394    }else
38395#endif
38396    {
38397      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38398      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
38399    }
38400
38401    nPathname = sqlite3Strlen30(zPathname);
38402    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
38403      /* This branch is taken when the journal path required by
38404      ** the database being opened will be more than pVfs->mxPathname
38405      ** bytes in length. This means the database cannot be opened,
38406      ** as it will not be possible to open the journal file or even
38407      ** check for a hot-journal before reading.
38408      */
38409      rc = SQLITE_CANTOPEN_BKPT;
38410    }
38411    if( rc!=SQLITE_OK ){
38412      sqlite3_free(zPathname);
38413      return rc;
38414    }
38415  }
38416
38417  /* Allocate memory for the Pager structure, PCache object, the
38418  ** three file descriptors, the database file name and the journal
38419  ** file name. The layout in memory is as follows:
38420  **
38421  **     Pager object                    (sizeof(Pager) bytes)
38422  **     PCache object                   (sqlite3PcacheSize() bytes)
38423  **     Database file handle            (pVfs->szOsFile bytes)
38424  **     Sub-journal file handle         (journalFileSize bytes)
38425  **     Main journal file handle        (journalFileSize bytes)
38426  **     Database file name              (nPathname+1 bytes)
38427  **     Journal file name               (nPathname+8+1 bytes)
38428  */
38429  pPtr = (u8 *)sqlite3MallocZero(
38430    ROUND8(sizeof(*pPager)) +      /* Pager structure */
38431    ROUND8(pcacheSize) +           /* PCache object */
38432    ROUND8(pVfs->szOsFile) +       /* The main db file */
38433    journalFileSize * 2 +          /* The two journal files */
38434    nPathname + 1 +                /* zFilename */
38435    nPathname + 8 + 1              /* zJournal */
38436#ifndef SQLITE_OMIT_WAL
38437    + nPathname + 4 + 1              /* zWal */
38438#endif
38439  );
38440  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
38441  if( !pPtr ){
38442    sqlite3_free(zPathname);
38443    return SQLITE_NOMEM;
38444  }
38445  pPager =              (Pager*)(pPtr);
38446  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
38447  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
38448  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
38449  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
38450  pPager->zFilename =    (char*)(pPtr += journalFileSize);
38451  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
38452
38453  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
38454  if( zPathname ){
38455    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
38456    memcpy(pPager->zFilename, zPathname, nPathname);
38457    memcpy(pPager->zJournal, zPathname, nPathname);
38458    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
38459    if( pPager->zFilename[0]==0 ){
38460      pPager->zJournal[0] = 0;
38461    }
38462#ifndef SQLITE_OMIT_WAL
38463    else{
38464      pPager->zWal = &pPager->zJournal[nPathname+8+1];
38465      memcpy(pPager->zWal, zPathname, nPathname);
38466      memcpy(&pPager->zWal[nPathname], "-wal", 4);
38467    }
38468#endif
38469    sqlite3_free(zPathname);
38470  }
38471  pPager->pVfs = pVfs;
38472  pPager->vfsFlags = vfsFlags;
38473
38474  /* Open the pager file.
38475  */
38476  if( zFilename && zFilename[0] && !memDb ){
38477    int fout = 0;                    /* VFS flags returned by xOpen() */
38478    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
38479    readOnly = (fout&SQLITE_OPEN_READONLY);
38480
38481    /* If the file was successfully opened for read/write access,
38482    ** choose a default page size in case we have to create the
38483    ** database file. The default page size is the maximum of:
38484    **
38485    **    + SQLITE_DEFAULT_PAGE_SIZE,
38486    **    + The value returned by sqlite3OsSectorSize()
38487    **    + The largest page size that can be written atomically.
38488    */
38489    if( rc==SQLITE_OK && !readOnly ){
38490      setSectorSize(pPager);
38491      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
38492      if( szPageDflt<pPager->sectorSize ){
38493        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
38494          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
38495        }else{
38496          szPageDflt = (u32)pPager->sectorSize;
38497        }
38498      }
38499#ifdef SQLITE_ENABLE_ATOMIC_WRITE
38500      {
38501        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
38502        int ii;
38503        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38504        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38505        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
38506        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
38507          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
38508            szPageDflt = ii;
38509          }
38510        }
38511      }
38512#endif
38513    }
38514  }else{
38515    /* If a temporary file is requested, it is not opened immediately.
38516    ** In this case we accept the default page size and delay actually
38517    ** opening the file until the first call to OsWrite().
38518    **
38519    ** This branch is also run for an in-memory database. An in-memory
38520    ** database is the same as a temp-file that is never written out to
38521    ** disk and uses an in-memory rollback journal.
38522    */
38523    tempFile = 1;
38524    pPager->eState = PAGER_READER;
38525    pPager->eLock = EXCLUSIVE_LOCK;
38526    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
38527  }
38528
38529  /* The following call to PagerSetPagesize() serves to set the value of
38530  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
38531  */
38532  if( rc==SQLITE_OK ){
38533    assert( pPager->memDb==0 );
38534    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
38535    testcase( rc!=SQLITE_OK );
38536  }
38537
38538  /* If an error occurred in either of the blocks above, free the
38539  ** Pager structure and close the file.
38540  */
38541  if( rc!=SQLITE_OK ){
38542    assert( !pPager->pTmpSpace );
38543    sqlite3OsClose(pPager->fd);
38544    sqlite3_free(pPager);
38545    return rc;
38546  }
38547
38548  /* Initialize the PCache object. */
38549  assert( nExtra<1000 );
38550  nExtra = ROUND8(nExtra);
38551  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
38552                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
38553
38554  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
38555  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
38556
38557  pPager->useJournal = (u8)useJournal;
38558  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
38559  /* pPager->stmtOpen = 0; */
38560  /* pPager->stmtInUse = 0; */
38561  /* pPager->nRef = 0; */
38562  /* pPager->stmtSize = 0; */
38563  /* pPager->stmtJSize = 0; */
38564  /* pPager->nPage = 0; */
38565  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
38566  /* pPager->state = PAGER_UNLOCK; */
38567#if 0
38568  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
38569#endif
38570  /* pPager->errMask = 0; */
38571  pPager->tempFile = (u8)tempFile;
38572  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
38573          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
38574  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
38575  pPager->exclusiveMode = (u8)tempFile;
38576  pPager->changeCountDone = pPager->tempFile;
38577  pPager->memDb = (u8)memDb;
38578  pPager->readOnly = (u8)readOnly;
38579  assert( useJournal || pPager->tempFile );
38580  pPager->noSync = pPager->tempFile;
38581  pPager->fullSync = pPager->noSync ?0:1;
38582  pPager->sync_flags = SQLITE_SYNC_NORMAL;
38583  /* pPager->pFirst = 0; */
38584  /* pPager->pFirstSynced = 0; */
38585  /* pPager->pLast = 0; */
38586  pPager->nExtra = (u16)nExtra;
38587  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
38588  assert( isOpen(pPager->fd) || tempFile );
38589  setSectorSize(pPager);
38590  if( !useJournal ){
38591    pPager->journalMode = PAGER_JOURNALMODE_OFF;
38592  }else if( memDb ){
38593    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
38594  }
38595  /* pPager->xBusyHandler = 0; */
38596  /* pPager->pBusyHandlerArg = 0; */
38597  pPager->xReiniter = xReinit;
38598  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
38599
38600  *ppPager = pPager;
38601  return SQLITE_OK;
38602}
38603
38604
38605
38606/*
38607** This function is called after transitioning from PAGER_UNLOCK to
38608** PAGER_SHARED state. It tests if there is a hot journal present in
38609** the file-system for the given pager. A hot journal is one that
38610** needs to be played back. According to this function, a hot-journal
38611** file exists if the following criteria are met:
38612**
38613**   * The journal file exists in the file system, and
38614**   * No process holds a RESERVED or greater lock on the database file, and
38615**   * The database file itself is greater than 0 bytes in size, and
38616**   * The first byte of the journal file exists and is not 0x00.
38617**
38618** If the current size of the database file is 0 but a journal file
38619** exists, that is probably an old journal left over from a prior
38620** database with the same name. In this case the journal file is
38621** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
38622** is returned.
38623**
38624** This routine does not check if there is a master journal filename
38625** at the end of the file. If there is, and that master journal file
38626** does not exist, then the journal file is not really hot. In this
38627** case this routine will return a false-positive. The pager_playback()
38628** routine will discover that the journal file is not really hot and
38629** will not roll it back.
38630**
38631** If a hot-journal file is found to exist, *pExists is set to 1 and
38632** SQLITE_OK returned. If no hot-journal file is present, *pExists is
38633** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
38634** to determine whether or not a hot-journal file exists, the IO error
38635** code is returned and the value of *pExists is undefined.
38636*/
38637static int hasHotJournal(Pager *pPager, int *pExists){
38638  sqlite3_vfs * const pVfs = pPager->pVfs;
38639  int rc = SQLITE_OK;           /* Return code */
38640  int exists = 1;               /* True if a journal file is present */
38641  int jrnlOpen = !!isOpen(pPager->jfd);
38642
38643  assert( pPager->useJournal );
38644  assert( isOpen(pPager->fd) );
38645  assert( pPager->eState==PAGER_OPEN );
38646
38647  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
38648    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
38649  ));
38650
38651  *pExists = 0;
38652  if( !jrnlOpen ){
38653    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
38654  }
38655  if( rc==SQLITE_OK && exists ){
38656    int locked = 0;             /* True if some process holds a RESERVED lock */
38657
38658    /* Race condition here:  Another process might have been holding the
38659    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
38660    ** call above, but then delete the journal and drop the lock before
38661    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
38662    ** is the case, this routine might think there is a hot journal when
38663    ** in fact there is none.  This results in a false-positive which will
38664    ** be dealt with by the playback routine.  Ticket #3883.
38665    */
38666    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
38667    if( rc==SQLITE_OK && !locked ){
38668      Pgno nPage;                 /* Number of pages in database file */
38669
38670      /* Check the size of the database file. If it consists of 0 pages,
38671      ** then delete the journal file. See the header comment above for
38672      ** the reasoning here.  Delete the obsolete journal file under
38673      ** a RESERVED lock to avoid race conditions and to avoid violating
38674      ** [H33020].
38675      */
38676      rc = pagerPagecount(pPager, &nPage);
38677      if( rc==SQLITE_OK ){
38678        if( nPage==0 ){
38679          sqlite3BeginBenignMalloc();
38680          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
38681            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
38682            pagerUnlockDb(pPager, SHARED_LOCK);
38683          }
38684          sqlite3EndBenignMalloc();
38685        }else{
38686          /* The journal file exists and no other connection has a reserved
38687          ** or greater lock on the database file. Now check that there is
38688          ** at least one non-zero bytes at the start of the journal file.
38689          ** If there is, then we consider this journal to be hot. If not,
38690          ** it can be ignored.
38691          */
38692          if( !jrnlOpen ){
38693            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
38694            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
38695          }
38696          if( rc==SQLITE_OK ){
38697            u8 first = 0;
38698            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
38699            if( rc==SQLITE_IOERR_SHORT_READ ){
38700              rc = SQLITE_OK;
38701            }
38702            if( !jrnlOpen ){
38703              sqlite3OsClose(pPager->jfd);
38704            }
38705            *pExists = (first!=0);
38706          }else if( rc==SQLITE_CANTOPEN ){
38707            /* If we cannot open the rollback journal file in order to see if
38708            ** its has a zero header, that might be due to an I/O error, or
38709            ** it might be due to the race condition described above and in
38710            ** ticket #3883.  Either way, assume that the journal is hot.
38711            ** This might be a false positive.  But if it is, then the
38712            ** automatic journal playback and recovery mechanism will deal
38713            ** with it under an EXCLUSIVE lock where we do not need to
38714            ** worry so much with race conditions.
38715            */
38716            *pExists = 1;
38717            rc = SQLITE_OK;
38718          }
38719        }
38720      }
38721    }
38722  }
38723
38724  return rc;
38725}
38726
38727/*
38728** This function is called to obtain a shared lock on the database file.
38729** It is illegal to call sqlite3PagerAcquire() until after this function
38730** has been successfully called. If a shared-lock is already held when
38731** this function is called, it is a no-op.
38732**
38733** The following operations are also performed by this function.
38734**
38735**   1) If the pager is currently in PAGER_OPEN state (no lock held
38736**      on the database file), then an attempt is made to obtain a
38737**      SHARED lock on the database file. Immediately after obtaining
38738**      the SHARED lock, the file-system is checked for a hot-journal,
38739**      which is played back if present. Following any hot-journal
38740**      rollback, the contents of the cache are validated by checking
38741**      the 'change-counter' field of the database file header and
38742**      discarded if they are found to be invalid.
38743**
38744**   2) If the pager is running in exclusive-mode, and there are currently
38745**      no outstanding references to any pages, and is in the error state,
38746**      then an attempt is made to clear the error state by discarding
38747**      the contents of the page cache and rolling back any open journal
38748**      file.
38749**
38750** If everything is successful, SQLITE_OK is returned. If an IO error
38751** occurs while locking the database, checking for a hot-journal file or
38752** rolling back a journal file, the IO error code is returned.
38753*/
38754SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
38755  int rc = SQLITE_OK;                /* Return code */
38756
38757  /* This routine is only called from b-tree and only when there are no
38758  ** outstanding pages. This implies that the pager state should either
38759  ** be OPEN or READER. READER is only possible if the pager is or was in
38760  ** exclusive access mode.
38761  */
38762  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
38763  assert( assert_pager_state(pPager) );
38764  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
38765  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
38766
38767  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
38768    int bHotJournal = 1;          /* True if there exists a hot journal-file */
38769
38770    assert( !MEMDB );
38771    assert( pPager->noReadlock==0 || pPager->readOnly );
38772
38773    if( pPager->noReadlock==0 ){
38774      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
38775      if( rc!=SQLITE_OK ){
38776        assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
38777        goto failed;
38778      }
38779    }
38780
38781    /* If a journal file exists, and there is no RESERVED lock on the
38782    ** database file, then it either needs to be played back or deleted.
38783    */
38784    if( pPager->eLock<=SHARED_LOCK ){
38785      rc = hasHotJournal(pPager, &bHotJournal);
38786    }
38787    if( rc!=SQLITE_OK ){
38788      goto failed;
38789    }
38790    if( bHotJournal ){
38791      /* Get an EXCLUSIVE lock on the database file. At this point it is
38792      ** important that a RESERVED lock is not obtained on the way to the
38793      ** EXCLUSIVE lock. If it were, another process might open the
38794      ** database file, detect the RESERVED lock, and conclude that the
38795      ** database is safe to read while this process is still rolling the
38796      ** hot-journal back.
38797      **
38798      ** Because the intermediate RESERVED lock is not requested, any
38799      ** other process attempting to access the database file will get to
38800      ** this point in the code and fail to obtain its own EXCLUSIVE lock
38801      ** on the database file.
38802      **
38803      ** Unless the pager is in locking_mode=exclusive mode, the lock is
38804      ** downgraded to SHARED_LOCK before this function returns.
38805      */
38806      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
38807      if( rc!=SQLITE_OK ){
38808        goto failed;
38809      }
38810
38811      /* If it is not already open and the file exists on disk, open the
38812      ** journal for read/write access. Write access is required because
38813      ** in exclusive-access mode the file descriptor will be kept open
38814      ** and possibly used for a transaction later on. Also, write-access
38815      ** is usually required to finalize the journal in journal_mode=persist
38816      ** mode (and also for journal_mode=truncate on some systems).
38817      **
38818      ** If the journal does not exist, it usually means that some
38819      ** other connection managed to get in and roll it back before
38820      ** this connection obtained the exclusive lock above. Or, it
38821      ** may mean that the pager was in the error-state when this
38822      ** function was called and the journal file does not exist.
38823      */
38824      if( !isOpen(pPager->jfd) ){
38825        sqlite3_vfs * const pVfs = pPager->pVfs;
38826        int bExists;              /* True if journal file exists */
38827        rc = sqlite3OsAccess(
38828            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
38829        if( rc==SQLITE_OK && bExists ){
38830          int fout = 0;
38831          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
38832          assert( !pPager->tempFile );
38833          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
38834          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
38835          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
38836            rc = SQLITE_CANTOPEN_BKPT;
38837            sqlite3OsClose(pPager->jfd);
38838          }
38839        }
38840      }
38841
38842      /* Playback and delete the journal.  Drop the database write
38843      ** lock and reacquire the read lock. Purge the cache before
38844      ** playing back the hot-journal so that we don't end up with
38845      ** an inconsistent cache.  Sync the hot journal before playing
38846      ** it back since the process that crashed and left the hot journal
38847      ** probably did not sync it and we are required to always sync
38848      ** the journal before playing it back.
38849      */
38850      if( isOpen(pPager->jfd) ){
38851        assert( rc==SQLITE_OK );
38852        rc = pagerSyncHotJournal(pPager);
38853        if( rc==SQLITE_OK ){
38854          rc = pager_playback(pPager, 1);
38855          pPager->eState = PAGER_OPEN;
38856        }
38857      }else if( !pPager->exclusiveMode ){
38858        pagerUnlockDb(pPager, SHARED_LOCK);
38859      }
38860
38861      if( rc!=SQLITE_OK ){
38862        /* This branch is taken if an error occurs while trying to open
38863        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
38864        ** pager_unlock() routine will be called before returning to unlock
38865        ** the file. If the unlock attempt fails, then Pager.eLock must be
38866        ** set to UNKNOWN_LOCK (see the comment above the #define for
38867        ** UNKNOWN_LOCK above for an explanation).
38868        **
38869        ** In order to get pager_unlock() to do this, set Pager.eState to
38870        ** PAGER_ERROR now. This is not actually counted as a transition
38871        ** to ERROR state in the state diagram at the top of this file,
38872        ** since we know that the same call to pager_unlock() will very
38873        ** shortly transition the pager object to the OPEN state. Calling
38874        ** assert_pager_state() would fail now, as it should not be possible
38875        ** to be in ERROR state when there are zero outstanding page
38876        ** references.
38877        */
38878        pager_error(pPager, rc);
38879        goto failed;
38880      }
38881
38882      assert( pPager->eState==PAGER_OPEN );
38883      assert( (pPager->eLock==SHARED_LOCK)
38884           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
38885      );
38886    }
38887
38888    if( !pPager->tempFile
38889     && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
38890    ){
38891      /* The shared-lock has just been acquired on the database file
38892      ** and there are already pages in the cache (from a previous
38893      ** read or write transaction).  Check to see if the database
38894      ** has been modified.  If the database has changed, flush the
38895      ** cache.
38896      **
38897      ** Database changes is detected by looking at 15 bytes beginning
38898      ** at offset 24 into the file.  The first 4 of these 16 bytes are
38899      ** a 32-bit counter that is incremented with each change.  The
38900      ** other bytes change randomly with each file change when
38901      ** a codec is in use.
38902      **
38903      ** There is a vanishingly small chance that a change will not be
38904      ** detected.  The chance of an undetected change is so small that
38905      ** it can be neglected.
38906      */
38907      Pgno nPage = 0;
38908      char dbFileVers[sizeof(pPager->dbFileVers)];
38909
38910      rc = pagerPagecount(pPager, &nPage);
38911      if( rc ) goto failed;
38912
38913      if( nPage>0 ){
38914        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
38915        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
38916        if( rc!=SQLITE_OK ){
38917          goto failed;
38918        }
38919      }else{
38920        memset(dbFileVers, 0, sizeof(dbFileVers));
38921      }
38922
38923      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
38924        pager_reset(pPager);
38925      }
38926    }
38927
38928    /* If there is a WAL file in the file-system, open this database in WAL
38929    ** mode. Otherwise, the following function call is a no-op.
38930    */
38931    rc = pagerOpenWalIfPresent(pPager);
38932    assert( pPager->pWal==0 || rc==SQLITE_OK );
38933  }
38934
38935  if( pagerUseWal(pPager) ){
38936    assert( rc==SQLITE_OK );
38937    rc = pagerBeginReadTransaction(pPager);
38938  }
38939
38940  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
38941    rc = pagerPagecount(pPager, &pPager->dbSize);
38942  }
38943
38944 failed:
38945  if( rc!=SQLITE_OK ){
38946    assert( !MEMDB );
38947    pager_unlock(pPager);
38948    assert( pPager->eState==PAGER_OPEN );
38949  }else{
38950    pPager->eState = PAGER_READER;
38951  }
38952  return rc;
38953}
38954
38955/*
38956** If the reference count has reached zero, rollback any active
38957** transaction and unlock the pager.
38958**
38959** Except, in locking_mode=EXCLUSIVE when there is nothing to in
38960** the rollback journal, the unlock is not performed and there is
38961** nothing to rollback, so this routine is a no-op.
38962*/
38963static void pagerUnlockIfUnused(Pager *pPager){
38964  if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
38965    pagerUnlockAndRollback(pPager);
38966  }
38967}
38968
38969/*
38970** Acquire a reference to page number pgno in pager pPager (a page
38971** reference has type DbPage*). If the requested reference is
38972** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
38973**
38974** If the requested page is already in the cache, it is returned.
38975** Otherwise, a new page object is allocated and populated with data
38976** read from the database file. In some cases, the pcache module may
38977** choose not to allocate a new page object and may reuse an existing
38978** object with no outstanding references.
38979**
38980** The extra data appended to a page is always initialized to zeros the
38981** first time a page is loaded into memory. If the page requested is
38982** already in the cache when this function is called, then the extra
38983** data is left as it was when the page object was last used.
38984**
38985** If the database image is smaller than the requested page or if a
38986** non-zero value is passed as the noContent parameter and the
38987** requested page is not already stored in the cache, then no
38988** actual disk read occurs. In this case the memory image of the
38989** page is initialized to all zeros.
38990**
38991** If noContent is true, it means that we do not care about the contents
38992** of the page. This occurs in two seperate scenarios:
38993**
38994**   a) When reading a free-list leaf page from the database, and
38995**
38996**   b) When a savepoint is being rolled back and we need to load
38997**      a new page into the cache to be filled with the data read
38998**      from the savepoint journal.
38999**
39000** If noContent is true, then the data returned is zeroed instead of
39001** being read from the database. Additionally, the bits corresponding
39002** to pgno in Pager.pInJournal (bitvec of pages already written to the
39003** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
39004** savepoints are set. This means if the page is made writable at any
39005** point in the future, using a call to sqlite3PagerWrite(), its contents
39006** will not be journaled. This saves IO.
39007**
39008** The acquisition might fail for several reasons.  In all cases,
39009** an appropriate error code is returned and *ppPage is set to NULL.
39010**
39011** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
39012** to find a page in the in-memory cache first.  If the page is not already
39013** in memory, this routine goes to disk to read it in whereas Lookup()
39014** just returns 0.  This routine acquires a read-lock the first time it
39015** has to go to disk, and could also playback an old journal if necessary.
39016** Since Lookup() never goes to disk, it never has to deal with locks
39017** or journal files.
39018*/
39019SQLITE_PRIVATE int sqlite3PagerAcquire(
39020  Pager *pPager,      /* The pager open on the database file */
39021  Pgno pgno,          /* Page number to fetch */
39022  DbPage **ppPage,    /* Write a pointer to the page here */
39023  int noContent       /* Do not bother reading content from disk if true */
39024){
39025  int rc;
39026  PgHdr *pPg;
39027
39028  assert( pPager->eState>=PAGER_READER );
39029  assert( assert_pager_state(pPager) );
39030
39031  if( pgno==0 ){
39032    return SQLITE_CORRUPT_BKPT;
39033  }
39034
39035  /* If the pager is in the error state, return an error immediately.
39036  ** Otherwise, request the page from the PCache layer. */
39037  if( pPager->errCode!=SQLITE_OK ){
39038    rc = pPager->errCode;
39039  }else{
39040    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
39041  }
39042
39043  if( rc!=SQLITE_OK ){
39044    /* Either the call to sqlite3PcacheFetch() returned an error or the
39045    ** pager was already in the error-state when this function was called.
39046    ** Set pPg to 0 and jump to the exception handler.  */
39047    pPg = 0;
39048    goto pager_acquire_err;
39049  }
39050  assert( (*ppPage)->pgno==pgno );
39051  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
39052
39053  if( (*ppPage)->pPager && !noContent ){
39054    /* In this case the pcache already contains an initialized copy of
39055    ** the page. Return without further ado.  */
39056    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
39057    PAGER_INCR(pPager->nHit);
39058    return SQLITE_OK;
39059
39060  }else{
39061    /* The pager cache has created a new page. Its content needs to
39062    ** be initialized.  */
39063
39064    PAGER_INCR(pPager->nMiss);
39065    pPg = *ppPage;
39066    pPg->pPager = pPager;
39067
39068    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
39069    ** number greater than this, or the unused locking-page, is requested. */
39070    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
39071      rc = SQLITE_CORRUPT_BKPT;
39072      goto pager_acquire_err;
39073    }
39074
39075    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
39076      if( pgno>pPager->mxPgno ){
39077        rc = SQLITE_FULL;
39078        goto pager_acquire_err;
39079      }
39080      if( noContent ){
39081        /* Failure to set the bits in the InJournal bit-vectors is benign.
39082        ** It merely means that we might do some extra work to journal a
39083        ** page that does not need to be journaled.  Nevertheless, be sure
39084        ** to test the case where a malloc error occurs while trying to set
39085        ** a bit in a bit vector.
39086        */
39087        sqlite3BeginBenignMalloc();
39088        if( pgno<=pPager->dbOrigSize ){
39089          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
39090          testcase( rc==SQLITE_NOMEM );
39091        }
39092        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
39093        testcase( rc==SQLITE_NOMEM );
39094        sqlite3EndBenignMalloc();
39095      }
39096      memset(pPg->pData, 0, pPager->pageSize);
39097      IOTRACE(("ZERO %p %d\n", pPager, pgno));
39098    }else{
39099      assert( pPg->pPager==pPager );
39100      rc = readDbPage(pPg);
39101      if( rc!=SQLITE_OK ){
39102        goto pager_acquire_err;
39103      }
39104    }
39105    pager_set_pagehash(pPg);
39106  }
39107
39108  return SQLITE_OK;
39109
39110pager_acquire_err:
39111  assert( rc!=SQLITE_OK );
39112  if( pPg ){
39113    sqlite3PcacheDrop(pPg);
39114  }
39115  pagerUnlockIfUnused(pPager);
39116
39117  *ppPage = 0;
39118  return rc;
39119}
39120
39121/*
39122** Acquire a page if it is already in the in-memory cache.  Do
39123** not read the page from disk.  Return a pointer to the page,
39124** or 0 if the page is not in cache.
39125**
39126** See also sqlite3PagerGet().  The difference between this routine
39127** and sqlite3PagerGet() is that _get() will go to the disk and read
39128** in the page if the page is not already in cache.  This routine
39129** returns NULL if the page is not in cache or if a disk I/O error
39130** has ever happened.
39131*/
39132SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
39133  PgHdr *pPg = 0;
39134  assert( pPager!=0 );
39135  assert( pgno!=0 );
39136  assert( pPager->pPCache!=0 );
39137  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
39138  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
39139  return pPg;
39140}
39141
39142/*
39143** Release a page reference.
39144**
39145** If the number of references to the page drop to zero, then the
39146** page is added to the LRU list.  When all references to all pages
39147** are released, a rollback occurs and the lock on the database is
39148** removed.
39149*/
39150SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
39151  if( pPg ){
39152    Pager *pPager = pPg->pPager;
39153    sqlite3PcacheRelease(pPg);
39154    pagerUnlockIfUnused(pPager);
39155  }
39156}
39157
39158/*
39159** This function is called at the start of every write transaction.
39160** There must already be a RESERVED or EXCLUSIVE lock on the database
39161** file when this routine is called.
39162**
39163** Open the journal file for pager pPager and write a journal header
39164** to the start of it. If there are active savepoints, open the sub-journal
39165** as well. This function is only used when the journal file is being
39166** opened to write a rollback log for a transaction. It is not used
39167** when opening a hot journal file to roll it back.
39168**
39169** If the journal file is already open (as it may be in exclusive mode),
39170** then this function just writes a journal header to the start of the
39171** already open file.
39172**
39173** Whether or not the journal file is opened by this function, the
39174** Pager.pInJournal bitvec structure is allocated.
39175**
39176** Return SQLITE_OK if everything is successful. Otherwise, return
39177** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
39178** an IO error code if opening or writing the journal file fails.
39179*/
39180static int pager_open_journal(Pager *pPager){
39181  int rc = SQLITE_OK;                        /* Return code */
39182  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
39183
39184  assert( pPager->eState==PAGER_WRITER_LOCKED );
39185  assert( assert_pager_state(pPager) );
39186  assert( pPager->pInJournal==0 );
39187
39188  /* If already in the error state, this function is a no-op.  But on
39189  ** the other hand, this routine is never called if we are already in
39190  ** an error state. */
39191  if( NEVER(pPager->errCode) ) return pPager->errCode;
39192
39193  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
39194    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
39195    if( pPager->pInJournal==0 ){
39196      return SQLITE_NOMEM;
39197    }
39198
39199    /* Open the journal file if it is not already open. */
39200    if( !isOpen(pPager->jfd) ){
39201      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
39202        sqlite3MemJournalOpen(pPager->jfd);
39203      }else{
39204        const int flags =                   /* VFS flags to open journal file */
39205          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
39206          (pPager->tempFile ?
39207            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
39208            (SQLITE_OPEN_MAIN_JOURNAL)
39209          );
39210  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39211        rc = sqlite3JournalOpen(
39212            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
39213        );
39214  #else
39215        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
39216  #endif
39217      }
39218      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39219    }
39220
39221
39222    /* Write the first journal header to the journal file and open
39223    ** the sub-journal if necessary.
39224    */
39225    if( rc==SQLITE_OK ){
39226      /* TODO: Check if all of these are really required. */
39227      pPager->nRec = 0;
39228      pPager->journalOff = 0;
39229      pPager->setMaster = 0;
39230      pPager->journalHdr = 0;
39231      rc = writeJournalHdr(pPager);
39232    }
39233  }
39234
39235  if( rc!=SQLITE_OK ){
39236    sqlite3BitvecDestroy(pPager->pInJournal);
39237    pPager->pInJournal = 0;
39238  }else{
39239    assert( pPager->eState==PAGER_WRITER_LOCKED );
39240    pPager->eState = PAGER_WRITER_CACHEMOD;
39241  }
39242
39243  return rc;
39244}
39245
39246/*
39247** Begin a write-transaction on the specified pager object. If a
39248** write-transaction has already been opened, this function is a no-op.
39249**
39250** If the exFlag argument is false, then acquire at least a RESERVED
39251** lock on the database file. If exFlag is true, then acquire at least
39252** an EXCLUSIVE lock. If such a lock is already held, no locking
39253** functions need be called.
39254**
39255** If the subjInMemory argument is non-zero, then any sub-journal opened
39256** within this transaction will be opened as an in-memory file. This
39257** has no effect if the sub-journal is already opened (as it may be when
39258** running in exclusive mode) or if the transaction does not require a
39259** sub-journal. If the subjInMemory argument is zero, then any required
39260** sub-journal is implemented in-memory if pPager is an in-memory database,
39261** or using a temporary file otherwise.
39262*/
39263SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
39264  int rc = SQLITE_OK;
39265
39266  if( pPager->errCode ) return pPager->errCode;
39267  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
39268  pPager->subjInMemory = (u8)subjInMemory;
39269
39270  if( ALWAYS(pPager->eState==PAGER_READER) ){
39271    assert( pPager->pInJournal==0 );
39272
39273    if( pagerUseWal(pPager) ){
39274      /* If the pager is configured to use locking_mode=exclusive, and an
39275      ** exclusive lock on the database is not already held, obtain it now.
39276      */
39277      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
39278        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
39279        if( rc!=SQLITE_OK ){
39280          return rc;
39281        }
39282        sqlite3WalExclusiveMode(pPager->pWal, 1);
39283      }
39284
39285      /* Grab the write lock on the log file. If successful, upgrade to
39286      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
39287      ** The busy-handler is not invoked if another connection already
39288      ** holds the write-lock. If possible, the upper layer will call it.
39289      */
39290      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
39291    }else{
39292      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
39293      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
39294      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
39295      ** lock, but not when obtaining the RESERVED lock.
39296      */
39297      rc = pagerLockDb(pPager, RESERVED_LOCK);
39298      if( rc==SQLITE_OK && exFlag ){
39299        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39300      }
39301    }
39302
39303    if( rc==SQLITE_OK ){
39304      /* Change to WRITER_LOCKED state.
39305      **
39306      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
39307      ** when it has an open transaction, but never to DBMOD or FINISHED.
39308      ** This is because in those states the code to roll back savepoint
39309      ** transactions may copy data from the sub-journal into the database
39310      ** file as well as into the page cache. Which would be incorrect in
39311      ** WAL mode.
39312      */
39313      pPager->eState = PAGER_WRITER_LOCKED;
39314      pPager->dbHintSize = pPager->dbSize;
39315      pPager->dbFileSize = pPager->dbSize;
39316      pPager->dbOrigSize = pPager->dbSize;
39317      pPager->journalOff = 0;
39318    }
39319
39320    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
39321    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
39322    assert( assert_pager_state(pPager) );
39323  }
39324
39325  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
39326  return rc;
39327}
39328
39329/*
39330** Mark a single data page as writeable. The page is written into the
39331** main journal or sub-journal as required. If the page is written into
39332** one of the journals, the corresponding bit is set in the
39333** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
39334** of any open savepoints as appropriate.
39335*/
39336static int pager_write(PgHdr *pPg){
39337  void *pData = pPg->pData;
39338  Pager *pPager = pPg->pPager;
39339  int rc = SQLITE_OK;
39340
39341  /* This routine is not called unless a write-transaction has already
39342  ** been started. The journal file may or may not be open at this point.
39343  ** It is never called in the ERROR state.
39344  */
39345  assert( pPager->eState==PAGER_WRITER_LOCKED
39346       || pPager->eState==PAGER_WRITER_CACHEMOD
39347       || pPager->eState==PAGER_WRITER_DBMOD
39348  );
39349  assert( assert_pager_state(pPager) );
39350
39351  /* If an error has been previously detected, report the same error
39352  ** again. This should not happen, but the check provides robustness. */
39353  if( NEVER(pPager->errCode) )  return pPager->errCode;
39354
39355  /* Higher-level routines never call this function if database is not
39356  ** writable.  But check anyway, just for robustness. */
39357  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
39358
39359  CHECK_PAGE(pPg);
39360
39361  /* Mark the page as dirty.  If the page has already been written
39362  ** to the journal then we can return right away.
39363  */
39364  sqlite3PcacheMakeDirty(pPg);
39365  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
39366    assert( !pagerUseWal(pPager) );
39367    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
39368  }else{
39369
39370    /* If we get this far, it means that the page needs to be
39371    ** written to the transaction journal or the checkpoint journal
39372    ** or both.
39373    **
39374    ** Higher level routines have already obtained the necessary locks
39375    ** to begin the write-transaction, but the rollback journal might not
39376    ** yet be open. Open it now if this is the case.
39377    */
39378    if( pPager->eState==PAGER_WRITER_LOCKED ){
39379      rc = pager_open_journal(pPager);
39380      if( rc!=SQLITE_OK ) return rc;
39381    }
39382    assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
39383    assert( assert_pager_state(pPager) );
39384
39385    /* The transaction journal now exists and we have a RESERVED or an
39386    ** EXCLUSIVE lock on the main database file.  Write the current page to
39387    ** the transaction journal if it is not there already.
39388    */
39389    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
39390      assert( pagerUseWal(pPager)==0 );
39391      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
39392        u32 cksum;
39393        char *pData2;
39394        i64 iOff = pPager->journalOff;
39395
39396        /* We should never write to the journal file the page that
39397        ** contains the database locks.  The following assert verifies
39398        ** that we do not. */
39399        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
39400
39401        assert( pPager->journalHdr<=pPager->journalOff );
39402        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
39403        cksum = pager_cksum(pPager, (u8*)pData2);
39404
39405        /* Even if an IO or diskfull error occurs while journalling the
39406        ** page in the block above, set the need-sync flag for the page.
39407        ** Otherwise, when the transaction is rolled back, the logic in
39408        ** playback_one_page() will think that the page needs to be restored
39409        ** in the database file. And if an IO error occurs while doing so,
39410        ** then corruption may follow.
39411        */
39412        pPg->flags |= PGHDR_NEED_SYNC;
39413
39414        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
39415        if( rc!=SQLITE_OK ) return rc;
39416        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
39417        if( rc!=SQLITE_OK ) return rc;
39418        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
39419        if( rc!=SQLITE_OK ) return rc;
39420
39421        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
39422                 pPager->journalOff, pPager->pageSize));
39423        PAGER_INCR(sqlite3_pager_writej_count);
39424        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
39425             PAGERID(pPager), pPg->pgno,
39426             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
39427
39428        pPager->journalOff += 8 + pPager->pageSize;
39429        pPager->nRec++;
39430        assert( pPager->pInJournal!=0 );
39431        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
39432        testcase( rc==SQLITE_NOMEM );
39433        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39434        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
39435        if( rc!=SQLITE_OK ){
39436          assert( rc==SQLITE_NOMEM );
39437          return rc;
39438        }
39439      }else{
39440        if( pPager->eState!=PAGER_WRITER_DBMOD ){
39441          pPg->flags |= PGHDR_NEED_SYNC;
39442        }
39443        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
39444                PAGERID(pPager), pPg->pgno,
39445               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
39446      }
39447    }
39448
39449    /* If the statement journal is open and the page is not in it,
39450    ** then write the current page to the statement journal.  Note that
39451    ** the statement journal format differs from the standard journal format
39452    ** in that it omits the checksums and the header.
39453    */
39454    if( subjRequiresPage(pPg) ){
39455      rc = subjournalPage(pPg);
39456    }
39457  }
39458
39459  /* Update the database size and return.
39460  */
39461  if( pPager->dbSize<pPg->pgno ){
39462    pPager->dbSize = pPg->pgno;
39463  }
39464  return rc;
39465}
39466
39467/*
39468** Mark a data page as writeable. This routine must be called before
39469** making changes to a page. The caller must check the return value
39470** of this function and be careful not to change any page data unless
39471** this routine returns SQLITE_OK.
39472**
39473** The difference between this function and pager_write() is that this
39474** function also deals with the special case where 2 or more pages
39475** fit on a single disk sector. In this case all co-resident pages
39476** must have been written to the journal file before returning.
39477**
39478** If an error occurs, SQLITE_NOMEM or an IO error code is returned
39479** as appropriate. Otherwise, SQLITE_OK.
39480*/
39481SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
39482  int rc = SQLITE_OK;
39483
39484  PgHdr *pPg = pDbPage;
39485  Pager *pPager = pPg->pPager;
39486  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
39487
39488  assert( pPager->eState>=PAGER_WRITER_LOCKED );
39489  assert( pPager->eState!=PAGER_ERROR );
39490  assert( assert_pager_state(pPager) );
39491
39492  if( nPagePerSector>1 ){
39493    Pgno nPageCount;          /* Total number of pages in database file */
39494    Pgno pg1;                 /* First page of the sector pPg is located on. */
39495    int nPage = 0;            /* Number of pages starting at pg1 to journal */
39496    int ii;                   /* Loop counter */
39497    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
39498
39499    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
39500    ** a journal header to be written between the pages journaled by
39501    ** this function.
39502    */
39503    assert( !MEMDB );
39504    assert( pPager->doNotSyncSpill==0 );
39505    pPager->doNotSyncSpill++;
39506
39507    /* This trick assumes that both the page-size and sector-size are
39508    ** an integer power of 2. It sets variable pg1 to the identifier
39509    ** of the first page of the sector pPg is located on.
39510    */
39511    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
39512
39513    nPageCount = pPager->dbSize;
39514    if( pPg->pgno>nPageCount ){
39515      nPage = (pPg->pgno - pg1)+1;
39516    }else if( (pg1+nPagePerSector-1)>nPageCount ){
39517      nPage = nPageCount+1-pg1;
39518    }else{
39519      nPage = nPagePerSector;
39520    }
39521    assert(nPage>0);
39522    assert(pg1<=pPg->pgno);
39523    assert((pg1+nPage)>pPg->pgno);
39524
39525    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
39526      Pgno pg = pg1+ii;
39527      PgHdr *pPage;
39528      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
39529        if( pg!=PAGER_MJ_PGNO(pPager) ){
39530          rc = sqlite3PagerGet(pPager, pg, &pPage);
39531          if( rc==SQLITE_OK ){
39532            rc = pager_write(pPage);
39533            if( pPage->flags&PGHDR_NEED_SYNC ){
39534              needSync = 1;
39535            }
39536            sqlite3PagerUnref(pPage);
39537          }
39538        }
39539      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
39540        if( pPage->flags&PGHDR_NEED_SYNC ){
39541          needSync = 1;
39542        }
39543        sqlite3PagerUnref(pPage);
39544      }
39545    }
39546
39547    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
39548    ** starting at pg1, then it needs to be set for all of them. Because
39549    ** writing to any of these nPage pages may damage the others, the
39550    ** journal file must contain sync()ed copies of all of them
39551    ** before any of them can be written out to the database file.
39552    */
39553    if( rc==SQLITE_OK && needSync ){
39554      assert( !MEMDB );
39555      for(ii=0; ii<nPage; ii++){
39556        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
39557        if( pPage ){
39558          pPage->flags |= PGHDR_NEED_SYNC;
39559          sqlite3PagerUnref(pPage);
39560        }
39561      }
39562    }
39563
39564    assert( pPager->doNotSyncSpill==1 );
39565    pPager->doNotSyncSpill--;
39566  }else{
39567    rc = pager_write(pDbPage);
39568  }
39569  return rc;
39570}
39571
39572/*
39573** Return TRUE if the page given in the argument was previously passed
39574** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
39575** to change the content of the page.
39576*/
39577#ifndef NDEBUG
39578SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
39579  return pPg->flags&PGHDR_DIRTY;
39580}
39581#endif
39582
39583/*
39584** A call to this routine tells the pager that it is not necessary to
39585** write the information on page pPg back to the disk, even though
39586** that page might be marked as dirty.  This happens, for example, when
39587** the page has been added as a leaf of the freelist and so its
39588** content no longer matters.
39589**
39590** The overlying software layer calls this routine when all of the data
39591** on the given page is unused. The pager marks the page as clean so
39592** that it does not get written to disk.
39593**
39594** Tests show that this optimization can quadruple the speed of large
39595** DELETE operations.
39596*/
39597SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
39598  Pager *pPager = pPg->pPager;
39599  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
39600    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
39601    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
39602    pPg->flags |= PGHDR_DONT_WRITE;
39603    pager_set_pagehash(pPg);
39604  }
39605}
39606
39607/*
39608** This routine is called to increment the value of the database file
39609** change-counter, stored as a 4-byte big-endian integer starting at
39610** byte offset 24 of the pager file.
39611**
39612** If the isDirectMode flag is zero, then this is done by calling
39613** sqlite3PagerWrite() on page 1, then modifying the contents of the
39614** page data. In this case the file will be updated when the current
39615** transaction is committed.
39616**
39617** The isDirectMode flag may only be non-zero if the library was compiled
39618** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
39619** if isDirect is non-zero, then the database file is updated directly
39620** by writing an updated version of page 1 using a call to the
39621** sqlite3OsWrite() function.
39622*/
39623static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
39624  int rc = SQLITE_OK;
39625
39626  assert( pPager->eState==PAGER_WRITER_CACHEMOD
39627       || pPager->eState==PAGER_WRITER_DBMOD
39628  );
39629  assert( assert_pager_state(pPager) );
39630
39631  /* Declare and initialize constant integer 'isDirect'. If the
39632  ** atomic-write optimization is enabled in this build, then isDirect
39633  ** is initialized to the value passed as the isDirectMode parameter
39634  ** to this function. Otherwise, it is always set to zero.
39635  **
39636  ** The idea is that if the atomic-write optimization is not
39637  ** enabled at compile time, the compiler can omit the tests of
39638  ** 'isDirect' below, as well as the block enclosed in the
39639  ** "if( isDirect )" condition.
39640  */
39641#ifndef SQLITE_ENABLE_ATOMIC_WRITE
39642# define DIRECT_MODE 0
39643  assert( isDirectMode==0 );
39644  UNUSED_PARAMETER(isDirectMode);
39645#else
39646# define DIRECT_MODE isDirectMode
39647#endif
39648
39649  if( !pPager->changeCountDone && pPager->dbSize>0 ){
39650    PgHdr *pPgHdr;                /* Reference to page 1 */
39651    u32 change_counter;           /* Initial value of change-counter field */
39652
39653    assert( !pPager->tempFile && isOpen(pPager->fd) );
39654
39655    /* Open page 1 of the file for writing. */
39656    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
39657    assert( pPgHdr==0 || rc==SQLITE_OK );
39658
39659    /* If page one was fetched successfully, and this function is not
39660    ** operating in direct-mode, make page 1 writable.  When not in
39661    ** direct mode, page 1 is always held in cache and hence the PagerGet()
39662    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
39663    */
39664    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
39665      rc = sqlite3PagerWrite(pPgHdr);
39666    }
39667
39668    if( rc==SQLITE_OK ){
39669      /* Increment the value just read and write it back to byte 24. */
39670      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
39671      change_counter++;
39672      put32bits(((char*)pPgHdr->pData)+24, change_counter);
39673
39674      /* Also store the SQLite version number in bytes 96..99 and in
39675      ** bytes 92..95 store the change counter for which the version number
39676      ** is valid. */
39677      put32bits(((char*)pPgHdr->pData)+92, change_counter);
39678      put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
39679
39680      /* If running in direct mode, write the contents of page 1 to the file. */
39681      if( DIRECT_MODE ){
39682        const void *zBuf;
39683        assert( pPager->dbFileSize>0 );
39684        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
39685        if( rc==SQLITE_OK ){
39686          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
39687        }
39688        if( rc==SQLITE_OK ){
39689          pPager->changeCountDone = 1;
39690        }
39691      }else{
39692        pPager->changeCountDone = 1;
39693      }
39694    }
39695
39696    /* Release the page reference. */
39697    sqlite3PagerUnref(pPgHdr);
39698  }
39699  return rc;
39700}
39701
39702/*
39703** Sync the pager file to disk. This is a no-op for in-memory files
39704** or pages with the Pager.noSync flag set.
39705**
39706** If successful, or called on a pager for which it is a no-op, this
39707** function returns SQLITE_OK. Otherwise, an IO error code is returned.
39708*/
39709SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
39710  int rc;                              /* Return code */
39711  assert( !MEMDB );
39712  if( pPager->noSync ){
39713    rc = SQLITE_OK;
39714  }else{
39715    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
39716  }
39717  return rc;
39718}
39719
39720/*
39721** This function may only be called while a write-transaction is active in
39722** rollback. If the connection is in WAL mode, this call is a no-op.
39723** Otherwise, if the connection does not already have an EXCLUSIVE lock on
39724** the database file, an attempt is made to obtain one.
39725**
39726** If the EXCLUSIVE lock is already held or the attempt to obtain it is
39727** successful, or the connection is in WAL mode, SQLITE_OK is returned.
39728** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
39729** returned.
39730*/
39731SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
39732  int rc = SQLITE_OK;
39733  assert( pPager->eState==PAGER_WRITER_CACHEMOD
39734       || pPager->eState==PAGER_WRITER_DBMOD
39735       || pPager->eState==PAGER_WRITER_LOCKED
39736  );
39737  assert( assert_pager_state(pPager) );
39738  if( 0==pagerUseWal(pPager) ){
39739    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39740  }
39741  return rc;
39742}
39743
39744/*
39745** Sync the database file for the pager pPager. zMaster points to the name
39746** of a master journal file that should be written into the individual
39747** journal file. zMaster may be NULL, which is interpreted as no master
39748** journal (a single database transaction).
39749**
39750** This routine ensures that:
39751**
39752**   * The database file change-counter is updated,
39753**   * the journal is synced (unless the atomic-write optimization is used),
39754**   * all dirty pages are written to the database file,
39755**   * the database file is truncated (if required), and
39756**   * the database file synced.
39757**
39758** The only thing that remains to commit the transaction is to finalize
39759** (delete, truncate or zero the first part of) the journal file (or
39760** delete the master journal file if specified).
39761**
39762** Note that if zMaster==NULL, this does not overwrite a previous value
39763** passed to an sqlite3PagerCommitPhaseOne() call.
39764**
39765** If the final parameter - noSync - is true, then the database file itself
39766** is not synced. The caller must call sqlite3PagerSync() directly to
39767** sync the database file before calling CommitPhaseTwo() to delete the
39768** journal file in this case.
39769*/
39770SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
39771  Pager *pPager,                  /* Pager object */
39772  const char *zMaster,            /* If not NULL, the master journal name */
39773  int noSync                      /* True to omit the xSync on the db file */
39774){
39775  int rc = SQLITE_OK;             /* Return code */
39776
39777  assert( pPager->eState==PAGER_WRITER_LOCKED
39778       || pPager->eState==PAGER_WRITER_CACHEMOD
39779       || pPager->eState==PAGER_WRITER_DBMOD
39780       || pPager->eState==PAGER_ERROR
39781  );
39782  assert( assert_pager_state(pPager) );
39783
39784  /* If a prior error occurred, report that error again. */
39785  if( NEVER(pPager->errCode) ) return pPager->errCode;
39786
39787  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
39788      pPager->zFilename, zMaster, pPager->dbSize));
39789
39790  /* If no database changes have been made, return early. */
39791  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
39792
39793  if( MEMDB ){
39794    /* If this is an in-memory db, or no pages have been written to, or this
39795    ** function has already been called, it is mostly a no-op.  However, any
39796    ** backup in progress needs to be restarted.
39797    */
39798    sqlite3BackupRestart(pPager->pBackup);
39799  }else{
39800    if( pagerUseWal(pPager) ){
39801      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
39802      if( pList ){
39803        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
39804            (pPager->fullSync ? pPager->sync_flags : 0)
39805        );
39806      }
39807      if( rc==SQLITE_OK ){
39808        sqlite3PcacheCleanAll(pPager->pPCache);
39809      }
39810    }else{
39811      /* The following block updates the change-counter. Exactly how it
39812      ** does this depends on whether or not the atomic-update optimization
39813      ** was enabled at compile time, and if this transaction meets the
39814      ** runtime criteria to use the operation:
39815      **
39816      **    * The file-system supports the atomic-write property for
39817      **      blocks of size page-size, and
39818      **    * This commit is not part of a multi-file transaction, and
39819      **    * Exactly one page has been modified and store in the journal file.
39820      **
39821      ** If the optimization was not enabled at compile time, then the
39822      ** pager_incr_changecounter() function is called to update the change
39823      ** counter in 'indirect-mode'. If the optimization is compiled in but
39824      ** is not applicable to this transaction, call sqlite3JournalCreate()
39825      ** to make sure the journal file has actually been created, then call
39826      ** pager_incr_changecounter() to update the change-counter in indirect
39827      ** mode.
39828      **
39829      ** Otherwise, if the optimization is both enabled and applicable,
39830      ** then call pager_incr_changecounter() to update the change-counter
39831      ** in 'direct' mode. In this case the journal file will never be
39832      ** created for this transaction.
39833      */
39834  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39835      PgHdr *pPg;
39836      assert( isOpen(pPager->jfd)
39837           || pPager->journalMode==PAGER_JOURNALMODE_OFF
39838           || pPager->journalMode==PAGER_JOURNALMODE_WAL
39839      );
39840      if( !zMaster && isOpen(pPager->jfd)
39841       && pPager->journalOff==jrnlBufferSize(pPager)
39842       && pPager->dbSize>=pPager->dbOrigSize
39843       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
39844      ){
39845        /* Update the db file change counter via the direct-write method. The
39846        ** following call will modify the in-memory representation of page 1
39847        ** to include the updated change counter and then write page 1
39848        ** directly to the database file. Because of the atomic-write
39849        ** property of the host file-system, this is safe.
39850        */
39851        rc = pager_incr_changecounter(pPager, 1);
39852      }else{
39853        rc = sqlite3JournalCreate(pPager->jfd);
39854        if( rc==SQLITE_OK ){
39855          rc = pager_incr_changecounter(pPager, 0);
39856        }
39857      }
39858  #else
39859      rc = pager_incr_changecounter(pPager, 0);
39860  #endif
39861      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39862
39863      /* If this transaction has made the database smaller, then all pages
39864      ** being discarded by the truncation must be written to the journal
39865      ** file. This can only happen in auto-vacuum mode.
39866      **
39867      ** Before reading the pages with page numbers larger than the
39868      ** current value of Pager.dbSize, set dbSize back to the value
39869      ** that it took at the start of the transaction. Otherwise, the
39870      ** calls to sqlite3PagerGet() return zeroed pages instead of
39871      ** reading data from the database file.
39872      */
39873  #ifndef SQLITE_OMIT_AUTOVACUUM
39874      if( pPager->dbSize<pPager->dbOrigSize
39875       && pPager->journalMode!=PAGER_JOURNALMODE_OFF
39876      ){
39877        Pgno i;                                   /* Iterator variable */
39878        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
39879        const Pgno dbSize = pPager->dbSize;       /* Database image size */
39880        pPager->dbSize = pPager->dbOrigSize;
39881        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
39882          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
39883            PgHdr *pPage;             /* Page to journal */
39884            rc = sqlite3PagerGet(pPager, i, &pPage);
39885            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39886            rc = sqlite3PagerWrite(pPage);
39887            sqlite3PagerUnref(pPage);
39888            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39889          }
39890        }
39891        pPager->dbSize = dbSize;
39892      }
39893  #endif
39894
39895      /* Write the master journal name into the journal file. If a master
39896      ** journal file name has already been written to the journal file,
39897      ** or if zMaster is NULL (no master journal), then this call is a no-op.
39898      */
39899      rc = writeMasterJournal(pPager, zMaster);
39900      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39901
39902      /* Sync the journal file and write all dirty pages to the database.
39903      ** If the atomic-update optimization is being used, this sync will not
39904      ** create the journal file or perform any real IO.
39905      **
39906      ** Because the change-counter page was just modified, unless the
39907      ** atomic-update optimization is used it is almost certain that the
39908      ** journal requires a sync here. However, in locking_mode=exclusive
39909      ** on a system under memory pressure it is just possible that this is
39910      ** not the case. In this case it is likely enough that the redundant
39911      ** xSync() call will be changed to a no-op by the OS anyhow.
39912      */
39913      rc = syncJournal(pPager, 0);
39914      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39915
39916      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
39917      if( rc!=SQLITE_OK ){
39918        assert( rc!=SQLITE_IOERR_BLOCKED );
39919        goto commit_phase_one_exit;
39920      }
39921      sqlite3PcacheCleanAll(pPager->pPCache);
39922
39923      /* If the file on disk is not the same size as the database image,
39924      ** then use pager_truncate to grow or shrink the file here.
39925      */
39926      if( pPager->dbSize!=pPager->dbFileSize ){
39927        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
39928        assert( pPager->eState==PAGER_WRITER_DBMOD );
39929        rc = pager_truncate(pPager, nNew);
39930        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
39931      }
39932
39933      /* Finally, sync the database file. */
39934      if( !pPager->noSync && !noSync ){
39935        rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
39936      }
39937      IOTRACE(("DBSYNC %p\n", pPager))
39938    }
39939  }
39940
39941commit_phase_one_exit:
39942  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
39943    pPager->eState = PAGER_WRITER_FINISHED;
39944  }
39945  return rc;
39946}
39947
39948
39949/*
39950** When this function is called, the database file has been completely
39951** updated to reflect the changes made by the current transaction and
39952** synced to disk. The journal file still exists in the file-system
39953** though, and if a failure occurs at this point it will eventually
39954** be used as a hot-journal and the current transaction rolled back.
39955**
39956** This function finalizes the journal file, either by deleting,
39957** truncating or partially zeroing it, so that it cannot be used
39958** for hot-journal rollback. Once this is done the transaction is
39959** irrevocably committed.
39960**
39961** If an error occurs, an IO error code is returned and the pager
39962** moves into the error state. Otherwise, SQLITE_OK is returned.
39963*/
39964SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
39965  int rc = SQLITE_OK;                  /* Return code */
39966
39967  /* This routine should not be called if a prior error has occurred.
39968  ** But if (due to a coding error elsewhere in the system) it does get
39969  ** called, just return the same error code without doing anything. */
39970  if( NEVER(pPager->errCode) ) return pPager->errCode;
39971
39972  assert( pPager->eState==PAGER_WRITER_LOCKED
39973       || pPager->eState==PAGER_WRITER_FINISHED
39974       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
39975  );
39976  assert( assert_pager_state(pPager) );
39977
39978  /* An optimization. If the database was not actually modified during
39979  ** this transaction, the pager is running in exclusive-mode and is
39980  ** using persistent journals, then this function is a no-op.
39981  **
39982  ** The start of the journal file currently contains a single journal
39983  ** header with the nRec field set to 0. If such a journal is used as
39984  ** a hot-journal during hot-journal rollback, 0 changes will be made
39985  ** to the database file. So there is no need to zero the journal
39986  ** header. Since the pager is in exclusive mode, there is no need
39987  ** to drop any locks either.
39988  */
39989  if( pPager->eState==PAGER_WRITER_LOCKED
39990   && pPager->exclusiveMode
39991   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39992  ){
39993    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
39994    pPager->eState = PAGER_READER;
39995    return SQLITE_OK;
39996  }
39997
39998  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
39999  rc = pager_end_transaction(pPager, pPager->setMaster);
40000  return pager_error(pPager, rc);
40001}
40002
40003/*
40004** If a write transaction is open, then all changes made within the
40005** transaction are reverted and the current write-transaction is closed.
40006** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
40007** state if an error occurs.
40008**
40009** If the pager is already in PAGER_ERROR state when this function is called,
40010** it returns Pager.errCode immediately. No work is performed in this case.
40011**
40012** Otherwise, in rollback mode, this function performs two functions:
40013**
40014**   1) It rolls back the journal file, restoring all database file and
40015**      in-memory cache pages to the state they were in when the transaction
40016**      was opened, and
40017**
40018**   2) It finalizes the journal file, so that it is not used for hot
40019**      rollback at any point in the future.
40020**
40021** Finalization of the journal file (task 2) is only performed if the
40022** rollback is successful.
40023**
40024** In WAL mode, all cache-entries containing data modified within the
40025** current transaction are either expelled from the cache or reverted to
40026** their pre-transaction state by re-reading data from the database or
40027** WAL files. The WAL transaction is then closed.
40028*/
40029SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
40030  int rc = SQLITE_OK;                  /* Return code */
40031  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
40032
40033  /* PagerRollback() is a no-op if called in READER or OPEN state. If
40034  ** the pager is already in the ERROR state, the rollback is not
40035  ** attempted here. Instead, the error code is returned to the caller.
40036  */
40037  assert( assert_pager_state(pPager) );
40038  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
40039  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
40040
40041  if( pagerUseWal(pPager) ){
40042    int rc2;
40043    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
40044    rc2 = pager_end_transaction(pPager, pPager->setMaster);
40045    if( rc==SQLITE_OK ) rc = rc2;
40046  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
40047    rc = pager_end_transaction(pPager, 0);
40048  }else{
40049    rc = pager_playback(pPager, 0);
40050  }
40051
40052  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
40053  assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
40054
40055  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
40056  ** cache. So call pager_error() on the way out to make any error persistent.
40057  */
40058  return pager_error(pPager, rc);
40059}
40060
40061/*
40062** Return TRUE if the database file is opened read-only.  Return FALSE
40063** if the database is (in theory) writable.
40064*/
40065SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
40066  return pPager->readOnly;
40067}
40068
40069/*
40070** Return the number of references to the pager.
40071*/
40072SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
40073  return sqlite3PcacheRefCount(pPager->pPCache);
40074}
40075
40076/*
40077** Return the approximate number of bytes of memory currently
40078** used by the pager and its associated cache.
40079*/
40080SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
40081  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
40082                                     + 5*sizeof(void*);
40083  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
40084           + sqlite3MallocSize(pPager)
40085           + pPager->pageSize;
40086}
40087
40088/*
40089** Return the number of references to the specified page.
40090*/
40091SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
40092  return sqlite3PcachePageRefcount(pPage);
40093}
40094
40095#ifdef SQLITE_TEST
40096/*
40097** This routine is used for testing and analysis only.
40098*/
40099SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
40100  static int a[11];
40101  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
40102  a[1] = sqlite3PcachePagecount(pPager->pPCache);
40103  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
40104  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
40105  a[4] = pPager->eState;
40106  a[5] = pPager->errCode;
40107  a[6] = pPager->nHit;
40108  a[7] = pPager->nMiss;
40109  a[8] = 0;  /* Used to be pPager->nOvfl */
40110  a[9] = pPager->nRead;
40111  a[10] = pPager->nWrite;
40112  return a;
40113}
40114#endif
40115
40116/*
40117** Return true if this is an in-memory pager.
40118*/
40119SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
40120  return MEMDB;
40121}
40122
40123/*
40124** Check that there are at least nSavepoint savepoints open. If there are
40125** currently less than nSavepoints open, then open one or more savepoints
40126** to make up the difference. If the number of savepoints is already
40127** equal to nSavepoint, then this function is a no-op.
40128**
40129** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
40130** occurs while opening the sub-journal file, then an IO error code is
40131** returned. Otherwise, SQLITE_OK.
40132*/
40133SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
40134  int rc = SQLITE_OK;                       /* Return code */
40135  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
40136
40137  assert( pPager->eState>=PAGER_WRITER_LOCKED );
40138  assert( assert_pager_state(pPager) );
40139
40140  if( nSavepoint>nCurrent && pPager->useJournal ){
40141    int ii;                                 /* Iterator variable */
40142    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
40143
40144    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
40145    ** if the allocation fails. Otherwise, zero the new portion in case a
40146    ** malloc failure occurs while populating it in the for(...) loop below.
40147    */
40148    aNew = (PagerSavepoint *)sqlite3Realloc(
40149        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
40150    );
40151    if( !aNew ){
40152      return SQLITE_NOMEM;
40153    }
40154    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
40155    pPager->aSavepoint = aNew;
40156
40157    /* Populate the PagerSavepoint structures just allocated. */
40158    for(ii=nCurrent; ii<nSavepoint; ii++){
40159      aNew[ii].nOrig = pPager->dbSize;
40160      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
40161        aNew[ii].iOffset = pPager->journalOff;
40162      }else{
40163        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
40164      }
40165      aNew[ii].iSubRec = pPager->nSubRec;
40166      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
40167      if( !aNew[ii].pInSavepoint ){
40168        return SQLITE_NOMEM;
40169      }
40170      if( pagerUseWal(pPager) ){
40171        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
40172      }
40173      pPager->nSavepoint = ii+1;
40174    }
40175    assert( pPager->nSavepoint==nSavepoint );
40176    assertTruncateConstraint(pPager);
40177  }
40178
40179  return rc;
40180}
40181
40182/*
40183** This function is called to rollback or release (commit) a savepoint.
40184** The savepoint to release or rollback need not be the most recently
40185** created savepoint.
40186**
40187** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
40188** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
40189** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
40190** that have occurred since the specified savepoint was created.
40191**
40192** The savepoint to rollback or release is identified by parameter
40193** iSavepoint. A value of 0 means to operate on the outermost savepoint
40194** (the first created). A value of (Pager.nSavepoint-1) means operate
40195** on the most recently created savepoint. If iSavepoint is greater than
40196** (Pager.nSavepoint-1), then this function is a no-op.
40197**
40198** If a negative value is passed to this function, then the current
40199** transaction is rolled back. This is different to calling
40200** sqlite3PagerRollback() because this function does not terminate
40201** the transaction or unlock the database, it just restores the
40202** contents of the database to its original state.
40203**
40204** In any case, all savepoints with an index greater than iSavepoint
40205** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
40206** then savepoint iSavepoint is also destroyed.
40207**
40208** This function may return SQLITE_NOMEM if a memory allocation fails,
40209** or an IO error code if an IO error occurs while rolling back a
40210** savepoint. If no errors occur, SQLITE_OK is returned.
40211*/
40212SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
40213  int rc = pPager->errCode;       /* Return code */
40214
40215  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40216  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
40217
40218  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
40219    int ii;            /* Iterator variable */
40220    int nNew;          /* Number of remaining savepoints after this op. */
40221
40222    /* Figure out how many savepoints will still be active after this
40223    ** operation. Store this value in nNew. Then free resources associated
40224    ** with any savepoints that are destroyed by this operation.
40225    */
40226    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
40227    for(ii=nNew; ii<pPager->nSavepoint; ii++){
40228      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40229    }
40230    pPager->nSavepoint = nNew;
40231
40232    /* If this is a release of the outermost savepoint, truncate
40233    ** the sub-journal to zero bytes in size. */
40234    if( op==SAVEPOINT_RELEASE ){
40235      if( nNew==0 && isOpen(pPager->sjfd) ){
40236        /* Only truncate if it is an in-memory sub-journal. */
40237        if( sqlite3IsMemJournal(pPager->sjfd) ){
40238          rc = sqlite3OsTruncate(pPager->sjfd, 0);
40239          assert( rc==SQLITE_OK );
40240        }
40241        pPager->nSubRec = 0;
40242      }
40243    }
40244    /* Else this is a rollback operation, playback the specified savepoint.
40245    ** If this is a temp-file, it is possible that the journal file has
40246    ** not yet been opened. In this case there have been no changes to
40247    ** the database file, so the playback operation can be skipped.
40248    */
40249    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
40250      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
40251      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
40252      assert(rc!=SQLITE_DONE);
40253    }
40254  }
40255
40256  return rc;
40257}
40258
40259/*
40260** Return the full pathname of the database file.
40261*/
40262SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
40263  return pPager->zFilename;
40264}
40265
40266/*
40267** Return the VFS structure for the pager.
40268*/
40269SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
40270  return pPager->pVfs;
40271}
40272
40273/*
40274** Return the file handle for the database file associated
40275** with the pager.  This might return NULL if the file has
40276** not yet been opened.
40277*/
40278SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
40279  return pPager->fd;
40280}
40281
40282/*
40283** Return the full pathname of the journal file.
40284*/
40285SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
40286  return pPager->zJournal;
40287}
40288
40289/*
40290** Return true if fsync() calls are disabled for this pager.  Return FALSE
40291** if fsync()s are executed normally.
40292*/
40293SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
40294  return pPager->noSync;
40295}
40296
40297#ifdef SQLITE_HAS_CODEC
40298/*
40299** Set or retrieve the codec for this pager
40300*/
40301SQLITE_PRIVATE void sqlite3PagerSetCodec(
40302  Pager *pPager,
40303  void *(*xCodec)(void*,void*,Pgno,int),
40304  void (*xCodecSizeChng)(void*,int,int),
40305  void (*xCodecFree)(void*),
40306  void *pCodec
40307){
40308  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40309  pPager->xCodec = pPager->memDb ? 0 : xCodec;
40310  pPager->xCodecSizeChng = xCodecSizeChng;
40311  pPager->xCodecFree = xCodecFree;
40312  pPager->pCodec = pCodec;
40313  pagerReportSize(pPager);
40314}
40315SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
40316  return pPager->pCodec;
40317}
40318#endif
40319
40320#ifndef SQLITE_OMIT_AUTOVACUUM
40321/*
40322** Move the page pPg to location pgno in the file.
40323**
40324** There must be no references to the page previously located at
40325** pgno (which we call pPgOld) though that page is allowed to be
40326** in cache.  If the page previously located at pgno is not already
40327** in the rollback journal, it is not put there by by this routine.
40328**
40329** References to the page pPg remain valid. Updating any
40330** meta-data associated with pPg (i.e. data stored in the nExtra bytes
40331** allocated along with the page) is the responsibility of the caller.
40332**
40333** A transaction must be active when this routine is called. It used to be
40334** required that a statement transaction was not active, but this restriction
40335** has been removed (CREATE INDEX needs to move a page when a statement
40336** transaction is active).
40337**
40338** If the fourth argument, isCommit, is non-zero, then this page is being
40339** moved as part of a database reorganization just before the transaction
40340** is being committed. In this case, it is guaranteed that the database page
40341** pPg refers to will not be written to again within this transaction.
40342**
40343** This function may return SQLITE_NOMEM or an IO error code if an error
40344** occurs. Otherwise, it returns SQLITE_OK.
40345*/
40346SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
40347  PgHdr *pPgOld;               /* The page being overwritten. */
40348  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
40349  int rc;                      /* Return code */
40350  Pgno origPgno;               /* The original page number */
40351
40352  assert( pPg->nRef>0 );
40353  assert( pPager->eState==PAGER_WRITER_CACHEMOD
40354       || pPager->eState==PAGER_WRITER_DBMOD
40355  );
40356  assert( assert_pager_state(pPager) );
40357
40358  /* In order to be able to rollback, an in-memory database must journal
40359  ** the page we are moving from.
40360  */
40361  if( MEMDB ){
40362    rc = sqlite3PagerWrite(pPg);
40363    if( rc ) return rc;
40364  }
40365
40366  /* If the page being moved is dirty and has not been saved by the latest
40367  ** savepoint, then save the current contents of the page into the
40368  ** sub-journal now. This is required to handle the following scenario:
40369  **
40370  **   BEGIN;
40371  **     <journal page X, then modify it in memory>
40372  **     SAVEPOINT one;
40373  **       <Move page X to location Y>
40374  **     ROLLBACK TO one;
40375  **
40376  ** If page X were not written to the sub-journal here, it would not
40377  ** be possible to restore its contents when the "ROLLBACK TO one"
40378  ** statement were is processed.
40379  **
40380  ** subjournalPage() may need to allocate space to store pPg->pgno into
40381  ** one or more savepoint bitvecs. This is the reason this function
40382  ** may return SQLITE_NOMEM.
40383  */
40384  if( pPg->flags&PGHDR_DIRTY
40385   && subjRequiresPage(pPg)
40386   && SQLITE_OK!=(rc = subjournalPage(pPg))
40387  ){
40388    return rc;
40389  }
40390
40391  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
40392      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
40393  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
40394
40395  /* If the journal needs to be sync()ed before page pPg->pgno can
40396  ** be written to, store pPg->pgno in local variable needSyncPgno.
40397  **
40398  ** If the isCommit flag is set, there is no need to remember that
40399  ** the journal needs to be sync()ed before database page pPg->pgno
40400  ** can be written to. The caller has already promised not to write to it.
40401  */
40402  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
40403    needSyncPgno = pPg->pgno;
40404    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
40405    assert( pPg->flags&PGHDR_DIRTY );
40406  }
40407
40408  /* If the cache contains a page with page-number pgno, remove it
40409  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
40410  ** page pgno before the 'move' operation, it needs to be retained
40411  ** for the page moved there.
40412  */
40413  pPg->flags &= ~PGHDR_NEED_SYNC;
40414  pPgOld = pager_lookup(pPager, pgno);
40415  assert( !pPgOld || pPgOld->nRef==1 );
40416  if( pPgOld ){
40417    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
40418    if( MEMDB ){
40419      /* Do not discard pages from an in-memory database since we might
40420      ** need to rollback later.  Just move the page out of the way. */
40421      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
40422    }else{
40423      sqlite3PcacheDrop(pPgOld);
40424    }
40425  }
40426
40427  origPgno = pPg->pgno;
40428  sqlite3PcacheMove(pPg, pgno);
40429  sqlite3PcacheMakeDirty(pPg);
40430
40431  /* For an in-memory database, make sure the original page continues
40432  ** to exist, in case the transaction needs to roll back.  Use pPgOld
40433  ** as the original page since it has already been allocated.
40434  */
40435  if( MEMDB ){
40436    assert( pPgOld );
40437    sqlite3PcacheMove(pPgOld, origPgno);
40438    sqlite3PagerUnref(pPgOld);
40439  }
40440
40441  if( needSyncPgno ){
40442    /* If needSyncPgno is non-zero, then the journal file needs to be
40443    ** sync()ed before any data is written to database file page needSyncPgno.
40444    ** Currently, no such page exists in the page-cache and the
40445    ** "is journaled" bitvec flag has been set. This needs to be remedied by
40446    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
40447    ** flag.
40448    **
40449    ** If the attempt to load the page into the page-cache fails, (due
40450    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
40451    ** array. Otherwise, if the page is loaded and written again in
40452    ** this transaction, it may be written to the database file before
40453    ** it is synced into the journal file. This way, it may end up in
40454    ** the journal file twice, but that is not a problem.
40455    */
40456    PgHdr *pPgHdr;
40457    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
40458    if( rc!=SQLITE_OK ){
40459      if( needSyncPgno<=pPager->dbOrigSize ){
40460        assert( pPager->pTmpSpace!=0 );
40461        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
40462      }
40463      return rc;
40464    }
40465    pPgHdr->flags |= PGHDR_NEED_SYNC;
40466    sqlite3PcacheMakeDirty(pPgHdr);
40467    sqlite3PagerUnref(pPgHdr);
40468  }
40469
40470  return SQLITE_OK;
40471}
40472#endif
40473
40474/*
40475** Return a pointer to the data for the specified page.
40476*/
40477SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
40478  assert( pPg->nRef>0 || pPg->pPager->memDb );
40479  return pPg->pData;
40480}
40481
40482/*
40483** Return a pointer to the Pager.nExtra bytes of "extra" space
40484** allocated along with the specified page.
40485*/
40486SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
40487  return pPg->pExtra;
40488}
40489
40490/*
40491** Get/set the locking-mode for this pager. Parameter eMode must be one
40492** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
40493** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
40494** the locking-mode is set to the value specified.
40495**
40496** The returned value is either PAGER_LOCKINGMODE_NORMAL or
40497** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
40498** locking-mode.
40499*/
40500SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
40501  assert( eMode==PAGER_LOCKINGMODE_QUERY
40502            || eMode==PAGER_LOCKINGMODE_NORMAL
40503            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
40504  assert( PAGER_LOCKINGMODE_QUERY<0 );
40505  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
40506  if( eMode>=0 && !pPager->tempFile ){
40507    pPager->exclusiveMode = (u8)eMode;
40508  }
40509  return (int)pPager->exclusiveMode;
40510}
40511
40512/*
40513** Set the journal-mode for this pager. Parameter eMode must be one of:
40514**
40515**    PAGER_JOURNALMODE_DELETE
40516**    PAGER_JOURNALMODE_TRUNCATE
40517**    PAGER_JOURNALMODE_PERSIST
40518**    PAGER_JOURNALMODE_OFF
40519**    PAGER_JOURNALMODE_MEMORY
40520**    PAGER_JOURNALMODE_WAL
40521**
40522** The journalmode is set to the value specified if the change is allowed.
40523** The change may be disallowed for the following reasons:
40524**
40525**   *  An in-memory database can only have its journal_mode set to _OFF
40526**      or _MEMORY.
40527**
40528**   *  Temporary databases cannot have _WAL journalmode.
40529**
40530** The returned indicate the current (possibly updated) journal-mode.
40531*/
40532SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
40533  u8 eOld = pPager->journalMode;    /* Prior journalmode */
40534
40535#ifdef SQLITE_DEBUG
40536  /* The print_pager_state() routine is intended to be used by the debugger
40537  ** only.  We invoke it once here to suppress a compiler warning. */
40538  print_pager_state(pPager);
40539#endif
40540
40541
40542  /* The eMode parameter is always valid */
40543  assert(      eMode==PAGER_JOURNALMODE_DELETE
40544            || eMode==PAGER_JOURNALMODE_TRUNCATE
40545            || eMode==PAGER_JOURNALMODE_PERSIST
40546            || eMode==PAGER_JOURNALMODE_OFF
40547            || eMode==PAGER_JOURNALMODE_WAL
40548            || eMode==PAGER_JOURNALMODE_MEMORY );
40549
40550  /* This routine is only called from the OP_JournalMode opcode, and
40551  ** the logic there will never allow a temporary file to be changed
40552  ** to WAL mode.
40553  */
40554  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
40555
40556  /* Do allow the journalmode of an in-memory database to be set to
40557  ** anything other than MEMORY or OFF
40558  */
40559  if( MEMDB ){
40560    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
40561    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
40562      eMode = eOld;
40563    }
40564  }
40565
40566  if( eMode!=eOld ){
40567
40568    /* Change the journal mode. */
40569    assert( pPager->eState!=PAGER_ERROR );
40570    pPager->journalMode = (u8)eMode;
40571
40572    /* When transistioning from TRUNCATE or PERSIST to any other journal
40573    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
40574    ** delete the journal file.
40575    */
40576    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40577    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
40578    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
40579    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
40580    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
40581    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
40582
40583    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
40584    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
40585
40586      /* In this case we would like to delete the journal file. If it is
40587      ** not possible, then that is not a problem. Deleting the journal file
40588      ** here is an optimization only.
40589      **
40590      ** Before deleting the journal file, obtain a RESERVED lock on the
40591      ** database file. This ensures that the journal file is not deleted
40592      ** while it is in use by some other client.
40593      */
40594      sqlite3OsClose(pPager->jfd);
40595      if( pPager->eLock>=RESERVED_LOCK ){
40596        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40597      }else{
40598        int rc = SQLITE_OK;
40599        int state = pPager->eState;
40600        assert( state==PAGER_OPEN || state==PAGER_READER );
40601        if( state==PAGER_OPEN ){
40602          rc = sqlite3PagerSharedLock(pPager);
40603        }
40604        if( pPager->eState==PAGER_READER ){
40605          assert( rc==SQLITE_OK );
40606          rc = pagerLockDb(pPager, RESERVED_LOCK);
40607        }
40608        if( rc==SQLITE_OK ){
40609          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40610        }
40611        if( rc==SQLITE_OK && state==PAGER_READER ){
40612          pagerUnlockDb(pPager, SHARED_LOCK);
40613        }else if( state==PAGER_OPEN ){
40614          pager_unlock(pPager);
40615        }
40616        assert( state==pPager->eState );
40617      }
40618    }
40619  }
40620
40621  /* Return the new journal mode */
40622  return (int)pPager->journalMode;
40623}
40624
40625/*
40626** Return the current journal mode.
40627*/
40628SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
40629  return (int)pPager->journalMode;
40630}
40631
40632/*
40633** Return TRUE if the pager is in a state where it is OK to change the
40634** journalmode.  Journalmode changes can only happen when the database
40635** is unmodified.
40636*/
40637SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
40638  assert( assert_pager_state(pPager) );
40639  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
40640  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
40641  return 1;
40642}
40643
40644/*
40645** Get/set the size-limit used for persistent journal files.
40646**
40647** Setting the size limit to -1 means no limit is enforced.
40648** An attempt to set a limit smaller than -1 is a no-op.
40649*/
40650SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
40651  if( iLimit>=-1 ){
40652    pPager->journalSizeLimit = iLimit;
40653  }
40654  return pPager->journalSizeLimit;
40655}
40656
40657/*
40658** Return a pointer to the pPager->pBackup variable. The backup module
40659** in backup.c maintains the content of this variable. This module
40660** uses it opaquely as an argument to sqlite3BackupRestart() and
40661** sqlite3BackupUpdate() only.
40662*/
40663SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
40664  return &pPager->pBackup;
40665}
40666
40667#ifndef SQLITE_OMIT_WAL
40668/*
40669** This function is called when the user invokes "PRAGMA checkpoint".
40670*/
40671SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
40672  int rc = SQLITE_OK;
40673  if( pPager->pWal ){
40674    u8 *zBuf = (u8 *)pPager->pTmpSpace;
40675    rc = sqlite3WalCheckpoint(pPager->pWal,
40676        (pPager->noSync ? 0 : pPager->sync_flags),
40677        pPager->pageSize, zBuf
40678    );
40679  }
40680  return rc;
40681}
40682
40683SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
40684  return sqlite3WalCallback(pPager->pWal);
40685}
40686
40687/*
40688** Return true if the underlying VFS for the given pager supports the
40689** primitives necessary for write-ahead logging.
40690*/
40691SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
40692  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
40693  return pMethods->iVersion>=2 && pMethods->xShmMap!=0;
40694}
40695
40696/*
40697** The caller must be holding a SHARED lock on the database file to call
40698** this function.
40699**
40700** If the pager passed as the first argument is open on a real database
40701** file (not a temp file or an in-memory database), and the WAL file
40702** is not already open, make an attempt to open it now. If successful,
40703** return SQLITE_OK. If an error occurs or the VFS used by the pager does
40704** not support the xShmXXX() methods, return an error code. *pbOpen is
40705** not modified in either case.
40706**
40707** If the pager is open on a temp-file (or in-memory database), or if
40708** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
40709** without doing anything.
40710*/
40711SQLITE_PRIVATE int sqlite3PagerOpenWal(
40712  Pager *pPager,                  /* Pager object */
40713  int *pbOpen                     /* OUT: Set to true if call is a no-op */
40714){
40715  int rc = SQLITE_OK;             /* Return code */
40716
40717  assert( assert_pager_state(pPager) );
40718  assert( pPager->eState==PAGER_OPEN   || pbOpen );
40719  assert( pPager->eState==PAGER_READER || !pbOpen );
40720  assert( pbOpen==0 || *pbOpen==0 );
40721  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
40722
40723  if( !pPager->tempFile && !pPager->pWal ){
40724    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
40725
40726    /* Close any rollback journal previously open */
40727    sqlite3OsClose(pPager->jfd);
40728
40729    /* Open the connection to the log file. If this operation fails,
40730    ** (e.g. due to malloc() failure), unlock the database file and
40731    ** return an error code.
40732    */
40733    rc = sqlite3WalOpen(pPager->pVfs, pPager->fd, pPager->zWal, &pPager->pWal);
40734    if( rc==SQLITE_OK ){
40735      pPager->journalMode = PAGER_JOURNALMODE_WAL;
40736      pPager->eState = PAGER_OPEN;
40737    }
40738  }else{
40739    *pbOpen = 1;
40740  }
40741
40742  return rc;
40743}
40744
40745/*
40746** This function is called to close the connection to the log file prior
40747** to switching from WAL to rollback mode.
40748**
40749** Before closing the log file, this function attempts to take an
40750** EXCLUSIVE lock on the database file. If this cannot be obtained, an
40751** error (SQLITE_BUSY) is returned and the log connection is not closed.
40752** If successful, the EXCLUSIVE lock is not released before returning.
40753*/
40754SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
40755  int rc = SQLITE_OK;
40756
40757  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
40758
40759  /* If the log file is not already open, but does exist in the file-system,
40760  ** it may need to be checkpointed before the connection can switch to
40761  ** rollback mode. Open it now so this can happen.
40762  */
40763  if( !pPager->pWal ){
40764    int logexists = 0;
40765    rc = pagerLockDb(pPager, SHARED_LOCK);
40766    if( rc==SQLITE_OK ){
40767      rc = sqlite3OsAccess(
40768          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
40769      );
40770    }
40771    if( rc==SQLITE_OK && logexists ){
40772      rc = sqlite3WalOpen(pPager->pVfs, pPager->fd,
40773                          pPager->zWal, &pPager->pWal);
40774    }
40775  }
40776
40777  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
40778  ** the database file, the log and log-summary files will be deleted.
40779  */
40780  if( rc==SQLITE_OK && pPager->pWal ){
40781    rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
40782    if( rc==SQLITE_OK ){
40783      rc = sqlite3WalClose(pPager->pWal,
40784                           (pPager->noSync ? 0 : pPager->sync_flags),
40785        pPager->pageSize, (u8*)pPager->pTmpSpace
40786      );
40787      pPager->pWal = 0;
40788    }else{
40789      /* If we cannot get an EXCLUSIVE lock, downgrade the PENDING lock
40790      ** that we did get back to SHARED. */
40791      pagerUnlockDb(pPager, SQLITE_LOCK_SHARED);
40792    }
40793  }
40794  return rc;
40795}
40796
40797#ifdef SQLITE_HAS_CODEC
40798/*
40799** This function is called by the wal module when writing page content
40800** into the log file.
40801**
40802** This function returns a pointer to a buffer containing the encrypted
40803** page content. If a malloc fails, this function may return NULL.
40804*/
40805SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
40806  void *aData = 0;
40807  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
40808  return aData;
40809}
40810#endif /* SQLITE_HAS_CODEC */
40811
40812#endif /* !SQLITE_OMIT_WAL */
40813
40814#endif /* SQLITE_OMIT_DISKIO */
40815
40816/************** End of pager.c ***********************************************/
40817/************** Begin file wal.c *********************************************/
40818/*
40819** 2010 February 1
40820**
40821** The author disclaims copyright to this source code.  In place of
40822** a legal notice, here is a blessing:
40823**
40824**    May you do good and not evil.
40825**    May you find forgiveness for yourself and forgive others.
40826**    May you share freely, never taking more than you give.
40827**
40828*************************************************************************
40829**
40830** This file contains the implementation of a write-ahead log (WAL) used in
40831** "journal_mode=WAL" mode.
40832**
40833** WRITE-AHEAD LOG (WAL) FILE FORMAT
40834**
40835** A WAL file consists of a header followed by zero or more "frames".
40836** Each frame records the revised content of a single page from the
40837** database file.  All changes to the database are recorded by writing
40838** frames into the WAL.  Transactions commit when a frame is written that
40839** contains a commit marker.  A single WAL can and usually does record
40840** multiple transactions.  Periodically, the content of the WAL is
40841** transferred back into the database file in an operation called a
40842** "checkpoint".
40843**
40844** A single WAL file can be used multiple times.  In other words, the
40845** WAL can fill up with frames and then be checkpointed and then new
40846** frames can overwrite the old ones.  A WAL always grows from beginning
40847** toward the end.  Checksums and counters attached to each frame are
40848** used to determine which frames within the WAL are valid and which
40849** are leftovers from prior checkpoints.
40850**
40851** The WAL header is 32 bytes in size and consists of the following eight
40852** big-endian 32-bit unsigned integer values:
40853**
40854**     0: Magic number.  0x377f0682 or 0x377f0683
40855**     4: File format version.  Currently 3007000
40856**     8: Database page size.  Example: 1024
40857**    12: Checkpoint sequence number
40858**    16: Salt-1, random integer incremented with each checkpoint
40859**    20: Salt-2, a different random integer changing with each ckpt
40860**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
40861**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
40862**
40863** Immediately following the wal-header are zero or more frames. Each
40864** frame consists of a 24-byte frame-header followed by a <page-size> bytes
40865** of page data. The frame-header is six big-endian 32-bit unsigned
40866** integer values, as follows:
40867**
40868**     0: Page number.
40869**     4: For commit records, the size of the database image in pages
40870**        after the commit. For all other records, zero.
40871**     8: Salt-1 (copied from the header)
40872**    12: Salt-2 (copied from the header)
40873**    16: Checksum-1.
40874**    20: Checksum-2.
40875**
40876** A frame is considered valid if and only if the following conditions are
40877** true:
40878**
40879**    (1) The salt-1 and salt-2 values in the frame-header match
40880**        salt values in the wal-header
40881**
40882**    (2) The checksum values in the final 8 bytes of the frame-header
40883**        exactly match the checksum computed consecutively on the
40884**        WAL header and the first 8 bytes and the content of all frames
40885**        up to and including the current frame.
40886**
40887** The checksum is computed using 32-bit big-endian integers if the
40888** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
40889** is computed using little-endian if the magic number is 0x377f0682.
40890** The checksum values are always stored in the frame header in a
40891** big-endian format regardless of which byte order is used to compute
40892** the checksum.  The checksum is computed by interpreting the input as
40893** an even number of unsigned 32-bit integers: x[0] through x[N].  The
40894** algorithm used for the checksum is as follows:
40895**
40896**   for i from 0 to n-1 step 2:
40897**     s0 += x[i] + s1;
40898**     s1 += x[i+1] + s0;
40899**   endfor
40900**
40901** Note that s0 and s1 are both weighted checksums using fibonacci weights
40902** in reverse order (the largest fibonacci weight occurs on the first element
40903** of the sequence being summed.)  The s1 value spans all 32-bit
40904** terms of the sequence whereas s0 omits the final term.
40905**
40906** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
40907** WAL is transferred into the database, then the database is VFS.xSync-ed.
40908** The VFS.xSync operations serve as write barriers - all writes launched
40909** before the xSync must complete before any write that launches after the
40910** xSync begins.
40911**
40912** After each checkpoint, the salt-1 value is incremented and the salt-2
40913** value is randomized.  This prevents old and new frames in the WAL from
40914** being considered valid at the same time and being checkpointing together
40915** following a crash.
40916**
40917** READER ALGORITHM
40918**
40919** To read a page from the database (call it page number P), a reader
40920** first checks the WAL to see if it contains page P.  If so, then the
40921** last valid instance of page P that is a followed by a commit frame
40922** or is a commit frame itself becomes the value read.  If the WAL
40923** contains no copies of page P that are valid and which are a commit
40924** frame or are followed by a commit frame, then page P is read from
40925** the database file.
40926**
40927** To start a read transaction, the reader records the index of the last
40928** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
40929** for all subsequent read operations.  New transactions can be appended
40930** to the WAL, but as long as the reader uses its original mxFrame value
40931** and ignores the newly appended content, it will see a consistent snapshot
40932** of the database from a single point in time.  This technique allows
40933** multiple concurrent readers to view different versions of the database
40934** content simultaneously.
40935**
40936** The reader algorithm in the previous paragraphs works correctly, but
40937** because frames for page P can appear anywhere within the WAL, the
40938** reader has to scan the entire WAL looking for page P frames.  If the
40939** WAL is large (multiple megabytes is typical) that scan can be slow,
40940** and read performance suffers.  To overcome this problem, a separate
40941** data structure called the wal-index is maintained to expedite the
40942** search for frames of a particular page.
40943**
40944** WAL-INDEX FORMAT
40945**
40946** Conceptually, the wal-index is shared memory, though VFS implementations
40947** might choose to implement the wal-index using a mmapped file.  Because
40948** the wal-index is shared memory, SQLite does not support journal_mode=WAL
40949** on a network filesystem.  All users of the database must be able to
40950** share memory.
40951**
40952** The wal-index is transient.  After a crash, the wal-index can (and should
40953** be) reconstructed from the original WAL file.  In fact, the VFS is required
40954** to either truncate or zero the header of the wal-index when the last
40955** connection to it closes.  Because the wal-index is transient, it can
40956** use an architecture-specific format; it does not have to be cross-platform.
40957** Hence, unlike the database and WAL file formats which store all values
40958** as big endian, the wal-index can store multi-byte values in the native
40959** byte order of the host computer.
40960**
40961** The purpose of the wal-index is to answer this question quickly:  Given
40962** a page number P, return the index of the last frame for page P in the WAL,
40963** or return NULL if there are no frames for page P in the WAL.
40964**
40965** The wal-index consists of a header region, followed by an one or
40966** more index blocks.
40967**
40968** The wal-index header contains the total number of frames within the WAL
40969** in the the mxFrame field.
40970**
40971** Each index block except for the first contains information on
40972** HASHTABLE_NPAGE frames. The first index block contains information on
40973** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
40974** HASHTABLE_NPAGE are selected so that together the wal-index header and
40975** first index block are the same size as all other index blocks in the
40976** wal-index.
40977**
40978** Each index block contains two sections, a page-mapping that contains the
40979** database page number associated with each wal frame, and a hash-table
40980** that allows readers to query an index block for a specific page number.
40981** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
40982** for the first index block) 32-bit page numbers. The first entry in the
40983** first index-block contains the database page number corresponding to the
40984** first frame in the WAL file. The first entry in the second index block
40985** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
40986** the log, and so on.
40987**
40988** The last index block in a wal-index usually contains less than the full
40989** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
40990** depending on the contents of the WAL file. This does not change the
40991** allocated size of the page-mapping array - the page-mapping array merely
40992** contains unused entries.
40993**
40994** Even without using the hash table, the last frame for page P
40995** can be found by scanning the page-mapping sections of each index block
40996** starting with the last index block and moving toward the first, and
40997** within each index block, starting at the end and moving toward the
40998** beginning.  The first entry that equals P corresponds to the frame
40999** holding the content for that page.
41000**
41001** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
41002** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
41003** hash table for each page number in the mapping section, so the hash
41004** table is never more than half full.  The expected number of collisions
41005** prior to finding a match is 1.  Each entry of the hash table is an
41006** 1-based index of an entry in the mapping section of the same
41007** index block.   Let K be the 1-based index of the largest entry in
41008** the mapping section.  (For index blocks other than the last, K will
41009** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
41010** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
41011** contain a value of 0.
41012**
41013** To look for page P in the hash table, first compute a hash iKey on
41014** P as follows:
41015**
41016**      iKey = (P * 383) % HASHTABLE_NSLOT
41017**
41018** Then start scanning entries of the hash table, starting with iKey
41019** (wrapping around to the beginning when the end of the hash table is
41020** reached) until an unused hash slot is found. Let the first unused slot
41021** be at index iUnused.  (iUnused might be less than iKey if there was
41022** wrap-around.) Because the hash table is never more than half full,
41023** the search is guaranteed to eventually hit an unused entry.  Let
41024** iMax be the value between iKey and iUnused, closest to iUnused,
41025** where aHash[iMax]==P.  If there is no iMax entry (if there exists
41026** no hash slot such that aHash[i]==p) then page P is not in the
41027** current index block.  Otherwise the iMax-th mapping entry of the
41028** current index block corresponds to the last entry that references
41029** page P.
41030**
41031** A hash search begins with the last index block and moves toward the
41032** first index block, looking for entries corresponding to page P.  On
41033** average, only two or three slots in each index block need to be
41034** examined in order to either find the last entry for page P, or to
41035** establish that no such entry exists in the block.  Each index block
41036** holds over 4000 entries.  So two or three index blocks are sufficient
41037** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
41038** comparisons (on average) suffice to either locate a frame in the
41039** WAL or to establish that the frame does not exist in the WAL.  This
41040** is much faster than scanning the entire 10MB WAL.
41041**
41042** Note that entries are added in order of increasing K.  Hence, one
41043** reader might be using some value K0 and a second reader that started
41044** at a later time (after additional transactions were added to the WAL
41045** and to the wal-index) might be using a different value K1, where K1>K0.
41046** Both readers can use the same hash table and mapping section to get
41047** the correct result.  There may be entries in the hash table with
41048** K>K0 but to the first reader, those entries will appear to be unused
41049** slots in the hash table and so the first reader will get an answer as
41050** if no values greater than K0 had ever been inserted into the hash table
41051** in the first place - which is what reader one wants.  Meanwhile, the
41052** second reader using K1 will see additional values that were inserted
41053** later, which is exactly what reader two wants.
41054**
41055** When a rollback occurs, the value of K is decreased. Hash table entries
41056** that correspond to frames greater than the new K value are removed
41057** from the hash table at this point.
41058*/
41059#ifndef SQLITE_OMIT_WAL
41060
41061
41062/*
41063** Trace output macros
41064*/
41065#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41066SQLITE_PRIVATE int sqlite3WalTrace = 0;
41067# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
41068#else
41069# define WALTRACE(X)
41070#endif
41071
41072/*
41073** The maximum (and only) versions of the wal and wal-index formats
41074** that may be interpreted by this version of SQLite.
41075**
41076** If a client begins recovering a WAL file and finds that (a) the checksum
41077** values in the wal-header are correct and (b) the version field is not
41078** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
41079**
41080** Similarly, if a client successfully reads a wal-index header (i.e. the
41081** checksum test is successful) and finds that the version field is not
41082** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
41083** returns SQLITE_CANTOPEN.
41084*/
41085#define WAL_MAX_VERSION      3007000
41086#define WALINDEX_MAX_VERSION 3007000
41087
41088/*
41089** Indices of various locking bytes.   WAL_NREADER is the number
41090** of available reader locks and should be at least 3.
41091*/
41092#define WAL_WRITE_LOCK         0
41093#define WAL_ALL_BUT_WRITE      1
41094#define WAL_CKPT_LOCK          1
41095#define WAL_RECOVER_LOCK       2
41096#define WAL_READ_LOCK(I)       (3+(I))
41097#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
41098
41099
41100/* Object declarations */
41101typedef struct WalIndexHdr WalIndexHdr;
41102typedef struct WalIterator WalIterator;
41103typedef struct WalCkptInfo WalCkptInfo;
41104
41105
41106/*
41107** The following object holds a copy of the wal-index header content.
41108**
41109** The actual header in the wal-index consists of two copies of this
41110** object.
41111**
41112** The szPage value can be any power of 2 between 512 and 32768, inclusive.
41113** Or it can be 1 to represent a 65536-byte page.  The latter case was
41114** added in 3.7.1 when support for 64K pages was added.
41115*/
41116struct WalIndexHdr {
41117  u32 iVersion;                   /* Wal-index version */
41118  u32 unused;                     /* Unused (padding) field */
41119  u32 iChange;                    /* Counter incremented each transaction */
41120  u8 isInit;                      /* 1 when initialized */
41121  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
41122  u16 szPage;                     /* Database page size in bytes. 1==64K */
41123  u32 mxFrame;                    /* Index of last valid frame in the WAL */
41124  u32 nPage;                      /* Size of database in pages */
41125  u32 aFrameCksum[2];             /* Checksum of last frame in log */
41126  u32 aSalt[2];                   /* Two salt values copied from WAL header */
41127  u32 aCksum[2];                  /* Checksum over all prior fields */
41128};
41129
41130/*
41131** A copy of the following object occurs in the wal-index immediately
41132** following the second copy of the WalIndexHdr.  This object stores
41133** information used by checkpoint.
41134**
41135** nBackfill is the number of frames in the WAL that have been written
41136** back into the database. (We call the act of moving content from WAL to
41137** database "backfilling".)  The nBackfill number is never greater than
41138** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
41139** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
41140** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
41141** mxFrame back to zero when the WAL is reset.
41142**
41143** There is one entry in aReadMark[] for each reader lock.  If a reader
41144** holds read-lock K, then the value in aReadMark[K] is no greater than
41145** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
41146** for any aReadMark[] means that entry is unused.  aReadMark[0] is
41147** a special case; its value is never used and it exists as a place-holder
41148** to avoid having to offset aReadMark[] indexs by one.  Readers holding
41149** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
41150** directly from the database.
41151**
41152** The value of aReadMark[K] may only be changed by a thread that
41153** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
41154** aReadMark[K] cannot changed while there is a reader is using that mark
41155** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
41156**
41157** The checkpointer may only transfer frames from WAL to database where
41158** the frame numbers are less than or equal to every aReadMark[] that is
41159** in use (that is, every aReadMark[j] for which there is a corresponding
41160** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
41161** largest value and will increase an unused aReadMark[] to mxFrame if there
41162** is not already an aReadMark[] equal to mxFrame.  The exception to the
41163** previous sentence is when nBackfill equals mxFrame (meaning that everything
41164** in the WAL has been backfilled into the database) then new readers
41165** will choose aReadMark[0] which has value 0 and hence such reader will
41166** get all their all content directly from the database file and ignore
41167** the WAL.
41168**
41169** Writers normally append new frames to the end of the WAL.  However,
41170** if nBackfill equals mxFrame (meaning that all WAL content has been
41171** written back into the database) and if no readers are using the WAL
41172** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
41173** the writer will first "reset" the WAL back to the beginning and start
41174** writing new content beginning at frame 1.
41175**
41176** We assume that 32-bit loads are atomic and so no locks are needed in
41177** order to read from any aReadMark[] entries.
41178*/
41179struct WalCkptInfo {
41180  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
41181  u32 aReadMark[WAL_NREADER];     /* Reader marks */
41182};
41183#define READMARK_NOT_USED  0xffffffff
41184
41185
41186/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
41187** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
41188** only support mandatory file-locks, we do not read or write data
41189** from the region of the file on which locks are applied.
41190*/
41191#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
41192#define WALINDEX_LOCK_RESERVED 16
41193#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
41194
41195/* Size of header before each frame in wal */
41196#define WAL_FRAME_HDRSIZE 24
41197
41198/* Size of write ahead log header, including checksum. */
41199/* #define WAL_HDRSIZE 24 */
41200#define WAL_HDRSIZE 32
41201
41202/* WAL magic value. Either this value, or the same value with the least
41203** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
41204** big-endian format in the first 4 bytes of a WAL file.
41205**
41206** If the LSB is set, then the checksums for each frame within the WAL
41207** file are calculated by treating all data as an array of 32-bit
41208** big-endian words. Otherwise, they are calculated by interpreting
41209** all data as 32-bit little-endian words.
41210*/
41211#define WAL_MAGIC 0x377f0682
41212
41213/*
41214** Return the offset of frame iFrame in the write-ahead log file,
41215** assuming a database page size of szPage bytes. The offset returned
41216** is to the start of the write-ahead log frame-header.
41217*/
41218#define walFrameOffset(iFrame, szPage) (                               \
41219  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
41220)
41221
41222/*
41223** An open write-ahead log file is represented by an instance of the
41224** following object.
41225*/
41226struct Wal {
41227  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
41228  sqlite3_file *pDbFd;       /* File handle for the database file */
41229  sqlite3_file *pWalFd;      /* File handle for WAL file */
41230  u32 iCallback;             /* Value to pass to log callback (or 0) */
41231  int nWiData;               /* Size of array apWiData */
41232  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
41233  u32 szPage;                /* Database page size */
41234  i16 readLock;              /* Which read lock is being held.  -1 for none */
41235  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
41236  u8 writeLock;              /* True if in a write transaction */
41237  u8 ckptLock;               /* True if holding a checkpoint lock */
41238  u8 readOnly;               /* True if the WAL file is open read-only */
41239  WalIndexHdr hdr;           /* Wal-index header for current transaction */
41240  const char *zWalName;      /* Name of WAL file */
41241  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
41242#ifdef SQLITE_DEBUG
41243  u8 lockError;              /* True if a locking error has occurred */
41244#endif
41245};
41246
41247/*
41248** Each page of the wal-index mapping contains a hash-table made up of
41249** an array of HASHTABLE_NSLOT elements of the following type.
41250*/
41251typedef u16 ht_slot;
41252
41253/*
41254** This structure is used to implement an iterator that loops through
41255** all frames in the WAL in database page order. Where two or more frames
41256** correspond to the same database page, the iterator visits only the
41257** frame most recently written to the WAL (in other words, the frame with
41258** the largest index).
41259**
41260** The internals of this structure are only accessed by:
41261**
41262**   walIteratorInit() - Create a new iterator,
41263**   walIteratorNext() - Step an iterator,
41264**   walIteratorFree() - Free an iterator.
41265**
41266** This functionality is used by the checkpoint code (see walCheckpoint()).
41267*/
41268struct WalIterator {
41269  int iPrior;                     /* Last result returned from the iterator */
41270  int nSegment;                   /* Size of the aSegment[] array */
41271  struct WalSegment {
41272    int iNext;                    /* Next slot in aIndex[] not yet returned */
41273    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
41274    u32 *aPgno;                   /* Array of page numbers. */
41275    int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
41276    int iZero;                    /* Frame number associated with aPgno[0] */
41277  } aSegment[1];                  /* One for every 32KB page in the WAL */
41278};
41279
41280/*
41281** Define the parameters of the hash tables in the wal-index file. There
41282** is a hash-table following every HASHTABLE_NPAGE page numbers in the
41283** wal-index.
41284**
41285** Changing any of these constants will alter the wal-index format and
41286** create incompatibilities.
41287*/
41288#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
41289#define HASHTABLE_HASH_1     383                  /* Should be prime */
41290#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
41291
41292/*
41293** The block of page numbers associated with the first hash-table in a
41294** wal-index is smaller than usual. This is so that there is a complete
41295** hash-table on each aligned 32KB page of the wal-index.
41296*/
41297#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
41298
41299/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
41300#define WALINDEX_PGSZ   (                                         \
41301    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
41302)
41303
41304/*
41305** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
41306** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
41307** numbered from zero.
41308**
41309** If this call is successful, *ppPage is set to point to the wal-index
41310** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
41311** then an SQLite error code is returned and *ppPage is set to 0.
41312*/
41313static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
41314  int rc = SQLITE_OK;
41315
41316  /* Enlarge the pWal->apWiData[] array if required */
41317  if( pWal->nWiData<=iPage ){
41318    int nByte = sizeof(u32*)*(iPage+1);
41319    volatile u32 **apNew;
41320    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
41321    if( !apNew ){
41322      *ppPage = 0;
41323      return SQLITE_NOMEM;
41324    }
41325    memset((void*)&apNew[pWal->nWiData], 0,
41326           sizeof(u32*)*(iPage+1-pWal->nWiData));
41327    pWal->apWiData = apNew;
41328    pWal->nWiData = iPage+1;
41329  }
41330
41331  /* Request a pointer to the required page from the VFS */
41332  if( pWal->apWiData[iPage]==0 ){
41333    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
41334        pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
41335    );
41336  }
41337
41338  *ppPage = pWal->apWiData[iPage];
41339  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
41340  return rc;
41341}
41342
41343/*
41344** Return a pointer to the WalCkptInfo structure in the wal-index.
41345*/
41346static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
41347  assert( pWal->nWiData>0 && pWal->apWiData[0] );
41348  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
41349}
41350
41351/*
41352** Return a pointer to the WalIndexHdr structure in the wal-index.
41353*/
41354static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
41355  assert( pWal->nWiData>0 && pWal->apWiData[0] );
41356  return (volatile WalIndexHdr*)pWal->apWiData[0];
41357}
41358
41359/*
41360** The argument to this macro must be of type u32. On a little-endian
41361** architecture, it returns the u32 value that results from interpreting
41362** the 4 bytes as a big-endian value. On a big-endian architecture, it
41363** returns the value that would be produced by intepreting the 4 bytes
41364** of the input value as a little-endian integer.
41365*/
41366#define BYTESWAP32(x) ( \
41367    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
41368  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
41369)
41370
41371/*
41372** Generate or extend an 8 byte checksum based on the data in
41373** array aByte[] and the initial values of aIn[0] and aIn[1] (or
41374** initial values of 0 and 0 if aIn==NULL).
41375**
41376** The checksum is written back into aOut[] before returning.
41377**
41378** nByte must be a positive multiple of 8.
41379*/
41380static void walChecksumBytes(
41381  int nativeCksum, /* True for native byte-order, false for non-native */
41382  u8 *a,           /* Content to be checksummed */
41383  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
41384  const u32 *aIn,  /* Initial checksum value input */
41385  u32 *aOut        /* OUT: Final checksum value output */
41386){
41387  u32 s1, s2;
41388  u32 *aData = (u32 *)a;
41389  u32 *aEnd = (u32 *)&a[nByte];
41390
41391  if( aIn ){
41392    s1 = aIn[0];
41393    s2 = aIn[1];
41394  }else{
41395    s1 = s2 = 0;
41396  }
41397
41398  assert( nByte>=8 );
41399  assert( (nByte&0x00000007)==0 );
41400
41401  if( nativeCksum ){
41402    do {
41403      s1 += *aData++ + s2;
41404      s2 += *aData++ + s1;
41405    }while( aData<aEnd );
41406  }else{
41407    do {
41408      s1 += BYTESWAP32(aData[0]) + s2;
41409      s2 += BYTESWAP32(aData[1]) + s1;
41410      aData += 2;
41411    }while( aData<aEnd );
41412  }
41413
41414  aOut[0] = s1;
41415  aOut[1] = s2;
41416}
41417
41418/*
41419** Write the header information in pWal->hdr into the wal-index.
41420**
41421** The checksum on pWal->hdr is updated before it is written.
41422*/
41423static void walIndexWriteHdr(Wal *pWal){
41424  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
41425  const int nCksum = offsetof(WalIndexHdr, aCksum);
41426
41427  assert( pWal->writeLock );
41428  pWal->hdr.isInit = 1;
41429  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
41430  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
41431  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
41432  sqlite3OsShmBarrier(pWal->pDbFd);
41433  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
41434}
41435
41436/*
41437** This function encodes a single frame header and writes it to a buffer
41438** supplied by the caller. A frame-header is made up of a series of
41439** 4-byte big-endian integers, as follows:
41440**
41441**     0: Page number.
41442**     4: For commit records, the size of the database image in pages
41443**        after the commit. For all other records, zero.
41444**     8: Salt-1 (copied from the wal-header)
41445**    12: Salt-2 (copied from the wal-header)
41446**    16: Checksum-1.
41447**    20: Checksum-2.
41448*/
41449static void walEncodeFrame(
41450  Wal *pWal,                      /* The write-ahead log */
41451  u32 iPage,                      /* Database page number for frame */
41452  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
41453  u8 *aData,                      /* Pointer to page data */
41454  u8 *aFrame                      /* OUT: Write encoded frame here */
41455){
41456  int nativeCksum;                /* True for native byte-order checksums */
41457  u32 *aCksum = pWal->hdr.aFrameCksum;
41458  assert( WAL_FRAME_HDRSIZE==24 );
41459  sqlite3Put4byte(&aFrame[0], iPage);
41460  sqlite3Put4byte(&aFrame[4], nTruncate);
41461  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
41462
41463  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
41464  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
41465  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
41466
41467  sqlite3Put4byte(&aFrame[16], aCksum[0]);
41468  sqlite3Put4byte(&aFrame[20], aCksum[1]);
41469}
41470
41471/*
41472** Check to see if the frame with header in aFrame[] and content
41473** in aData[] is valid.  If it is a valid frame, fill *piPage and
41474** *pnTruncate and return true.  Return if the frame is not valid.
41475*/
41476static int walDecodeFrame(
41477  Wal *pWal,                      /* The write-ahead log */
41478  u32 *piPage,                    /* OUT: Database page number for frame */
41479  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
41480  u8 *aData,                      /* Pointer to page data (for checksum) */
41481  u8 *aFrame                      /* Frame data */
41482){
41483  int nativeCksum;                /* True for native byte-order checksums */
41484  u32 *aCksum = pWal->hdr.aFrameCksum;
41485  u32 pgno;                       /* Page number of the frame */
41486  assert( WAL_FRAME_HDRSIZE==24 );
41487
41488  /* A frame is only valid if the salt values in the frame-header
41489  ** match the salt values in the wal-header.
41490  */
41491  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
41492    return 0;
41493  }
41494
41495  /* A frame is only valid if the page number is creater than zero.
41496  */
41497  pgno = sqlite3Get4byte(&aFrame[0]);
41498  if( pgno==0 ){
41499    return 0;
41500  }
41501
41502  /* A frame is only valid if a checksum of the WAL header,
41503  ** all prior frams, the first 16 bytes of this frame-header,
41504  ** and the frame-data matches the checksum in the last 8
41505  ** bytes of this frame-header.
41506  */
41507  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
41508  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
41509  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
41510  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
41511   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
41512  ){
41513    /* Checksum failed. */
41514    return 0;
41515  }
41516
41517  /* If we reach this point, the frame is valid.  Return the page number
41518  ** and the new database size.
41519  */
41520  *piPage = pgno;
41521  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
41522  return 1;
41523}
41524
41525
41526#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41527/*
41528** Names of locks.  This routine is used to provide debugging output and is not
41529** a part of an ordinary build.
41530*/
41531static const char *walLockName(int lockIdx){
41532  if( lockIdx==WAL_WRITE_LOCK ){
41533    return "WRITE-LOCK";
41534  }else if( lockIdx==WAL_CKPT_LOCK ){
41535    return "CKPT-LOCK";
41536  }else if( lockIdx==WAL_RECOVER_LOCK ){
41537    return "RECOVER-LOCK";
41538  }else{
41539    static char zName[15];
41540    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
41541                     lockIdx-WAL_READ_LOCK(0));
41542    return zName;
41543  }
41544}
41545#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
41546
41547
41548/*
41549** Set or release locks on the WAL.  Locks are either shared or exclusive.
41550** A lock cannot be moved directly between shared and exclusive - it must go
41551** through the unlocked state first.
41552**
41553** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
41554*/
41555static int walLockShared(Wal *pWal, int lockIdx){
41556  int rc;
41557  if( pWal->exclusiveMode ) return SQLITE_OK;
41558  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
41559                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
41560  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
41561            walLockName(lockIdx), rc ? "failed" : "ok"));
41562  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
41563  return rc;
41564}
41565static void walUnlockShared(Wal *pWal, int lockIdx){
41566  if( pWal->exclusiveMode ) return;
41567  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
41568                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
41569  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
41570}
41571static int walLockExclusive(Wal *pWal, int lockIdx, int n){
41572  int rc;
41573  if( pWal->exclusiveMode ) return SQLITE_OK;
41574  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
41575                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
41576  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
41577            walLockName(lockIdx), n, rc ? "failed" : "ok"));
41578  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
41579  return rc;
41580}
41581static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
41582  if( pWal->exclusiveMode ) return;
41583  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
41584                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
41585  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
41586             walLockName(lockIdx), n));
41587}
41588
41589/*
41590** Compute a hash on a page number.  The resulting hash value must land
41591** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
41592** the hash to the next value in the event of a collision.
41593*/
41594static int walHash(u32 iPage){
41595  assert( iPage>0 );
41596  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
41597  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
41598}
41599static int walNextHash(int iPriorHash){
41600  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
41601}
41602
41603/*
41604** Return pointers to the hash table and page number array stored on
41605** page iHash of the wal-index. The wal-index is broken into 32KB pages
41606** numbered starting from 0.
41607**
41608** Set output variable *paHash to point to the start of the hash table
41609** in the wal-index file. Set *piZero to one less than the frame
41610** number of the first frame indexed by this hash table. If a
41611** slot in the hash table is set to N, it refers to frame number
41612** (*piZero+N) in the log.
41613**
41614** Finally, set *paPgno so that *paPgno[1] is the page number of the
41615** first frame indexed by the hash table, frame (*piZero+1).
41616*/
41617static int walHashGet(
41618  Wal *pWal,                      /* WAL handle */
41619  int iHash,                      /* Find the iHash'th table */
41620  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
41621  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
41622  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
41623){
41624  int rc;                         /* Return code */
41625  volatile u32 *aPgno;
41626
41627  rc = walIndexPage(pWal, iHash, &aPgno);
41628  assert( rc==SQLITE_OK || iHash>0 );
41629
41630  if( rc==SQLITE_OK ){
41631    u32 iZero;
41632    volatile ht_slot *aHash;
41633
41634    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
41635    if( iHash==0 ){
41636      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
41637      iZero = 0;
41638    }else{
41639      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
41640    }
41641
41642    *paPgno = &aPgno[-1];
41643    *paHash = aHash;
41644    *piZero = iZero;
41645  }
41646  return rc;
41647}
41648
41649/*
41650** Return the number of the wal-index page that contains the hash-table
41651** and page-number array that contain entries corresponding to WAL frame
41652** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
41653** are numbered starting from 0.
41654*/
41655static int walFramePage(u32 iFrame){
41656  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
41657  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
41658       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
41659       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
41660       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
41661       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
41662  );
41663  return iHash;
41664}
41665
41666/*
41667** Return the page number associated with frame iFrame in this WAL.
41668*/
41669static u32 walFramePgno(Wal *pWal, u32 iFrame){
41670  int iHash = walFramePage(iFrame);
41671  if( iHash==0 ){
41672    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
41673  }
41674  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
41675}
41676
41677/*
41678** Remove entries from the hash table that point to WAL slots greater
41679** than pWal->hdr.mxFrame.
41680**
41681** This function is called whenever pWal->hdr.mxFrame is decreased due
41682** to a rollback or savepoint.
41683**
41684** At most only the hash table containing pWal->hdr.mxFrame needs to be
41685** updated.  Any later hash tables will be automatically cleared when
41686** pWal->hdr.mxFrame advances to the point where those hash tables are
41687** actually needed.
41688*/
41689static void walCleanupHash(Wal *pWal){
41690  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
41691  volatile u32 *aPgno = 0;        /* Page number array for hash table */
41692  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
41693  int iLimit = 0;                 /* Zero values greater than this */
41694  int nByte;                      /* Number of bytes to zero in aPgno[] */
41695  int i;                          /* Used to iterate through aHash[] */
41696
41697  assert( pWal->writeLock );
41698  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
41699  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
41700  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
41701
41702  if( pWal->hdr.mxFrame==0 ) return;
41703
41704  /* Obtain pointers to the hash-table and page-number array containing
41705  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
41706  ** that the page said hash-table and array reside on is already mapped.
41707  */
41708  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
41709  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
41710  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
41711
41712  /* Zero all hash-table entries that correspond to frame numbers greater
41713  ** than pWal->hdr.mxFrame.
41714  */
41715  iLimit = pWal->hdr.mxFrame - iZero;
41716  assert( iLimit>0 );
41717  for(i=0; i<HASHTABLE_NSLOT; i++){
41718    if( aHash[i]>iLimit ){
41719      aHash[i] = 0;
41720    }
41721  }
41722
41723  /* Zero the entries in the aPgno array that correspond to frames with
41724  ** frame numbers greater than pWal->hdr.mxFrame.
41725  */
41726  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
41727  memset((void *)&aPgno[iLimit+1], 0, nByte);
41728
41729#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
41730  /* Verify that the every entry in the mapping region is still reachable
41731  ** via the hash table even after the cleanup.
41732  */
41733  if( iLimit ){
41734    int i;           /* Loop counter */
41735    int iKey;        /* Hash key */
41736    for(i=1; i<=iLimit; i++){
41737      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
41738        if( aHash[iKey]==i ) break;
41739      }
41740      assert( aHash[iKey]==i );
41741    }
41742  }
41743#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
41744}
41745
41746
41747/*
41748** Set an entry in the wal-index that will map database page number
41749** pPage into WAL frame iFrame.
41750*/
41751static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
41752  int rc;                         /* Return code */
41753  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
41754  volatile u32 *aPgno = 0;        /* Page number array */
41755  volatile ht_slot *aHash = 0;    /* Hash table */
41756
41757  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
41758
41759  /* Assuming the wal-index file was successfully mapped, populate the
41760  ** page number array and hash table entry.
41761  */
41762  if( rc==SQLITE_OK ){
41763    int iKey;                     /* Hash table key */
41764    int idx;                      /* Value to write to hash-table slot */
41765    int nCollide;                 /* Number of hash collisions */
41766
41767    idx = iFrame - iZero;
41768    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
41769
41770    /* If this is the first entry to be added to this hash-table, zero the
41771    ** entire hash table and aPgno[] array before proceding.
41772    */
41773    if( idx==1 ){
41774      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
41775      memset((void*)&aPgno[1], 0, nByte);
41776    }
41777
41778    /* If the entry in aPgno[] is already set, then the previous writer
41779    ** must have exited unexpectedly in the middle of a transaction (after
41780    ** writing one or more dirty pages to the WAL to free up memory).
41781    ** Remove the remnants of that writers uncommitted transaction from
41782    ** the hash-table before writing any new entries.
41783    */
41784    if( aPgno[idx] ){
41785      walCleanupHash(pWal);
41786      assert( !aPgno[idx] );
41787    }
41788
41789    /* Write the aPgno[] array entry and the hash-table slot. */
41790    nCollide = idx;
41791    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
41792      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
41793    }
41794    aPgno[idx] = iPage;
41795    aHash[iKey] = (ht_slot)idx;
41796
41797#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
41798    /* Verify that the number of entries in the hash table exactly equals
41799    ** the number of entries in the mapping region.
41800    */
41801    {
41802      int i;           /* Loop counter */
41803      int nEntry = 0;  /* Number of entries in the hash table */
41804      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
41805      assert( nEntry==idx );
41806    }
41807
41808    /* Verify that the every entry in the mapping region is reachable
41809    ** via the hash table.  This turns out to be a really, really expensive
41810    ** thing to check, so only do this occasionally - not on every
41811    ** iteration.
41812    */
41813    if( (idx&0x3ff)==0 ){
41814      int i;           /* Loop counter */
41815      for(i=1; i<=idx; i++){
41816        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
41817          if( aHash[iKey]==i ) break;
41818        }
41819        assert( aHash[iKey]==i );
41820      }
41821    }
41822#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
41823  }
41824
41825
41826  return rc;
41827}
41828
41829
41830/*
41831** Recover the wal-index by reading the write-ahead log file.
41832**
41833** This routine first tries to establish an exclusive lock on the
41834** wal-index to prevent other threads/processes from doing anything
41835** with the WAL or wal-index while recovery is running.  The
41836** WAL_RECOVER_LOCK is also held so that other threads will know
41837** that this thread is running recovery.  If unable to establish
41838** the necessary locks, this routine returns SQLITE_BUSY.
41839*/
41840static int walIndexRecover(Wal *pWal){
41841  int rc;                         /* Return Code */
41842  i64 nSize;                      /* Size of log file */
41843  u32 aFrameCksum[2] = {0, 0};
41844  int iLock;                      /* Lock offset to lock for checkpoint */
41845  int nLock;                      /* Number of locks to hold */
41846
41847  /* Obtain an exclusive lock on all byte in the locking range not already
41848  ** locked by the caller. The caller is guaranteed to have locked the
41849  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
41850  ** If successful, the same bytes that are locked here are unlocked before
41851  ** this function returns.
41852  */
41853  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
41854  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
41855  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
41856  assert( pWal->writeLock );
41857  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
41858  nLock = SQLITE_SHM_NLOCK - iLock;
41859  rc = walLockExclusive(pWal, iLock, nLock);
41860  if( rc ){
41861    return rc;
41862  }
41863  WALTRACE(("WAL%p: recovery begin...\n", pWal));
41864
41865  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
41866
41867  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
41868  if( rc!=SQLITE_OK ){
41869    goto recovery_error;
41870  }
41871
41872  if( nSize>WAL_HDRSIZE ){
41873    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
41874    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
41875    int szFrame;                  /* Number of bytes in buffer aFrame[] */
41876    u8 *aData;                    /* Pointer to data part of aFrame buffer */
41877    int iFrame;                   /* Index of last frame read */
41878    i64 iOffset;                  /* Next offset to read from log file */
41879    int szPage;                   /* Page size according to the log */
41880    u32 magic;                    /* Magic value read from WAL header */
41881    u32 version;                  /* Magic value read from WAL header */
41882
41883    /* Read in the WAL header. */
41884    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
41885    if( rc!=SQLITE_OK ){
41886      goto recovery_error;
41887    }
41888
41889    /* If the database page size is not a power of two, or is greater than
41890    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
41891    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
41892    ** WAL file.
41893    */
41894    magic = sqlite3Get4byte(&aBuf[0]);
41895    szPage = sqlite3Get4byte(&aBuf[8]);
41896    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
41897     || szPage&(szPage-1)
41898     || szPage>SQLITE_MAX_PAGE_SIZE
41899     || szPage<512
41900    ){
41901      goto finished;
41902    }
41903    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
41904    pWal->szPage = szPage;
41905    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
41906    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
41907
41908    /* Verify that the WAL header checksum is correct */
41909    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
41910        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
41911    );
41912    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
41913     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
41914    ){
41915      goto finished;
41916    }
41917
41918    /* Verify that the version number on the WAL format is one that
41919    ** are able to understand */
41920    version = sqlite3Get4byte(&aBuf[4]);
41921    if( version!=WAL_MAX_VERSION ){
41922      rc = SQLITE_CANTOPEN_BKPT;
41923      goto finished;
41924    }
41925
41926    /* Malloc a buffer to read frames into. */
41927    szFrame = szPage + WAL_FRAME_HDRSIZE;
41928    aFrame = (u8 *)sqlite3_malloc(szFrame);
41929    if( !aFrame ){
41930      rc = SQLITE_NOMEM;
41931      goto recovery_error;
41932    }
41933    aData = &aFrame[WAL_FRAME_HDRSIZE];
41934
41935    /* Read all frames from the log file. */
41936    iFrame = 0;
41937    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
41938      u32 pgno;                   /* Database page number for frame */
41939      u32 nTruncate;              /* dbsize field from frame header */
41940      int isValid;                /* True if this frame is valid */
41941
41942      /* Read and decode the next log frame. */
41943      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
41944      if( rc!=SQLITE_OK ) break;
41945      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
41946      if( !isValid ) break;
41947      rc = walIndexAppend(pWal, ++iFrame, pgno);
41948      if( rc!=SQLITE_OK ) break;
41949
41950      /* If nTruncate is non-zero, this is a commit record. */
41951      if( nTruncate ){
41952        pWal->hdr.mxFrame = iFrame;
41953        pWal->hdr.nPage = nTruncate;
41954        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
41955        testcase( szPage<=32768 );
41956        testcase( szPage>=65536 );
41957        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
41958        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
41959      }
41960    }
41961
41962    sqlite3_free(aFrame);
41963  }
41964
41965finished:
41966  if( rc==SQLITE_OK ){
41967    volatile WalCkptInfo *pInfo;
41968    int i;
41969    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
41970    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
41971    walIndexWriteHdr(pWal);
41972
41973    /* Reset the checkpoint-header. This is safe because this thread is
41974    ** currently holding locks that exclude all other readers, writers and
41975    ** checkpointers.
41976    */
41977    pInfo = walCkptInfo(pWal);
41978    pInfo->nBackfill = 0;
41979    pInfo->aReadMark[0] = 0;
41980    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
41981
41982    /* If more than one frame was recovered from the log file, report an
41983    ** event via sqlite3_log(). This is to help with identifying performance
41984    ** problems caused by applications routinely shutting down without
41985    ** checkpointing the log file.
41986    */
41987    if( pWal->hdr.nPage ){
41988      sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
41989          pWal->hdr.nPage, pWal->zWalName
41990      );
41991    }
41992  }
41993
41994recovery_error:
41995  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
41996  walUnlockExclusive(pWal, iLock, nLock);
41997  return rc;
41998}
41999
42000/*
42001** Close an open wal-index.
42002*/
42003static void walIndexClose(Wal *pWal, int isDelete){
42004  sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
42005}
42006
42007/*
42008** Open a connection to the WAL file zWalName. The database file must
42009** already be opened on connection pDbFd. The buffer that zWalName points
42010** to must remain valid for the lifetime of the returned Wal* handle.
42011**
42012** A SHARED lock should be held on the database file when this function
42013** is called. The purpose of this SHARED lock is to prevent any other
42014** client from unlinking the WAL or wal-index file. If another process
42015** were to do this just after this client opened one of these files, the
42016** system would be badly broken.
42017**
42018** If the log file is successfully opened, SQLITE_OK is returned and
42019** *ppWal is set to point to a new WAL handle. If an error occurs,
42020** an SQLite error code is returned and *ppWal is left unmodified.
42021*/
42022SQLITE_PRIVATE int sqlite3WalOpen(
42023  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
42024  sqlite3_file *pDbFd,            /* The open database file */
42025  const char *zWalName,           /* Name of the WAL file */
42026  Wal **ppWal                     /* OUT: Allocated Wal handle */
42027){
42028  int rc;                         /* Return Code */
42029  Wal *pRet;                      /* Object to allocate and return */
42030  int flags;                      /* Flags passed to OsOpen() */
42031
42032  assert( zWalName && zWalName[0] );
42033  assert( pDbFd );
42034
42035  /* In the amalgamation, the os_unix.c and os_win.c source files come before
42036  ** this source file.  Verify that the #defines of the locking byte offsets
42037  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
42038  */
42039#ifdef WIN_SHM_BASE
42040  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
42041#endif
42042#ifdef UNIX_SHM_BASE
42043  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
42044#endif
42045
42046
42047  /* Allocate an instance of struct Wal to return. */
42048  *ppWal = 0;
42049  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
42050  if( !pRet ){
42051    return SQLITE_NOMEM;
42052  }
42053
42054  pRet->pVfs = pVfs;
42055  pRet->pWalFd = (sqlite3_file *)&pRet[1];
42056  pRet->pDbFd = pDbFd;
42057  pRet->readLock = -1;
42058  pRet->zWalName = zWalName;
42059
42060  /* Open file handle on the write-ahead log file. */
42061  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
42062  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
42063  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
42064    pRet->readOnly = 1;
42065  }
42066
42067  if( rc!=SQLITE_OK ){
42068    walIndexClose(pRet, 0);
42069    sqlite3OsClose(pRet->pWalFd);
42070    sqlite3_free(pRet);
42071  }else{
42072    *ppWal = pRet;
42073    WALTRACE(("WAL%d: opened\n", pRet));
42074  }
42075  return rc;
42076}
42077
42078/*
42079** Find the smallest page number out of all pages held in the WAL that
42080** has not been returned by any prior invocation of this method on the
42081** same WalIterator object.   Write into *piFrame the frame index where
42082** that page was last written into the WAL.  Write into *piPage the page
42083** number.
42084**
42085** Return 0 on success.  If there are no pages in the WAL with a page
42086** number larger than *piPage, then return 1.
42087*/
42088static int walIteratorNext(
42089  WalIterator *p,               /* Iterator */
42090  u32 *piPage,                  /* OUT: The page number of the next page */
42091  u32 *piFrame                  /* OUT: Wal frame index of next page */
42092){
42093  u32 iMin;                     /* Result pgno must be greater than iMin */
42094  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
42095  int i;                        /* For looping through segments */
42096
42097  iMin = p->iPrior;
42098  assert( iMin<0xffffffff );
42099  for(i=p->nSegment-1; i>=0; i--){
42100    struct WalSegment *pSegment = &p->aSegment[i];
42101    while( pSegment->iNext<pSegment->nEntry ){
42102      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
42103      if( iPg>iMin ){
42104        if( iPg<iRet ){
42105          iRet = iPg;
42106          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
42107        }
42108        break;
42109      }
42110      pSegment->iNext++;
42111    }
42112  }
42113
42114  *piPage = p->iPrior = iRet;
42115  return (iRet==0xFFFFFFFF);
42116}
42117
42118/*
42119** This function merges two sorted lists into a single sorted list.
42120*/
42121static void walMerge(
42122  u32 *aContent,                  /* Pages in wal */
42123  ht_slot *aLeft,                 /* IN: Left hand input list */
42124  int nLeft,                      /* IN: Elements in array *paLeft */
42125  ht_slot **paRight,              /* IN/OUT: Right hand input list */
42126  int *pnRight,                   /* IN/OUT: Elements in *paRight */
42127  ht_slot *aTmp                   /* Temporary buffer */
42128){
42129  int iLeft = 0;                  /* Current index in aLeft */
42130  int iRight = 0;                 /* Current index in aRight */
42131  int iOut = 0;                   /* Current index in output buffer */
42132  int nRight = *pnRight;
42133  ht_slot *aRight = *paRight;
42134
42135  assert( nLeft>0 && nRight>0 );
42136  while( iRight<nRight || iLeft<nLeft ){
42137    ht_slot logpage;
42138    Pgno dbpage;
42139
42140    if( (iLeft<nLeft)
42141     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
42142    ){
42143      logpage = aLeft[iLeft++];
42144    }else{
42145      logpage = aRight[iRight++];
42146    }
42147    dbpage = aContent[logpage];
42148
42149    aTmp[iOut++] = logpage;
42150    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
42151
42152    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
42153    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
42154  }
42155
42156  *paRight = aLeft;
42157  *pnRight = iOut;
42158  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
42159}
42160
42161/*
42162** Sort the elements in list aList, removing any duplicates.
42163*/
42164static void walMergesort(
42165  u32 *aContent,                  /* Pages in wal */
42166  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
42167  ht_slot *aList,                 /* IN/OUT: List to sort */
42168  int *pnList                     /* IN/OUT: Number of elements in aList[] */
42169){
42170  struct Sublist {
42171    int nList;                    /* Number of elements in aList */
42172    ht_slot *aList;               /* Pointer to sub-list content */
42173  };
42174
42175  const int nList = *pnList;      /* Size of input list */
42176  int nMerge = 0;                 /* Number of elements in list aMerge */
42177  ht_slot *aMerge = 0;            /* List to be merged */
42178  int iList;                      /* Index into input list */
42179  int iSub = 0;                   /* Index into aSub array */
42180  struct Sublist aSub[13];        /* Array of sub-lists */
42181
42182  memset(aSub, 0, sizeof(aSub));
42183  assert( nList<=HASHTABLE_NPAGE && nList>0 );
42184  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
42185
42186  for(iList=0; iList<nList; iList++){
42187    nMerge = 1;
42188    aMerge = &aList[iList];
42189    for(iSub=0; iList & (1<<iSub); iSub++){
42190      struct Sublist *p = &aSub[iSub];
42191      assert( p->aList && p->nList<=(1<<iSub) );
42192      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
42193      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42194    }
42195    aSub[iSub].aList = aMerge;
42196    aSub[iSub].nList = nMerge;
42197  }
42198
42199  for(iSub++; iSub<ArraySize(aSub); iSub++){
42200    if( nList & (1<<iSub) ){
42201      struct Sublist *p = &aSub[iSub];
42202      assert( p->nList<=(1<<iSub) );
42203      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
42204      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42205    }
42206  }
42207  assert( aMerge==aList );
42208  *pnList = nMerge;
42209
42210#ifdef SQLITE_DEBUG
42211  {
42212    int i;
42213    for(i=1; i<*pnList; i++){
42214      assert( aContent[aList[i]] > aContent[aList[i-1]] );
42215    }
42216  }
42217#endif
42218}
42219
42220/*
42221** Free an iterator allocated by walIteratorInit().
42222*/
42223static void walIteratorFree(WalIterator *p){
42224  sqlite3ScratchFree(p);
42225}
42226
42227/*
42228** Construct a WalInterator object that can be used to loop over all
42229** pages in the WAL in ascending order. The caller must hold the checkpoint
42230**
42231** On success, make *pp point to the newly allocated WalInterator object
42232** return SQLITE_OK. Otherwise, return an error code. If this routine
42233** returns an error, the value of *pp is undefined.
42234**
42235** The calling routine should invoke walIteratorFree() to destroy the
42236** WalIterator object when it has finished with it.
42237*/
42238static int walIteratorInit(Wal *pWal, WalIterator **pp){
42239  WalIterator *p;                 /* Return value */
42240  int nSegment;                   /* Number of segments to merge */
42241  u32 iLast;                      /* Last frame in log */
42242  int nByte;                      /* Number of bytes to allocate */
42243  int i;                          /* Iterator variable */
42244  ht_slot *aTmp;                  /* Temp space used by merge-sort */
42245  int rc = SQLITE_OK;             /* Return Code */
42246
42247  /* This routine only runs while holding the checkpoint lock. And
42248  ** it only runs if there is actually content in the log (mxFrame>0).
42249  */
42250  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
42251  iLast = pWal->hdr.mxFrame;
42252
42253  /* Allocate space for the WalIterator object. */
42254  nSegment = walFramePage(iLast) + 1;
42255  nByte = sizeof(WalIterator)
42256        + (nSegment-1)*sizeof(struct WalSegment)
42257        + iLast*sizeof(ht_slot);
42258  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
42259  if( !p ){
42260    return SQLITE_NOMEM;
42261  }
42262  memset(p, 0, nByte);
42263  p->nSegment = nSegment;
42264
42265  /* Allocate temporary space used by the merge-sort routine. This block
42266  ** of memory will be freed before this function returns.
42267  */
42268  aTmp = (ht_slot *)sqlite3ScratchMalloc(
42269      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
42270  );
42271  if( !aTmp ){
42272    rc = SQLITE_NOMEM;
42273  }
42274
42275  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
42276    volatile ht_slot *aHash;
42277    u32 iZero;
42278    volatile u32 *aPgno;
42279
42280    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
42281    if( rc==SQLITE_OK ){
42282      int j;                      /* Counter variable */
42283      int nEntry;                 /* Number of entries in this segment */
42284      ht_slot *aIndex;            /* Sorted index for this segment */
42285
42286      aPgno++;
42287      if( (i+1)==nSegment ){
42288        nEntry = (int)(iLast - iZero);
42289      }else{
42290        nEntry = (int)((u32*)aHash - (u32*)aPgno);
42291      }
42292      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
42293      iZero++;
42294
42295      for(j=0; j<nEntry; j++){
42296        aIndex[j] = (ht_slot)j;
42297      }
42298      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
42299      p->aSegment[i].iZero = iZero;
42300      p->aSegment[i].nEntry = nEntry;
42301      p->aSegment[i].aIndex = aIndex;
42302      p->aSegment[i].aPgno = (u32 *)aPgno;
42303    }
42304  }
42305  sqlite3ScratchFree(aTmp);
42306
42307  if( rc!=SQLITE_OK ){
42308    walIteratorFree(p);
42309  }
42310  *pp = p;
42311  return rc;
42312}
42313
42314/*
42315** Copy as much content as we can from the WAL back into the database file
42316** in response to an sqlite3_wal_checkpoint() request or the equivalent.
42317**
42318** The amount of information copies from WAL to database might be limited
42319** by active readers.  This routine will never overwrite a database page
42320** that a concurrent reader might be using.
42321**
42322** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
42323** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
42324** checkpoints are always run by a background thread or background
42325** process, foreground threads will never block on a lengthy fsync call.
42326**
42327** Fsync is called on the WAL before writing content out of the WAL and
42328** into the database.  This ensures that if the new content is persistent
42329** in the WAL and can be recovered following a power-loss or hard reset.
42330**
42331** Fsync is also called on the database file if (and only if) the entire
42332** WAL content is copied into the database file.  This second fsync makes
42333** it safe to delete the WAL since the new content will persist in the
42334** database file.
42335**
42336** This routine uses and updates the nBackfill field of the wal-index header.
42337** This is the only routine tha will increase the value of nBackfill.
42338** (A WAL reset or recovery will revert nBackfill to zero, but not increase
42339** its value.)
42340**
42341** The caller must be holding sufficient locks to ensure that no other
42342** checkpoint is running (in any other thread or process) at the same
42343** time.
42344*/
42345static int walCheckpoint(
42346  Wal *pWal,                      /* Wal connection */
42347  int sync_flags,                 /* Flags for OsSync() (or 0) */
42348  int nBuf,                       /* Size of zBuf in bytes */
42349  u8 *zBuf                        /* Temporary buffer to use */
42350){
42351  int rc;                         /* Return code */
42352  int szPage;                     /* Database page-size */
42353  WalIterator *pIter = 0;         /* Wal iterator context */
42354  u32 iDbpage = 0;                /* Next database page to write */
42355  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
42356  u32 mxSafeFrame;                /* Max frame that can be backfilled */
42357  u32 mxPage;                     /* Max database page to write */
42358  int i;                          /* Loop counter */
42359  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
42360
42361  szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42362  testcase( szPage<=32768 );
42363  testcase( szPage>=65536 );
42364  if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
42365
42366  /* Allocate the iterator */
42367  rc = walIteratorInit(pWal, &pIter);
42368  if( rc!=SQLITE_OK ){
42369    return rc;
42370  }
42371  assert( pIter );
42372
42373  /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
42374  if( szPage!=nBuf ){
42375    rc = SQLITE_CORRUPT_BKPT;
42376    goto walcheckpoint_out;
42377  }
42378
42379  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
42380  ** safe to write into the database.  Frames beyond mxSafeFrame might
42381  ** overwrite database pages that are in use by active readers and thus
42382  ** cannot be backfilled from the WAL.
42383  */
42384  mxSafeFrame = pWal->hdr.mxFrame;
42385  mxPage = pWal->hdr.nPage;
42386  pInfo = walCkptInfo(pWal);
42387  for(i=1; i<WAL_NREADER; i++){
42388    u32 y = pInfo->aReadMark[i];
42389    if( mxSafeFrame>=y ){
42390      assert( y<=pWal->hdr.mxFrame );
42391      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
42392      if( rc==SQLITE_OK ){
42393        pInfo->aReadMark[i] = READMARK_NOT_USED;
42394        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
42395      }else if( rc==SQLITE_BUSY ){
42396        mxSafeFrame = y;
42397      }else{
42398        goto walcheckpoint_out;
42399      }
42400    }
42401  }
42402
42403  if( pInfo->nBackfill<mxSafeFrame
42404   && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
42405  ){
42406    i64 nSize;                    /* Current size of database file */
42407    u32 nBackfill = pInfo->nBackfill;
42408
42409    /* Sync the WAL to disk */
42410    if( sync_flags ){
42411      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
42412    }
42413
42414    /* If the database file may grow as a result of this checkpoint, hint
42415    ** about the eventual size of the db file to the VFS layer.
42416    */
42417    if( rc==SQLITE_OK ){
42418      i64 nReq = ((i64)mxPage * szPage);
42419      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
42420      if( rc==SQLITE_OK && nSize<nReq ){
42421        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
42422      }
42423    }
42424
42425    /* Iterate through the contents of the WAL, copying data to the db file. */
42426    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
42427      i64 iOffset;
42428      assert( walFramePgno(pWal, iFrame)==iDbpage );
42429      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
42430      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
42431      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
42432      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
42433      if( rc!=SQLITE_OK ) break;
42434      iOffset = (iDbpage-1)*(i64)szPage;
42435      testcase( IS_BIG_INT(iOffset) );
42436      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
42437      if( rc!=SQLITE_OK ) break;
42438    }
42439
42440    /* If work was actually accomplished... */
42441    if( rc==SQLITE_OK ){
42442      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
42443        i64 szDb = pWal->hdr.nPage*(i64)szPage;
42444        testcase( IS_BIG_INT(szDb) );
42445        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
42446        if( rc==SQLITE_OK && sync_flags ){
42447          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
42448        }
42449      }
42450      if( rc==SQLITE_OK ){
42451        pInfo->nBackfill = mxSafeFrame;
42452      }
42453    }
42454
42455    /* Release the reader lock held while backfilling */
42456    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
42457  }else if( rc==SQLITE_BUSY ){
42458    /* Reset the return code so as not to report a checkpoint failure
42459    ** just because active readers prevent any backfill.
42460    */
42461    rc = SQLITE_OK;
42462  }
42463
42464 walcheckpoint_out:
42465  walIteratorFree(pIter);
42466  return rc;
42467}
42468
42469/*
42470** Close a connection to a log file.
42471*/
42472SQLITE_PRIVATE int sqlite3WalClose(
42473  Wal *pWal,                      /* Wal to close */
42474  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
42475  int nBuf,
42476  u8 *zBuf                        /* Buffer of at least nBuf bytes */
42477){
42478  int rc = SQLITE_OK;
42479  if( pWal ){
42480    int isDelete = 0;             /* True to unlink wal and wal-index files */
42481
42482    /* If an EXCLUSIVE lock can be obtained on the database file (using the
42483    ** ordinary, rollback-mode locking methods, this guarantees that the
42484    ** connection associated with this log file is the only connection to
42485    ** the database. In this case checkpoint the database and unlink both
42486    ** the wal and wal-index files.
42487    **
42488    ** The EXCLUSIVE lock is not released before returning.
42489    */
42490    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
42491    if( rc==SQLITE_OK ){
42492      pWal->exclusiveMode = 1;
42493      rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
42494      if( rc==SQLITE_OK ){
42495        isDelete = 1;
42496      }
42497    }
42498
42499    walIndexClose(pWal, isDelete);
42500    sqlite3OsClose(pWal->pWalFd);
42501    if( isDelete ){
42502      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
42503    }
42504    WALTRACE(("WAL%p: closed\n", pWal));
42505    sqlite3_free((void *)pWal->apWiData);
42506    sqlite3_free(pWal);
42507  }
42508  return rc;
42509}
42510
42511/*
42512** Try to read the wal-index header.  Return 0 on success and 1 if
42513** there is a problem.
42514**
42515** The wal-index is in shared memory.  Another thread or process might
42516** be writing the header at the same time this procedure is trying to
42517** read it, which might result in inconsistency.  A dirty read is detected
42518** by verifying that both copies of the header are the same and also by
42519** a checksum on the header.
42520**
42521** If and only if the read is consistent and the header is different from
42522** pWal->hdr, then pWal->hdr is updated to the content of the new header
42523** and *pChanged is set to 1.
42524**
42525** If the checksum cannot be verified return non-zero. If the header
42526** is read successfully and the checksum verified, return zero.
42527*/
42528static int walIndexTryHdr(Wal *pWal, int *pChanged){
42529  u32 aCksum[2];                  /* Checksum on the header content */
42530  WalIndexHdr h1, h2;             /* Two copies of the header content */
42531  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
42532
42533  /* The first page of the wal-index must be mapped at this point. */
42534  assert( pWal->nWiData>0 && pWal->apWiData[0] );
42535
42536  /* Read the header. This might happen concurrently with a write to the
42537  ** same area of shared memory on a different CPU in a SMP,
42538  ** meaning it is possible that an inconsistent snapshot is read
42539  ** from the file. If this happens, return non-zero.
42540  **
42541  ** There are two copies of the header at the beginning of the wal-index.
42542  ** When reading, read [0] first then [1].  Writes are in the reverse order.
42543  ** Memory barriers are used to prevent the compiler or the hardware from
42544  ** reordering the reads and writes.
42545  */
42546  aHdr = walIndexHdr(pWal);
42547  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
42548  sqlite3OsShmBarrier(pWal->pDbFd);
42549  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
42550
42551  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
42552    return 1;   /* Dirty read */
42553  }
42554  if( h1.isInit==0 ){
42555    return 1;   /* Malformed header - probably all zeros */
42556  }
42557  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
42558  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
42559    return 1;   /* Checksum does not match */
42560  }
42561
42562  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
42563    *pChanged = 1;
42564    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
42565    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
42566    testcase( pWal->szPage<=32768 );
42567    testcase( pWal->szPage>=65536 );
42568  }
42569
42570  /* The header was successfully read. Return zero. */
42571  return 0;
42572}
42573
42574/*
42575** Read the wal-index header from the wal-index and into pWal->hdr.
42576** If the wal-header appears to be corrupt, try to reconstruct the
42577** wal-index from the WAL before returning.
42578**
42579** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
42580** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
42581** to 0.
42582**
42583** If the wal-index header is successfully read, return SQLITE_OK.
42584** Otherwise an SQLite error code.
42585*/
42586static int walIndexReadHdr(Wal *pWal, int *pChanged){
42587  int rc;                         /* Return code */
42588  int badHdr;                     /* True if a header read failed */
42589  volatile u32 *page0;            /* Chunk of wal-index containing header */
42590
42591  /* Ensure that page 0 of the wal-index (the page that contains the
42592  ** wal-index header) is mapped. Return early if an error occurs here.
42593  */
42594  assert( pChanged );
42595  rc = walIndexPage(pWal, 0, &page0);
42596  if( rc!=SQLITE_OK ){
42597    return rc;
42598  };
42599  assert( page0 || pWal->writeLock==0 );
42600
42601  /* If the first page of the wal-index has been mapped, try to read the
42602  ** wal-index header immediately, without holding any lock. This usually
42603  ** works, but may fail if the wal-index header is corrupt or currently
42604  ** being modified by another thread or process.
42605  */
42606  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
42607
42608  /* If the first attempt failed, it might have been due to a race
42609  ** with a writer.  So get a WRITE lock and try again.
42610  */
42611  assert( badHdr==0 || pWal->writeLock==0 );
42612  if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
42613    pWal->writeLock = 1;
42614    if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
42615      badHdr = walIndexTryHdr(pWal, pChanged);
42616      if( badHdr ){
42617        /* If the wal-index header is still malformed even while holding
42618        ** a WRITE lock, it can only mean that the header is corrupted and
42619        ** needs to be reconstructed.  So run recovery to do exactly that.
42620        */
42621        rc = walIndexRecover(pWal);
42622        *pChanged = 1;
42623      }
42624    }
42625    pWal->writeLock = 0;
42626    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
42627  }
42628
42629  /* If the header is read successfully, check the version number to make
42630  ** sure the wal-index was not constructed with some future format that
42631  ** this version of SQLite cannot understand.
42632  */
42633  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
42634    rc = SQLITE_CANTOPEN_BKPT;
42635  }
42636
42637  return rc;
42638}
42639
42640/*
42641** This is the value that walTryBeginRead returns when it needs to
42642** be retried.
42643*/
42644#define WAL_RETRY  (-1)
42645
42646/*
42647** Attempt to start a read transaction.  This might fail due to a race or
42648** other transient condition.  When that happens, it returns WAL_RETRY to
42649** indicate to the caller that it is safe to retry immediately.
42650**
42651** On success return SQLITE_OK.  On a permanent failure (such an
42652** I/O error or an SQLITE_BUSY because another process is running
42653** recovery) return a positive error code.
42654**
42655** The useWal parameter is true to force the use of the WAL and disable
42656** the case where the WAL is bypassed because it has been completely
42657** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
42658** to make a copy of the wal-index header into pWal->hdr.  If the
42659** wal-index header has changed, *pChanged is set to 1 (as an indication
42660** to the caller that the local paget cache is obsolete and needs to be
42661** flushed.)  When useWal==1, the wal-index header is assumed to already
42662** be loaded and the pChanged parameter is unused.
42663**
42664** The caller must set the cnt parameter to the number of prior calls to
42665** this routine during the current read attempt that returned WAL_RETRY.
42666** This routine will start taking more aggressive measures to clear the
42667** race conditions after multiple WAL_RETRY returns, and after an excessive
42668** number of errors will ultimately return SQLITE_PROTOCOL.  The
42669** SQLITE_PROTOCOL return indicates that some other process has gone rogue
42670** and is not honoring the locking protocol.  There is a vanishingly small
42671** chance that SQLITE_PROTOCOL could be returned because of a run of really
42672** bad luck when there is lots of contention for the wal-index, but that
42673** possibility is so small that it can be safely neglected, we believe.
42674**
42675** On success, this routine obtains a read lock on
42676** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
42677** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
42678** that means the Wal does not hold any read lock.  The reader must not
42679** access any database page that is modified by a WAL frame up to and
42680** including frame number aReadMark[pWal->readLock].  The reader will
42681** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
42682** Or if pWal->readLock==0, then the reader will ignore the WAL
42683** completely and get all content directly from the database file.
42684** If the useWal parameter is 1 then the WAL will never be ignored and
42685** this routine will always set pWal->readLock>0 on success.
42686** When the read transaction is completed, the caller must release the
42687** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
42688**
42689** This routine uses the nBackfill and aReadMark[] fields of the header
42690** to select a particular WAL_READ_LOCK() that strives to let the
42691** checkpoint process do as much work as possible.  This routine might
42692** update values of the aReadMark[] array in the header, but if it does
42693** so it takes care to hold an exclusive lock on the corresponding
42694** WAL_READ_LOCK() while changing values.
42695*/
42696static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
42697  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
42698  u32 mxReadMark;                 /* Largest aReadMark[] value */
42699  int mxI;                        /* Index of largest aReadMark[] value */
42700  int i;                          /* Loop counter */
42701  int rc = SQLITE_OK;             /* Return code  */
42702
42703  assert( pWal->readLock<0 );     /* Not currently locked */
42704
42705  /* Take steps to avoid spinning forever if there is a protocol error. */
42706  if( cnt>5 ){
42707    if( cnt>100 ) return SQLITE_PROTOCOL;
42708    sqlite3OsSleep(pWal->pVfs, 1);
42709  }
42710
42711  if( !useWal ){
42712    rc = walIndexReadHdr(pWal, pChanged);
42713    if( rc==SQLITE_BUSY ){
42714      /* If there is not a recovery running in another thread or process
42715      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
42716      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
42717      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
42718      ** would be technically correct.  But the race is benign since with
42719      ** WAL_RETRY this routine will be called again and will probably be
42720      ** right on the second iteration.
42721      */
42722      if( pWal->apWiData[0]==0 ){
42723        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
42724        ** We assume this is a transient condition, so return WAL_RETRY. The
42725        ** xShmMap() implementation used by the default unix and win32 VFS
42726        ** modules may return SQLITE_BUSY due to a race condition in the
42727        ** code that determines whether or not the shared-memory region
42728        ** must be zeroed before the requested page is returned.
42729        */
42730        rc = WAL_RETRY;
42731      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
42732        walUnlockShared(pWal, WAL_RECOVER_LOCK);
42733        rc = WAL_RETRY;
42734      }else if( rc==SQLITE_BUSY ){
42735        rc = SQLITE_BUSY_RECOVERY;
42736      }
42737    }
42738    if( rc!=SQLITE_OK ){
42739      return rc;
42740    }
42741  }
42742
42743  pInfo = walCkptInfo(pWal);
42744  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
42745    /* The WAL has been completely backfilled (or it is empty).
42746    ** and can be safely ignored.
42747    */
42748    rc = walLockShared(pWal, WAL_READ_LOCK(0));
42749    sqlite3OsShmBarrier(pWal->pDbFd);
42750    if( rc==SQLITE_OK ){
42751      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
42752        /* It is not safe to allow the reader to continue here if frames
42753        ** may have been appended to the log before READ_LOCK(0) was obtained.
42754        ** When holding READ_LOCK(0), the reader ignores the entire log file,
42755        ** which implies that the database file contains a trustworthy
42756        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
42757        ** happening, this is usually correct.
42758        **
42759        ** However, if frames have been appended to the log (or if the log
42760        ** is wrapped and written for that matter) before the READ_LOCK(0)
42761        ** is obtained, that is not necessarily true. A checkpointer may
42762        ** have started to backfill the appended frames but crashed before
42763        ** it finished. Leaving a corrupt image in the database file.
42764        */
42765        walUnlockShared(pWal, WAL_READ_LOCK(0));
42766        return WAL_RETRY;
42767      }
42768      pWal->readLock = 0;
42769      return SQLITE_OK;
42770    }else if( rc!=SQLITE_BUSY ){
42771      return rc;
42772    }
42773  }
42774
42775  /* If we get this far, it means that the reader will want to use
42776  ** the WAL to get at content from recent commits.  The job now is
42777  ** to select one of the aReadMark[] entries that is closest to
42778  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
42779  */
42780  mxReadMark = 0;
42781  mxI = 0;
42782  for(i=1; i<WAL_NREADER; i++){
42783    u32 thisMark = pInfo->aReadMark[i];
42784    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
42785      assert( thisMark!=READMARK_NOT_USED );
42786      mxReadMark = thisMark;
42787      mxI = i;
42788    }
42789  }
42790  if( mxI==0 ){
42791    /* If we get here, it means that all of the aReadMark[] entries between
42792    ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
42793    ** be mxFrame, then retry.
42794    */
42795    rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
42796    if( rc==SQLITE_OK ){
42797      pInfo->aReadMark[1] = pWal->hdr.mxFrame;
42798      walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
42799      rc = WAL_RETRY;
42800    }else if( rc==SQLITE_BUSY ){
42801      rc = WAL_RETRY;
42802    }
42803    return rc;
42804  }else{
42805    if( mxReadMark < pWal->hdr.mxFrame ){
42806      for(i=1; i<WAL_NREADER; i++){
42807        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
42808        if( rc==SQLITE_OK ){
42809          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
42810          mxI = i;
42811          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
42812          break;
42813        }else if( rc!=SQLITE_BUSY ){
42814          return rc;
42815        }
42816      }
42817    }
42818
42819    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
42820    if( rc ){
42821      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
42822    }
42823    /* Now that the read-lock has been obtained, check that neither the
42824    ** value in the aReadMark[] array or the contents of the wal-index
42825    ** header have changed.
42826    **
42827    ** It is necessary to check that the wal-index header did not change
42828    ** between the time it was read and when the shared-lock was obtained
42829    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
42830    ** that the log file may have been wrapped by a writer, or that frames
42831    ** that occur later in the log than pWal->hdr.mxFrame may have been
42832    ** copied into the database by a checkpointer. If either of these things
42833    ** happened, then reading the database with the current value of
42834    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
42835    ** instead.
42836    **
42837    ** This does not guarantee that the copy of the wal-index header is up to
42838    ** date before proceeding. That would not be possible without somehow
42839    ** blocking writers. It only guarantees that a dangerous checkpoint or
42840    ** log-wrap (either of which would require an exclusive lock on
42841    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
42842    */
42843    sqlite3OsShmBarrier(pWal->pDbFd);
42844    if( pInfo->aReadMark[mxI]!=mxReadMark
42845     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
42846    ){
42847      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
42848      return WAL_RETRY;
42849    }else{
42850      assert( mxReadMark<=pWal->hdr.mxFrame );
42851      pWal->readLock = (i16)mxI;
42852    }
42853  }
42854  return rc;
42855}
42856
42857/*
42858** Begin a read transaction on the database.
42859**
42860** This routine used to be called sqlite3OpenSnapshot() and with good reason:
42861** it takes a snapshot of the state of the WAL and wal-index for the current
42862** instant in time.  The current thread will continue to use this snapshot.
42863** Other threads might append new content to the WAL and wal-index but
42864** that extra content is ignored by the current thread.
42865**
42866** If the database contents have changes since the previous read
42867** transaction, then *pChanged is set to 1 before returning.  The
42868** Pager layer will use this to know that is cache is stale and
42869** needs to be flushed.
42870*/
42871SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
42872  int rc;                         /* Return code */
42873  int cnt = 0;                    /* Number of TryBeginRead attempts */
42874
42875  do{
42876    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
42877  }while( rc==WAL_RETRY );
42878  return rc;
42879}
42880
42881/*
42882** Finish with a read transaction.  All this does is release the
42883** read-lock.
42884*/
42885SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
42886  sqlite3WalEndWriteTransaction(pWal);
42887  if( pWal->readLock>=0 ){
42888    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
42889    pWal->readLock = -1;
42890  }
42891}
42892
42893/*
42894** Read a page from the WAL, if it is present in the WAL and if the
42895** current read transaction is configured to use the WAL.
42896**
42897** The *pInWal is set to 1 if the requested page is in the WAL and
42898** has been loaded.  Or *pInWal is set to 0 if the page was not in
42899** the WAL and needs to be read out of the database.
42900*/
42901SQLITE_PRIVATE int sqlite3WalRead(
42902  Wal *pWal,                      /* WAL handle */
42903  Pgno pgno,                      /* Database page number to read data for */
42904  int *pInWal,                    /* OUT: True if data is read from WAL */
42905  int nOut,                       /* Size of buffer pOut in bytes */
42906  u8 *pOut                        /* Buffer to write page data to */
42907){
42908  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
42909  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
42910  int iHash;                      /* Used to loop through N hash tables */
42911
42912  /* This routine is only be called from within a read transaction. */
42913  assert( pWal->readLock>=0 || pWal->lockError );
42914
42915  /* If the "last page" field of the wal-index header snapshot is 0, then
42916  ** no data will be read from the wal under any circumstances. Return early
42917  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
42918  ** then the WAL is ignored by the reader so return early, as if the
42919  ** WAL were empty.
42920  */
42921  if( iLast==0 || pWal->readLock==0 ){
42922    *pInWal = 0;
42923    return SQLITE_OK;
42924  }
42925
42926  /* Search the hash table or tables for an entry matching page number
42927  ** pgno. Each iteration of the following for() loop searches one
42928  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
42929  **
42930  ** This code might run concurrently to the code in walIndexAppend()
42931  ** that adds entries to the wal-index (and possibly to this hash
42932  ** table). This means the value just read from the hash
42933  ** slot (aHash[iKey]) may have been added before or after the
42934  ** current read transaction was opened. Values added after the
42935  ** read transaction was opened may have been written incorrectly -
42936  ** i.e. these slots may contain garbage data. However, we assume
42937  ** that any slots written before the current read transaction was
42938  ** opened remain unmodified.
42939  **
42940  ** For the reasons above, the if(...) condition featured in the inner
42941  ** loop of the following block is more stringent that would be required
42942  ** if we had exclusive access to the hash-table:
42943  **
42944  **   (aPgno[iFrame]==pgno):
42945  **     This condition filters out normal hash-table collisions.
42946  **
42947  **   (iFrame<=iLast):
42948  **     This condition filters out entries that were added to the hash
42949  **     table after the current read-transaction had started.
42950  */
42951  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
42952    volatile ht_slot *aHash;      /* Pointer to hash table */
42953    volatile u32 *aPgno;          /* Pointer to array of page numbers */
42954    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
42955    int iKey;                     /* Hash slot index */
42956    int nCollide;                 /* Number of hash collisions remaining */
42957    int rc;                       /* Error code */
42958
42959    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
42960    if( rc!=SQLITE_OK ){
42961      return rc;
42962    }
42963    nCollide = HASHTABLE_NSLOT;
42964    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
42965      u32 iFrame = aHash[iKey] + iZero;
42966      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
42967        assert( iFrame>iRead );
42968        iRead = iFrame;
42969      }
42970      if( (nCollide--)==0 ){
42971        return SQLITE_CORRUPT_BKPT;
42972      }
42973    }
42974  }
42975
42976#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42977  /* If expensive assert() statements are available, do a linear search
42978  ** of the wal-index file content. Make sure the results agree with the
42979  ** result obtained using the hash indexes above.  */
42980  {
42981    u32 iRead2 = 0;
42982    u32 iTest;
42983    for(iTest=iLast; iTest>0; iTest--){
42984      if( walFramePgno(pWal, iTest)==pgno ){
42985        iRead2 = iTest;
42986        break;
42987      }
42988    }
42989    assert( iRead==iRead2 );
42990  }
42991#endif
42992
42993  /* If iRead is non-zero, then it is the log frame number that contains the
42994  ** required page. Read and return data from the log file.
42995  */
42996  if( iRead ){
42997    int sz;
42998    i64 iOffset;
42999    sz = pWal->hdr.szPage;
43000    sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43001    testcase( sz<=32768 );
43002    testcase( sz>=65536 );
43003    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
43004    *pInWal = 1;
43005    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43006    return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
43007  }
43008
43009  *pInWal = 0;
43010  return SQLITE_OK;
43011}
43012
43013
43014/*
43015** Return the size of the database in pages (or zero, if unknown).
43016*/
43017SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
43018  if( pWal && ALWAYS(pWal->readLock>=0) ){
43019    return pWal->hdr.nPage;
43020  }
43021  return 0;
43022}
43023
43024
43025/*
43026** This function starts a write transaction on the WAL.
43027**
43028** A read transaction must have already been started by a prior call
43029** to sqlite3WalBeginReadTransaction().
43030**
43031** If another thread or process has written into the database since
43032** the read transaction was started, then it is not possible for this
43033** thread to write as doing so would cause a fork.  So this routine
43034** returns SQLITE_BUSY in that case and no write transaction is started.
43035**
43036** There can only be a single writer active at a time.
43037*/
43038SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
43039  int rc;
43040
43041  /* Cannot start a write transaction without first holding a read
43042  ** transaction. */
43043  assert( pWal->readLock>=0 );
43044
43045  if( pWal->readOnly ){
43046    return SQLITE_READONLY;
43047  }
43048
43049  /* Only one writer allowed at a time.  Get the write lock.  Return
43050  ** SQLITE_BUSY if unable.
43051  */
43052  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
43053  if( rc ){
43054    return rc;
43055  }
43056  pWal->writeLock = 1;
43057
43058  /* If another connection has written to the database file since the
43059  ** time the read transaction on this connection was started, then
43060  ** the write is disallowed.
43061  */
43062  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
43063    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43064    pWal->writeLock = 0;
43065    rc = SQLITE_BUSY;
43066  }
43067
43068  return rc;
43069}
43070
43071/*
43072** End a write transaction.  The commit has already been done.  This
43073** routine merely releases the lock.
43074*/
43075SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
43076  if( pWal->writeLock ){
43077    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43078    pWal->writeLock = 0;
43079  }
43080  return SQLITE_OK;
43081}
43082
43083/*
43084** If any data has been written (but not committed) to the log file, this
43085** function moves the write-pointer back to the start of the transaction.
43086**
43087** Additionally, the callback function is invoked for each frame written
43088** to the WAL since the start of the transaction. If the callback returns
43089** other than SQLITE_OK, it is not invoked again and the error code is
43090** returned to the caller.
43091**
43092** Otherwise, if the callback function does not return an error, this
43093** function returns SQLITE_OK.
43094*/
43095SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
43096  int rc = SQLITE_OK;
43097  if( ALWAYS(pWal->writeLock) ){
43098    Pgno iMax = pWal->hdr.mxFrame;
43099    Pgno iFrame;
43100
43101    /* Restore the clients cache of the wal-index header to the state it
43102    ** was in before the client began writing to the database.
43103    */
43104    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
43105
43106    for(iFrame=pWal->hdr.mxFrame+1;
43107        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
43108        iFrame++
43109    ){
43110      /* This call cannot fail. Unless the page for which the page number
43111      ** is passed as the second argument is (a) in the cache and
43112      ** (b) has an outstanding reference, then xUndo is either a no-op
43113      ** (if (a) is false) or simply expels the page from the cache (if (b)
43114      ** is false).
43115      **
43116      ** If the upper layer is doing a rollback, it is guaranteed that there
43117      ** are no outstanding references to any page other than page 1. And
43118      ** page 1 is never written to the log until the transaction is
43119      ** committed. As a result, the call to xUndo may not fail.
43120      */
43121      assert( walFramePgno(pWal, iFrame)!=1 );
43122      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
43123    }
43124    walCleanupHash(pWal);
43125  }
43126  assert( rc==SQLITE_OK );
43127  return rc;
43128}
43129
43130/*
43131** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
43132** values. This function populates the array with values required to
43133** "rollback" the write position of the WAL handle back to the current
43134** point in the event of a savepoint rollback (via WalSavepointUndo()).
43135*/
43136SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
43137  assert( pWal->writeLock );
43138  aWalData[0] = pWal->hdr.mxFrame;
43139  aWalData[1] = pWal->hdr.aFrameCksum[0];
43140  aWalData[2] = pWal->hdr.aFrameCksum[1];
43141  aWalData[3] = pWal->nCkpt;
43142}
43143
43144/*
43145** Move the write position of the WAL back to the point identified by
43146** the values in the aWalData[] array. aWalData must point to an array
43147** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
43148** by a call to WalSavepoint().
43149*/
43150SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
43151  int rc = SQLITE_OK;
43152
43153  assert( pWal->writeLock );
43154  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
43155
43156  if( aWalData[3]!=pWal->nCkpt ){
43157    /* This savepoint was opened immediately after the write-transaction
43158    ** was started. Right after that, the writer decided to wrap around
43159    ** to the start of the log. Update the savepoint values to match.
43160    */
43161    aWalData[0] = 0;
43162    aWalData[3] = pWal->nCkpt;
43163  }
43164
43165  if( aWalData[0]<pWal->hdr.mxFrame ){
43166    pWal->hdr.mxFrame = aWalData[0];
43167    pWal->hdr.aFrameCksum[0] = aWalData[1];
43168    pWal->hdr.aFrameCksum[1] = aWalData[2];
43169    walCleanupHash(pWal);
43170  }
43171
43172  return rc;
43173}
43174
43175/*
43176** This function is called just before writing a set of frames to the log
43177** file (see sqlite3WalFrames()). It checks to see if, instead of appending
43178** to the current log file, it is possible to overwrite the start of the
43179** existing log file with the new frames (i.e. "reset" the log). If so,
43180** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
43181** unchanged.
43182**
43183** SQLITE_OK is returned if no error is encountered (regardless of whether
43184** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
43185** if some error
43186*/
43187static int walRestartLog(Wal *pWal){
43188  int rc = SQLITE_OK;
43189  int cnt;
43190
43191  if( pWal->readLock==0 ){
43192    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
43193    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
43194    if( pInfo->nBackfill>0 ){
43195      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43196      if( rc==SQLITE_OK ){
43197        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
43198        ** readers are currently using the WAL), then the transactions
43199        ** frames will overwrite the start of the existing log. Update the
43200        ** wal-index header to reflect this.
43201        **
43202        ** In theory it would be Ok to update the cache of the header only
43203        ** at this point. But updating the actual wal-index header is also
43204        ** safe and means there is no special case for sqlite3WalUndo()
43205        ** to handle if this transaction is rolled back.
43206        */
43207        int i;                    /* Loop counter */
43208        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
43209        pWal->nCkpt++;
43210        pWal->hdr.mxFrame = 0;
43211        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
43212        sqlite3_randomness(4, &aSalt[1]);
43213        walIndexWriteHdr(pWal);
43214        pInfo->nBackfill = 0;
43215        for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
43216        assert( pInfo->aReadMark[0]==0 );
43217        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43218      }
43219    }
43220    walUnlockShared(pWal, WAL_READ_LOCK(0));
43221    pWal->readLock = -1;
43222    cnt = 0;
43223    do{
43224      int notUsed;
43225      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
43226    }while( rc==WAL_RETRY );
43227  }
43228  return rc;
43229}
43230
43231/*
43232** Write a set of frames to the log. The caller must hold the write-lock
43233** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
43234*/
43235SQLITE_PRIVATE int sqlite3WalFrames(
43236  Wal *pWal,                      /* Wal handle to write to */
43237  int szPage,                     /* Database page-size in bytes */
43238  PgHdr *pList,                   /* List of dirty pages to write */
43239  Pgno nTruncate,                 /* Database size after this commit */
43240  int isCommit,                   /* True if this is a commit */
43241  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
43242){
43243  int rc;                         /* Used to catch return codes */
43244  u32 iFrame;                     /* Next frame address */
43245  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
43246  PgHdr *p;                       /* Iterator to run through pList with. */
43247  PgHdr *pLast = 0;               /* Last frame in list */
43248  int nLast = 0;                  /* Number of extra copies of last page */
43249
43250  assert( pList );
43251  assert( pWal->writeLock );
43252
43253#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43254  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
43255    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
43256              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
43257  }
43258#endif
43259
43260  /* See if it is possible to write these frames into the start of the
43261  ** log file, instead of appending to it at pWal->hdr.mxFrame.
43262  */
43263  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
43264    return rc;
43265  }
43266
43267  /* If this is the first frame written into the log, write the WAL
43268  ** header to the start of the WAL file. See comments at the top of
43269  ** this source file for a description of the WAL header format.
43270  */
43271  iFrame = pWal->hdr.mxFrame;
43272  if( iFrame==0 ){
43273    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
43274    u32 aCksum[2];                /* Checksum for wal-header */
43275
43276    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
43277    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
43278    sqlite3Put4byte(&aWalHdr[8], szPage);
43279    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
43280    sqlite3_randomness(8, pWal->hdr.aSalt);
43281    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
43282    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
43283    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
43284    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
43285
43286    pWal->szPage = szPage;
43287    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
43288    pWal->hdr.aFrameCksum[0] = aCksum[0];
43289    pWal->hdr.aFrameCksum[1] = aCksum[1];
43290
43291    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
43292    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
43293    if( rc!=SQLITE_OK ){
43294      return rc;
43295    }
43296  }
43297  assert( pWal->szPage==szPage );
43298
43299  /* Write the log file. */
43300  for(p=pList; p; p=p->pDirty){
43301    u32 nDbsize;                  /* Db-size field for frame header */
43302    i64 iOffset;                  /* Write offset in log file */
43303    void *pData;
43304
43305    iOffset = walFrameOffset(++iFrame, szPage);
43306    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43307
43308    /* Populate and write the frame header */
43309    nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
43310#if defined(SQLITE_HAS_CODEC)
43311    if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
43312#else
43313    pData = p->pData;
43314#endif
43315    walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
43316    rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43317    if( rc!=SQLITE_OK ){
43318      return rc;
43319    }
43320
43321    /* Write the page data */
43322    rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
43323    if( rc!=SQLITE_OK ){
43324      return rc;
43325    }
43326    pLast = p;
43327  }
43328
43329  /* Sync the log file if the 'isSync' flag was specified. */
43330  if( sync_flags ){
43331    i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
43332    i64 iOffset = walFrameOffset(iFrame+1, szPage);
43333
43334    assert( isCommit );
43335    assert( iSegment>0 );
43336
43337    iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
43338    while( iOffset<iSegment ){
43339      void *pData;
43340#if defined(SQLITE_HAS_CODEC)
43341      if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
43342#else
43343      pData = pLast->pData;
43344#endif
43345      walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
43346      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43347      rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43348      if( rc!=SQLITE_OK ){
43349        return rc;
43350      }
43351      iOffset += WAL_FRAME_HDRSIZE;
43352      rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
43353      if( rc!=SQLITE_OK ){
43354        return rc;
43355      }
43356      nLast++;
43357      iOffset += szPage;
43358    }
43359
43360    rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
43361  }
43362
43363  /* Append data to the wal-index. It is not necessary to lock the
43364  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
43365  ** guarantees that there are no other writers, and no data that may
43366  ** be in use by existing readers is being overwritten.
43367  */
43368  iFrame = pWal->hdr.mxFrame;
43369  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
43370    iFrame++;
43371    rc = walIndexAppend(pWal, iFrame, p->pgno);
43372  }
43373  while( nLast>0 && rc==SQLITE_OK ){
43374    iFrame++;
43375    nLast--;
43376    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
43377  }
43378
43379  if( rc==SQLITE_OK ){
43380    /* Update the private copy of the header. */
43381    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
43382    testcase( szPage<=32768 );
43383    testcase( szPage>=65536 );
43384    pWal->hdr.mxFrame = iFrame;
43385    if( isCommit ){
43386      pWal->hdr.iChange++;
43387      pWal->hdr.nPage = nTruncate;
43388    }
43389    /* If this is a commit, update the wal-index header too. */
43390    if( isCommit ){
43391      walIndexWriteHdr(pWal);
43392      pWal->iCallback = iFrame;
43393    }
43394  }
43395
43396  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
43397  return rc;
43398}
43399
43400/*
43401** This routine is called to implement sqlite3_wal_checkpoint() and
43402** related interfaces.
43403**
43404** Obtain a CHECKPOINT lock and then backfill as much information as
43405** we can from WAL into the database.
43406*/
43407SQLITE_PRIVATE int sqlite3WalCheckpoint(
43408  Wal *pWal,                      /* Wal connection */
43409  int sync_flags,                 /* Flags to sync db file with (or 0) */
43410  int nBuf,                       /* Size of temporary buffer */
43411  u8 *zBuf                        /* Temporary buffer to use */
43412){
43413  int rc;                         /* Return code */
43414  int isChanged = 0;              /* True if a new wal-index header is loaded */
43415
43416  assert( pWal->ckptLock==0 );
43417
43418  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
43419  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
43420  if( rc ){
43421    /* Usually this is SQLITE_BUSY meaning that another thread or process
43422    ** is already running a checkpoint, or maybe a recovery.  But it might
43423    ** also be SQLITE_IOERR. */
43424    return rc;
43425  }
43426  pWal->ckptLock = 1;
43427
43428  /* Copy data from the log to the database file. */
43429  rc = walIndexReadHdr(pWal, &isChanged);
43430  if( rc==SQLITE_OK ){
43431    rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
43432  }
43433  if( isChanged ){
43434    /* If a new wal-index header was loaded before the checkpoint was
43435    ** performed, then the pager-cache associated with pWal is now
43436    ** out of date. So zero the cached wal-index header to ensure that
43437    ** next time the pager opens a snapshot on this database it knows that
43438    ** the cache needs to be reset.
43439    */
43440    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
43441  }
43442
43443  /* Release the locks. */
43444  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
43445  pWal->ckptLock = 0;
43446  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
43447  return rc;
43448}
43449
43450/* Return the value to pass to a sqlite3_wal_hook callback, the
43451** number of frames in the WAL at the point of the last commit since
43452** sqlite3WalCallback() was called.  If no commits have occurred since
43453** the last call, then return 0.
43454*/
43455SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
43456  u32 ret = 0;
43457  if( pWal ){
43458    ret = pWal->iCallback;
43459    pWal->iCallback = 0;
43460  }
43461  return (int)ret;
43462}
43463
43464/*
43465** This function is called to change the WAL subsystem into or out
43466** of locking_mode=EXCLUSIVE.
43467**
43468** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
43469** into locking_mode=NORMAL.  This means that we must acquire a lock
43470** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
43471** or if the acquisition of the lock fails, then return 0.  If the
43472** transition out of exclusive-mode is successful, return 1.  This
43473** operation must occur while the pager is still holding the exclusive
43474** lock on the main database file.
43475**
43476** If op is one, then change from locking_mode=NORMAL into
43477** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
43478** be released.  Return 1 if the transition is made and 0 if the
43479** WAL is already in exclusive-locking mode - meaning that this
43480** routine is a no-op.  The pager must already hold the exclusive lock
43481** on the main database file before invoking this operation.
43482**
43483** If op is negative, then do a dry-run of the op==1 case but do
43484** not actually change anything.  The pager uses this to see if it
43485** should acquire the database exclusive lock prior to invoking
43486** the op==1 case.
43487*/
43488SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
43489  int rc;
43490  assert( pWal->writeLock==0 );
43491
43492  /* pWal->readLock is usually set, but might be -1 if there was a
43493  ** prior error while attempting to acquire are read-lock. This cannot
43494  ** happen if the connection is actually in exclusive mode (as no xShmLock
43495  ** locks are taken in this case). Nor should the pager attempt to
43496  ** upgrade to exclusive-mode following such an error.
43497  */
43498  assert( pWal->readLock>=0 || pWal->lockError );
43499  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
43500
43501  if( op==0 ){
43502    if( pWal->exclusiveMode ){
43503      pWal->exclusiveMode = 0;
43504      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
43505        pWal->exclusiveMode = 1;
43506      }
43507      rc = pWal->exclusiveMode==0;
43508    }else{
43509      /* Already in locking_mode=NORMAL */
43510      rc = 0;
43511    }
43512  }else if( op>0 ){
43513    assert( pWal->exclusiveMode==0 );
43514    assert( pWal->readLock>=0 );
43515    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
43516    pWal->exclusiveMode = 1;
43517    rc = 1;
43518  }else{
43519    rc = pWal->exclusiveMode==0;
43520  }
43521  return rc;
43522}
43523
43524#endif /* #ifndef SQLITE_OMIT_WAL */
43525
43526/************** End of wal.c *************************************************/
43527/************** Begin file btmutex.c *****************************************/
43528/*
43529** 2007 August 27
43530**
43531** The author disclaims copyright to this source code.  In place of
43532** a legal notice, here is a blessing:
43533**
43534**    May you do good and not evil.
43535**    May you find forgiveness for yourself and forgive others.
43536**    May you share freely, never taking more than you give.
43537**
43538*************************************************************************
43539**
43540** This file contains code used to implement mutexes on Btree objects.
43541** This code really belongs in btree.c.  But btree.c is getting too
43542** big and we want to break it down some.  This packaged seemed like
43543** a good breakout.
43544*/
43545/************** Include btreeInt.h in the middle of btmutex.c ****************/
43546/************** Begin file btreeInt.h ****************************************/
43547/*
43548** 2004 April 6
43549**
43550** The author disclaims copyright to this source code.  In place of
43551** a legal notice, here is a blessing:
43552**
43553**    May you do good and not evil.
43554**    May you find forgiveness for yourself and forgive others.
43555**    May you share freely, never taking more than you give.
43556**
43557*************************************************************************
43558** This file implements a external (disk-based) database using BTrees.
43559** For a detailed discussion of BTrees, refer to
43560**
43561**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
43562**     "Sorting And Searching", pages 473-480. Addison-Wesley
43563**     Publishing Company, Reading, Massachusetts.
43564**
43565** The basic idea is that each page of the file contains N database
43566** entries and N+1 pointers to subpages.
43567**
43568**   ----------------------------------------------------------------
43569**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
43570**   ----------------------------------------------------------------
43571**
43572** All of the keys on the page that Ptr(0) points to have values less
43573** than Key(0).  All of the keys on page Ptr(1) and its subpages have
43574** values greater than Key(0) and less than Key(1).  All of the keys
43575** on Ptr(N) and its subpages have values greater than Key(N-1).  And
43576** so forth.
43577**
43578** Finding a particular key requires reading O(log(M)) pages from the
43579** disk where M is the number of entries in the tree.
43580**
43581** In this implementation, a single file can hold one or more separate
43582** BTrees.  Each BTree is identified by the index of its root page.  The
43583** key and data for any entry are combined to form the "payload".  A
43584** fixed amount of payload can be carried directly on the database
43585** page.  If the payload is larger than the preset amount then surplus
43586** bytes are stored on overflow pages.  The payload for an entry
43587** and the preceding pointer are combined to form a "Cell".  Each
43588** page has a small header which contains the Ptr(N) pointer and other
43589** information such as the size of key and data.
43590**
43591** FORMAT DETAILS
43592**
43593** The file is divided into pages.  The first page is called page 1,
43594** the second is page 2, and so forth.  A page number of zero indicates
43595** "no such page".  The page size can be any power of 2 between 512 and 65536.
43596** Each page can be either a btree page, a freelist page, an overflow
43597** page, or a pointer-map page.
43598**
43599** The first page is always a btree page.  The first 100 bytes of the first
43600** page contain a special header (the "file header") that describes the file.
43601** The format of the file header is as follows:
43602**
43603**   OFFSET   SIZE    DESCRIPTION
43604**      0      16     Header string: "SQLite format 3\000"
43605**     16       2     Page size in bytes.
43606**     18       1     File format write version
43607**     19       1     File format read version
43608**     20       1     Bytes of unused space at the end of each page
43609**     21       1     Max embedded payload fraction
43610**     22       1     Min embedded payload fraction
43611**     23       1     Min leaf payload fraction
43612**     24       4     File change counter
43613**     28       4     Reserved for future use
43614**     32       4     First freelist page
43615**     36       4     Number of freelist pages in the file
43616**     40      60     15 4-byte meta values passed to higher layers
43617**
43618**     40       4     Schema cookie
43619**     44       4     File format of schema layer
43620**     48       4     Size of page cache
43621**     52       4     Largest root-page (auto/incr_vacuum)
43622**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
43623**     60       4     User version
43624**     64       4     Incremental vacuum mode
43625**     68       4     unused
43626**     72       4     unused
43627**     76       4     unused
43628**
43629** All of the integer values are big-endian (most significant byte first).
43630**
43631** The file change counter is incremented when the database is changed
43632** This counter allows other processes to know when the file has changed
43633** and thus when they need to flush their cache.
43634**
43635** The max embedded payload fraction is the amount of the total usable
43636** space in a page that can be consumed by a single cell for standard
43637** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
43638** is to limit the maximum cell size so that at least 4 cells will fit
43639** on one page.  Thus the default max embedded payload fraction is 64.
43640**
43641** If the payload for a cell is larger than the max payload, then extra
43642** payload is spilled to overflow pages.  Once an overflow page is allocated,
43643** as many bytes as possible are moved into the overflow pages without letting
43644** the cell size drop below the min embedded payload fraction.
43645**
43646** The min leaf payload fraction is like the min embedded payload fraction
43647** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
43648** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
43649** not specified in the header.
43650**
43651** Each btree pages is divided into three sections:  The header, the
43652** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
43653** file header that occurs before the page header.
43654**
43655**      |----------------|
43656**      | file header    |   100 bytes.  Page 1 only.
43657**      |----------------|
43658**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
43659**      |----------------|
43660**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
43661**      | array          |   |  Grows downward
43662**      |                |   v
43663**      |----------------|
43664**      | unallocated    |
43665**      | space          |
43666**      |----------------|   ^  Grows upwards
43667**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
43668**      | area           |   |  and free space fragments.
43669**      |----------------|
43670**
43671** The page headers looks like this:
43672**
43673**   OFFSET   SIZE     DESCRIPTION
43674**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
43675**      1       2      byte offset to the first freeblock
43676**      3       2      number of cells on this page
43677**      5       2      first byte of the cell content area
43678**      7       1      number of fragmented free bytes
43679**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
43680**
43681** The flags define the format of this btree page.  The leaf flag means that
43682** this page has no children.  The zerodata flag means that this page carries
43683** only keys and no data.  The intkey flag means that the key is a integer
43684** which is stored in the key size entry of the cell header rather than in
43685** the payload area.
43686**
43687** The cell pointer array begins on the first byte after the page header.
43688** The cell pointer array contains zero or more 2-byte numbers which are
43689** offsets from the beginning of the page to the cell content in the cell
43690** content area.  The cell pointers occur in sorted order.  The system strives
43691** to keep free space after the last cell pointer so that new cells can
43692** be easily added without having to defragment the page.
43693**
43694** Cell content is stored at the very end of the page and grows toward the
43695** beginning of the page.
43696**
43697** Unused space within the cell content area is collected into a linked list of
43698** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
43699** to the first freeblock is given in the header.  Freeblocks occur in
43700** increasing order.  Because a freeblock must be at least 4 bytes in size,
43701** any group of 3 or fewer unused bytes in the cell content area cannot
43702** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
43703** a fragment.  The total number of bytes in all fragments is recorded.
43704** in the page header at offset 7.
43705**
43706**    SIZE    DESCRIPTION
43707**      2     Byte offset of the next freeblock
43708**      2     Bytes in this freeblock
43709**
43710** Cells are of variable length.  Cells are stored in the cell content area at
43711** the end of the page.  Pointers to the cells are in the cell pointer array
43712** that immediately follows the page header.  Cells is not necessarily
43713** contiguous or in order, but cell pointers are contiguous and in order.
43714**
43715** Cell content makes use of variable length integers.  A variable
43716** length integer is 1 to 9 bytes where the lower 7 bits of each
43717** byte are used.  The integer consists of all bytes that have bit 8 set and
43718** the first byte with bit 8 clear.  The most significant byte of the integer
43719** appears first.  A variable-length integer may not be more than 9 bytes long.
43720** As a special case, all 8 bytes of the 9th byte are used as data.  This
43721** allows a 64-bit integer to be encoded in 9 bytes.
43722**
43723**    0x00                      becomes  0x00000000
43724**    0x7f                      becomes  0x0000007f
43725**    0x81 0x00                 becomes  0x00000080
43726**    0x82 0x00                 becomes  0x00000100
43727**    0x80 0x7f                 becomes  0x0000007f
43728**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
43729**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
43730**
43731** Variable length integers are used for rowids and to hold the number of
43732** bytes of key and data in a btree cell.
43733**
43734** The content of a cell looks like this:
43735**
43736**    SIZE    DESCRIPTION
43737**      4     Page number of the left child. Omitted if leaf flag is set.
43738**     var    Number of bytes of data. Omitted if the zerodata flag is set.
43739**     var    Number of bytes of key. Or the key itself if intkey flag is set.
43740**      *     Payload
43741**      4     First page of the overflow chain.  Omitted if no overflow
43742**
43743** Overflow pages form a linked list.  Each page except the last is completely
43744** filled with data (pagesize - 4 bytes).  The last page can have as little
43745** as 1 byte of data.
43746**
43747**    SIZE    DESCRIPTION
43748**      4     Page number of next overflow page
43749**      *     Data
43750**
43751** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
43752** file header points to the first in a linked list of trunk page.  Each trunk
43753** page points to multiple leaf pages.  The content of a leaf page is
43754** unspecified.  A trunk page looks like this:
43755**
43756**    SIZE    DESCRIPTION
43757**      4     Page number of next trunk page
43758**      4     Number of leaf pointers on this page
43759**      *     zero or more pages numbers of leaves
43760*/
43761
43762
43763/* The following value is the maximum cell size assuming a maximum page
43764** size give above.
43765*/
43766#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
43767
43768/* The maximum number of cells on a single page of the database.  This
43769** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
43770** plus 2 bytes for the index to the cell in the page header).  Such
43771** small cells will be rare, but they are possible.
43772*/
43773#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
43774
43775/* Forward declarations */
43776typedef struct MemPage MemPage;
43777typedef struct BtLock BtLock;
43778
43779/*
43780** This is a magic string that appears at the beginning of every
43781** SQLite database in order to identify the file as a real database.
43782**
43783** You can change this value at compile-time by specifying a
43784** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
43785** header must be exactly 16 bytes including the zero-terminator so
43786** the string itself should be 15 characters long.  If you change
43787** the header, then your custom library will not be able to read
43788** databases generated by the standard tools and the standard tools
43789** will not be able to read databases created by your custom library.
43790*/
43791#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
43792#  define SQLITE_FILE_HEADER "SQLite format 3"
43793#endif
43794
43795/*
43796** Page type flags.  An ORed combination of these flags appear as the
43797** first byte of on-disk image of every BTree page.
43798*/
43799#define PTF_INTKEY    0x01
43800#define PTF_ZERODATA  0x02
43801#define PTF_LEAFDATA  0x04
43802#define PTF_LEAF      0x08
43803
43804/*
43805** As each page of the file is loaded into memory, an instance of the following
43806** structure is appended and initialized to zero.  This structure stores
43807** information about the page that is decoded from the raw file page.
43808**
43809** The pParent field points back to the parent page.  This allows us to
43810** walk up the BTree from any leaf to the root.  Care must be taken to
43811** unref() the parent page pointer when this page is no longer referenced.
43812** The pageDestructor() routine handles that chore.
43813**
43814** Access to all fields of this structure is controlled by the mutex
43815** stored in MemPage.pBt->mutex.
43816*/
43817struct MemPage {
43818  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
43819  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
43820  u8 intKey;           /* True if intkey flag is set */
43821  u8 leaf;             /* True if leaf flag is set */
43822  u8 hasData;          /* True if this page stores data */
43823  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
43824  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
43825  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
43826  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
43827  u16 cellOffset;      /* Index in aData of first cell pointer */
43828  u16 nFree;           /* Number of free bytes on the page */
43829  u16 nCell;           /* Number of cells on this page, local and ovfl */
43830  u16 maskPage;        /* Mask for page offset */
43831  struct _OvflCell {   /* Cells that will not fit on aData[] */
43832    u8 *pCell;          /* Pointers to the body of the overflow cell */
43833    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
43834  } aOvfl[5];
43835  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
43836  u8 *aData;           /* Pointer to disk image of the page data */
43837  DbPage *pDbPage;     /* Pager page handle */
43838  Pgno pgno;           /* Page number for this page */
43839};
43840
43841/*
43842** The in-memory image of a disk page has the auxiliary information appended
43843** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
43844** that extra information.
43845*/
43846#define EXTRA_SIZE sizeof(MemPage)
43847
43848/*
43849** A linked list of the following structures is stored at BtShared.pLock.
43850** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
43851** is opened on the table with root page BtShared.iTable. Locks are removed
43852** from this list when a transaction is committed or rolled back, or when
43853** a btree handle is closed.
43854*/
43855struct BtLock {
43856  Btree *pBtree;        /* Btree handle holding this lock */
43857  Pgno iTable;          /* Root page of table */
43858  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
43859  BtLock *pNext;        /* Next in BtShared.pLock list */
43860};
43861
43862/* Candidate values for BtLock.eLock */
43863#define READ_LOCK     1
43864#define WRITE_LOCK    2
43865
43866/* A Btree handle
43867**
43868** A database connection contains a pointer to an instance of
43869** this object for every database file that it has open.  This structure
43870** is opaque to the database connection.  The database connection cannot
43871** see the internals of this structure and only deals with pointers to
43872** this structure.
43873**
43874** For some database files, the same underlying database cache might be
43875** shared between multiple connections.  In that case, each connection
43876** has it own instance of this object.  But each instance of this object
43877** points to the same BtShared object.  The database cache and the
43878** schema associated with the database file are all contained within
43879** the BtShared object.
43880**
43881** All fields in this structure are accessed under sqlite3.mutex.
43882** The pBt pointer itself may not be changed while there exists cursors
43883** in the referenced BtShared that point back to this Btree since those
43884** cursors have to do go through this Btree to find their BtShared and
43885** they often do so without holding sqlite3.mutex.
43886*/
43887struct Btree {
43888  sqlite3 *db;       /* The database connection holding this btree */
43889  BtShared *pBt;     /* Sharable content of this btree */
43890  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
43891  u8 sharable;       /* True if we can share pBt with another db */
43892  u8 locked;         /* True if db currently has pBt locked */
43893  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
43894  int nBackup;       /* Number of backup operations reading this btree */
43895  Btree *pNext;      /* List of other sharable Btrees from the same db */
43896  Btree *pPrev;      /* Back pointer of the same list */
43897#ifndef SQLITE_OMIT_SHARED_CACHE
43898  BtLock lock;       /* Object used to lock page 1 */
43899#endif
43900};
43901
43902/*
43903** Btree.inTrans may take one of the following values.
43904**
43905** If the shared-data extension is enabled, there may be multiple users
43906** of the Btree structure. At most one of these may open a write transaction,
43907** but any number may have active read transactions.
43908*/
43909#define TRANS_NONE  0
43910#define TRANS_READ  1
43911#define TRANS_WRITE 2
43912
43913/*
43914** An instance of this object represents a single database file.
43915**
43916** A single database file can be in use as the same time by two
43917** or more database connections.  When two or more connections are
43918** sharing the same database file, each connection has it own
43919** private Btree object for the file and each of those Btrees points
43920** to this one BtShared object.  BtShared.nRef is the number of
43921** connections currently sharing this database file.
43922**
43923** Fields in this structure are accessed under the BtShared.mutex
43924** mutex, except for nRef and pNext which are accessed under the
43925** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
43926** may not be modified once it is initially set as long as nRef>0.
43927** The pSchema field may be set once under BtShared.mutex and
43928** thereafter is unchanged as long as nRef>0.
43929**
43930** isPending:
43931**
43932**   If a BtShared client fails to obtain a write-lock on a database
43933**   table (because there exists one or more read-locks on the table),
43934**   the shared-cache enters 'pending-lock' state and isPending is
43935**   set to true.
43936**
43937**   The shared-cache leaves the 'pending lock' state when either of
43938**   the following occur:
43939**
43940**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
43941**     2) The number of locks held by other connections drops to zero.
43942**
43943**   while in the 'pending-lock' state, no connection may start a new
43944**   transaction.
43945**
43946**   This feature is included to help prevent writer-starvation.
43947*/
43948struct BtShared {
43949  Pager *pPager;        /* The page cache */
43950  sqlite3 *db;          /* Database connection currently using this Btree */
43951  BtCursor *pCursor;    /* A list of all open cursors */
43952  MemPage *pPage1;      /* First page of the database */
43953  u8 readOnly;          /* True if the underlying file is readonly */
43954  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
43955  u8 secureDelete;      /* True if secure_delete is enabled */
43956  u8 initiallyEmpty;    /* Database is empty at start of transaction */
43957#ifndef SQLITE_OMIT_AUTOVACUUM
43958  u8 autoVacuum;        /* True if auto-vacuum is enabled */
43959  u8 incrVacuum;        /* True if incr-vacuum is enabled */
43960#endif
43961  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
43962  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
43963  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
43964  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
43965  u8 inTransaction;     /* Transaction state */
43966  u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
43967  u32 pageSize;         /* Total number of bytes on a page */
43968  u32 usableSize;       /* Number of usable bytes on each page */
43969  int nTransaction;     /* Number of open transactions (read + write) */
43970  u32 nPage;            /* Number of pages in the database */
43971  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
43972  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
43973  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
43974  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
43975#ifndef SQLITE_OMIT_SHARED_CACHE
43976  int nRef;             /* Number of references to this structure */
43977  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
43978  BtLock *pLock;        /* List of locks held on this shared-btree struct */
43979  Btree *pWriter;       /* Btree with currently open write transaction */
43980  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
43981  u8 isPending;         /* If waiting for read-locks to clear */
43982#endif
43983  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
43984};
43985
43986/*
43987** An instance of the following structure is used to hold information
43988** about a cell.  The parseCellPtr() function fills in this structure
43989** based on information extract from the raw disk page.
43990*/
43991typedef struct CellInfo CellInfo;
43992struct CellInfo {
43993  u8 *pCell;     /* Pointer to the start of cell content */
43994  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
43995  u32 nData;     /* Number of bytes of data */
43996  u32 nPayload;  /* Total amount of payload */
43997  u16 nHeader;   /* Size of the cell content header in bytes */
43998  u16 nLocal;    /* Amount of payload held locally */
43999  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
44000  u16 nSize;     /* Size of the cell content on the main b-tree page */
44001};
44002
44003/*
44004** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
44005** this will be declared corrupt. This value is calculated based on a
44006** maximum database size of 2^31 pages a minimum fanout of 2 for a
44007** root-node and 3 for all other internal nodes.
44008**
44009** If a tree that appears to be taller than this is encountered, it is
44010** assumed that the database is corrupt.
44011*/
44012#define BTCURSOR_MAX_DEPTH 20
44013
44014/*
44015** A cursor is a pointer to a particular entry within a particular
44016** b-tree within a database file.
44017**
44018** The entry is identified by its MemPage and the index in
44019** MemPage.aCell[] of the entry.
44020**
44021** A single database file can shared by two more database connections,
44022** but cursors cannot be shared.  Each cursor is associated with a
44023** particular database connection identified BtCursor.pBtree.db.
44024**
44025** Fields in this structure are accessed under the BtShared.mutex
44026** found at self->pBt->mutex.
44027*/
44028struct BtCursor {
44029  Btree *pBtree;            /* The Btree to which this cursor belongs */
44030  BtShared *pBt;            /* The BtShared this cursor points to */
44031  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
44032  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
44033  Pgno pgnoRoot;            /* The root page of this tree */
44034  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
44035  CellInfo info;            /* A parse of the cell we are pointing at */
44036  u8 wrFlag;                /* True if writable */
44037  u8 atLast;                /* Cursor pointing to the last entry */
44038  u8 validNKey;             /* True if info.nKey is valid */
44039  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
44040  void *pKey;      /* Saved key that was cursor's last known position */
44041  i64 nKey;        /* Size of pKey, or last integer key */
44042  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
44043#ifndef SQLITE_OMIT_INCRBLOB
44044  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
44045  Pgno *aOverflow;          /* Cache of overflow page locations */
44046#endif
44047  i16 iPage;                            /* Index of current page in apPage */
44048  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
44049  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
44050};
44051
44052/*
44053** Potential values for BtCursor.eState.
44054**
44055** CURSOR_VALID:
44056**   Cursor points to a valid entry. getPayload() etc. may be called.
44057**
44058** CURSOR_INVALID:
44059**   Cursor does not point to a valid entry. This can happen (for example)
44060**   because the table is empty or because BtreeCursorFirst() has not been
44061**   called.
44062**
44063** CURSOR_REQUIRESEEK:
44064**   The table that this cursor was opened on still exists, but has been
44065**   modified since the cursor was last used. The cursor position is saved
44066**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
44067**   this state, restoreCursorPosition() can be called to attempt to
44068**   seek the cursor to the saved position.
44069**
44070** CURSOR_FAULT:
44071**   A unrecoverable error (an I/O error or a malloc failure) has occurred
44072**   on a different connection that shares the BtShared cache with this
44073**   cursor.  The error has left the cache in an inconsistent state.
44074**   Do nothing else with this cursor.  Any attempt to use the cursor
44075**   should return the error code stored in BtCursor.skip
44076*/
44077#define CURSOR_INVALID           0
44078#define CURSOR_VALID             1
44079#define CURSOR_REQUIRESEEK       2
44080#define CURSOR_FAULT             3
44081
44082/*
44083** The database page the PENDING_BYTE occupies. This page is never used.
44084*/
44085# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
44086
44087/*
44088** These macros define the location of the pointer-map entry for a
44089** database page. The first argument to each is the number of usable
44090** bytes on each page of the database (often 1024). The second is the
44091** page number to look up in the pointer map.
44092**
44093** PTRMAP_PAGENO returns the database page number of the pointer-map
44094** page that stores the required pointer. PTRMAP_PTROFFSET returns
44095** the offset of the requested map entry.
44096**
44097** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
44098** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
44099** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
44100** this test.
44101*/
44102#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
44103#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
44104#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
44105
44106/*
44107** The pointer map is a lookup table that identifies the parent page for
44108** each child page in the database file.  The parent page is the page that
44109** contains a pointer to the child.  Every page in the database contains
44110** 0 or 1 parent pages.  (In this context 'database page' refers
44111** to any page that is not part of the pointer map itself.)  Each pointer map
44112** entry consists of a single byte 'type' and a 4 byte parent page number.
44113** The PTRMAP_XXX identifiers below are the valid types.
44114**
44115** The purpose of the pointer map is to facility moving pages from one
44116** position in the file to another as part of autovacuum.  When a page
44117** is moved, the pointer in its parent must be updated to point to the
44118** new location.  The pointer map is used to locate the parent page quickly.
44119**
44120** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
44121**                  used in this case.
44122**
44123** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
44124**                  is not used in this case.
44125**
44126** PTRMAP_OVERFLOW1: The database page is the first page in a list of
44127**                   overflow pages. The page number identifies the page that
44128**                   contains the cell with a pointer to this overflow page.
44129**
44130** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
44131**                   overflow pages. The page-number identifies the previous
44132**                   page in the overflow page list.
44133**
44134** PTRMAP_BTREE: The database page is a non-root btree page. The page number
44135**               identifies the parent page in the btree.
44136*/
44137#define PTRMAP_ROOTPAGE 1
44138#define PTRMAP_FREEPAGE 2
44139#define PTRMAP_OVERFLOW1 3
44140#define PTRMAP_OVERFLOW2 4
44141#define PTRMAP_BTREE 5
44142
44143/* A bunch of assert() statements to check the transaction state variables
44144** of handle p (type Btree*) are internally consistent.
44145*/
44146#define btreeIntegrity(p) \
44147  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
44148  assert( p->pBt->inTransaction>=p->inTrans );
44149
44150
44151/*
44152** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
44153** if the database supports auto-vacuum or not. Because it is used
44154** within an expression that is an argument to another macro
44155** (sqliteMallocRaw), it is not possible to use conditional compilation.
44156** So, this macro is defined instead.
44157*/
44158#ifndef SQLITE_OMIT_AUTOVACUUM
44159#define ISAUTOVACUUM (pBt->autoVacuum)
44160#else
44161#define ISAUTOVACUUM 0
44162#endif
44163
44164
44165/*
44166** This structure is passed around through all the sanity checking routines
44167** in order to keep track of some global state information.
44168*/
44169typedef struct IntegrityCk IntegrityCk;
44170struct IntegrityCk {
44171  BtShared *pBt;    /* The tree being checked out */
44172  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
44173  Pgno nPage;       /* Number of pages in the database */
44174  int *anRef;       /* Number of times each page is referenced */
44175  int mxErr;        /* Stop accumulating errors when this reaches zero */
44176  int nErr;         /* Number of messages written to zErrMsg so far */
44177  int mallocFailed; /* A memory allocation error has occurred */
44178  StrAccum errMsg;  /* Accumulate the error message text here */
44179};
44180
44181/*
44182** Read or write a two- and four-byte big-endian integer values.
44183*/
44184#define get2byte(x)   ((x)[0]<<8 | (x)[1])
44185#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
44186#define get4byte sqlite3Get4byte
44187#define put4byte sqlite3Put4byte
44188
44189/************** End of btreeInt.h ********************************************/
44190/************** Continuing where we left off in btmutex.c ********************/
44191#ifndef SQLITE_OMIT_SHARED_CACHE
44192#if SQLITE_THREADSAFE
44193
44194/*
44195** Obtain the BtShared mutex associated with B-Tree handle p. Also,
44196** set BtShared.db to the database handle associated with p and the
44197** p->locked boolean to true.
44198*/
44199static void lockBtreeMutex(Btree *p){
44200  assert( p->locked==0 );
44201  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
44202  assert( sqlite3_mutex_held(p->db->mutex) );
44203
44204  sqlite3_mutex_enter(p->pBt->mutex);
44205  p->pBt->db = p->db;
44206  p->locked = 1;
44207}
44208
44209/*
44210** Release the BtShared mutex associated with B-Tree handle p and
44211** clear the p->locked boolean.
44212*/
44213static void unlockBtreeMutex(Btree *p){
44214  assert( p->locked==1 );
44215  assert( sqlite3_mutex_held(p->pBt->mutex) );
44216  assert( sqlite3_mutex_held(p->db->mutex) );
44217  assert( p->db==p->pBt->db );
44218
44219  sqlite3_mutex_leave(p->pBt->mutex);
44220  p->locked = 0;
44221}
44222
44223/*
44224** Enter a mutex on the given BTree object.
44225**
44226** If the object is not sharable, then no mutex is ever required
44227** and this routine is a no-op.  The underlying mutex is non-recursive.
44228** But we keep a reference count in Btree.wantToLock so the behavior
44229** of this interface is recursive.
44230**
44231** To avoid deadlocks, multiple Btrees are locked in the same order
44232** by all database connections.  The p->pNext is a list of other
44233** Btrees belonging to the same database connection as the p Btree
44234** which need to be locked after p.  If we cannot get a lock on
44235** p, then first unlock all of the others on p->pNext, then wait
44236** for the lock to become available on p, then relock all of the
44237** subsequent Btrees that desire a lock.
44238*/
44239SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
44240  Btree *pLater;
44241
44242  /* Some basic sanity checking on the Btree.  The list of Btrees
44243  ** connected by pNext and pPrev should be in sorted order by
44244  ** Btree.pBt value. All elements of the list should belong to
44245  ** the same connection. Only shared Btrees are on the list. */
44246  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
44247  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
44248  assert( p->pNext==0 || p->pNext->db==p->db );
44249  assert( p->pPrev==0 || p->pPrev->db==p->db );
44250  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
44251
44252  /* Check for locking consistency */
44253  assert( !p->locked || p->wantToLock>0 );
44254  assert( p->sharable || p->wantToLock==0 );
44255
44256  /* We should already hold a lock on the database connection */
44257  assert( sqlite3_mutex_held(p->db->mutex) );
44258
44259  /* Unless the database is sharable and unlocked, then BtShared.db
44260  ** should already be set correctly. */
44261  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
44262
44263  if( !p->sharable ) return;
44264  p->wantToLock++;
44265  if( p->locked ) return;
44266
44267  /* In most cases, we should be able to acquire the lock we
44268  ** want without having to go throught the ascending lock
44269  ** procedure that follows.  Just be sure not to block.
44270  */
44271  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
44272    p->pBt->db = p->db;
44273    p->locked = 1;
44274    return;
44275  }
44276
44277  /* To avoid deadlock, first release all locks with a larger
44278  ** BtShared address.  Then acquire our lock.  Then reacquire
44279  ** the other BtShared locks that we used to hold in ascending
44280  ** order.
44281  */
44282  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
44283    assert( pLater->sharable );
44284    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
44285    assert( !pLater->locked || pLater->wantToLock>0 );
44286    if( pLater->locked ){
44287      unlockBtreeMutex(pLater);
44288    }
44289  }
44290  lockBtreeMutex(p);
44291  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
44292    if( pLater->wantToLock ){
44293      lockBtreeMutex(pLater);
44294    }
44295  }
44296}
44297
44298/*
44299** Exit the recursive mutex on a Btree.
44300*/
44301SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
44302  if( p->sharable ){
44303    assert( p->wantToLock>0 );
44304    p->wantToLock--;
44305    if( p->wantToLock==0 ){
44306      unlockBtreeMutex(p);
44307    }
44308  }
44309}
44310
44311#ifndef NDEBUG
44312/*
44313** Return true if the BtShared mutex is held on the btree, or if the
44314** B-Tree is not marked as sharable.
44315**
44316** This routine is used only from within assert() statements.
44317*/
44318SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
44319  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
44320  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
44321  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
44322  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
44323
44324  return (p->sharable==0 || p->locked);
44325}
44326#endif
44327
44328
44329#ifndef SQLITE_OMIT_INCRBLOB
44330/*
44331** Enter and leave a mutex on a Btree given a cursor owned by that
44332** Btree.  These entry points are used by incremental I/O and can be
44333** omitted if that module is not used.
44334*/
44335SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
44336  sqlite3BtreeEnter(pCur->pBtree);
44337}
44338SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
44339  sqlite3BtreeLeave(pCur->pBtree);
44340}
44341#endif /* SQLITE_OMIT_INCRBLOB */
44342
44343
44344/*
44345** Enter the mutex on every Btree associated with a database
44346** connection.  This is needed (for example) prior to parsing
44347** a statement since we will be comparing table and column names
44348** against all schemas and we do not want those schemas being
44349** reset out from under us.
44350**
44351** There is a corresponding leave-all procedures.
44352**
44353** Enter the mutexes in accending order by BtShared pointer address
44354** to avoid the possibility of deadlock when two threads with
44355** two or more btrees in common both try to lock all their btrees
44356** at the same instant.
44357*/
44358SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
44359  int i;
44360  Btree *p, *pLater;
44361  assert( sqlite3_mutex_held(db->mutex) );
44362  for(i=0; i<db->nDb; i++){
44363    p = db->aDb[i].pBt;
44364    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
44365    if( p && p->sharable ){
44366      p->wantToLock++;
44367      if( !p->locked ){
44368        assert( p->wantToLock==1 );
44369        while( p->pPrev ) p = p->pPrev;
44370        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
44371        ** the chain.  Otherwise the !p->locked test above would have failed */
44372        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
44373        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
44374          if( pLater->locked ){
44375            unlockBtreeMutex(pLater);
44376          }
44377        }
44378        while( p ){
44379          lockBtreeMutex(p);
44380          p = p->pNext;
44381        }
44382      }
44383    }
44384  }
44385}
44386SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
44387  int i;
44388  Btree *p;
44389  assert( sqlite3_mutex_held(db->mutex) );
44390  for(i=0; i<db->nDb; i++){
44391    p = db->aDb[i].pBt;
44392    if( p && p->sharable ){
44393      assert( p->wantToLock>0 );
44394      p->wantToLock--;
44395      if( p->wantToLock==0 ){
44396        unlockBtreeMutex(p);
44397      }
44398    }
44399  }
44400}
44401
44402#ifndef NDEBUG
44403/*
44404** Return true if the current thread holds the database connection
44405** mutex and all required BtShared mutexes.
44406**
44407** This routine is used inside assert() statements only.
44408*/
44409SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
44410  int i;
44411  if( !sqlite3_mutex_held(db->mutex) ){
44412    return 0;
44413  }
44414  for(i=0; i<db->nDb; i++){
44415    Btree *p;
44416    p = db->aDb[i].pBt;
44417    if( p && p->sharable &&
44418         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
44419      return 0;
44420    }
44421  }
44422  return 1;
44423}
44424#endif /* NDEBUG */
44425
44426/*
44427** Add a new Btree pointer to a BtreeMutexArray.
44428** if the pointer can possibly be shared with
44429** another database connection.
44430**
44431** The pointers are kept in sorted order by pBtree->pBt.  That
44432** way when we go to enter all the mutexes, we can enter them
44433** in order without every having to backup and retry and without
44434** worrying about deadlock.
44435**
44436** The number of shared btrees will always be small (usually 0 or 1)
44437** so an insertion sort is an adequate algorithm here.
44438*/
44439SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
44440  int i, j;
44441  BtShared *pBt;
44442  if( pBtree==0 || pBtree->sharable==0 ) return;
44443#ifndef NDEBUG
44444  {
44445    for(i=0; i<pArray->nMutex; i++){
44446      assert( pArray->aBtree[i]!=pBtree );
44447    }
44448  }
44449#endif
44450  assert( pArray->nMutex>=0 );
44451  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
44452  pBt = pBtree->pBt;
44453  for(i=0; i<pArray->nMutex; i++){
44454    assert( pArray->aBtree[i]!=pBtree );
44455    if( pArray->aBtree[i]->pBt>pBt ){
44456      for(j=pArray->nMutex; j>i; j--){
44457        pArray->aBtree[j] = pArray->aBtree[j-1];
44458      }
44459      pArray->aBtree[i] = pBtree;
44460      pArray->nMutex++;
44461      return;
44462    }
44463  }
44464  pArray->aBtree[pArray->nMutex++] = pBtree;
44465}
44466
44467/*
44468** Enter the mutex of every btree in the array.  This routine is
44469** called at the beginning of sqlite3VdbeExec().  The mutexes are
44470** exited at the end of the same function.
44471*/
44472SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
44473  int i;
44474  for(i=0; i<pArray->nMutex; i++){
44475    Btree *p = pArray->aBtree[i];
44476    /* Some basic sanity checking */
44477    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
44478    assert( !p->locked || p->wantToLock>0 );
44479
44480    /* We should already hold a lock on the database connection */
44481    assert( sqlite3_mutex_held(p->db->mutex) );
44482
44483    /* The Btree is sharable because only sharable Btrees are entered
44484    ** into the array in the first place. */
44485    assert( p->sharable );
44486
44487    p->wantToLock++;
44488    if( !p->locked ){
44489      lockBtreeMutex(p);
44490    }
44491  }
44492}
44493
44494/*
44495** Leave the mutex of every btree in the group.
44496*/
44497SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
44498  int i;
44499  for(i=0; i<pArray->nMutex; i++){
44500    Btree *p = pArray->aBtree[i];
44501    /* Some basic sanity checking */
44502    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
44503    assert( p->locked );
44504    assert( p->wantToLock>0 );
44505
44506    /* We should already hold a lock on the database connection */
44507    assert( sqlite3_mutex_held(p->db->mutex) );
44508
44509    p->wantToLock--;
44510    if( p->wantToLock==0 ){
44511      unlockBtreeMutex(p);
44512    }
44513  }
44514}
44515
44516#else
44517SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
44518  p->pBt->db = p->db;
44519}
44520SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
44521  int i;
44522  for(i=0; i<db->nDb; i++){
44523    Btree *p = db->aDb[i].pBt;
44524    if( p ){
44525      p->pBt->db = p->db;
44526    }
44527  }
44528}
44529#endif /* if SQLITE_THREADSAFE */
44530#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
44531
44532/************** End of btmutex.c *********************************************/
44533/************** Begin file btree.c *******************************************/
44534/*
44535** 2004 April 6
44536**
44537** The author disclaims copyright to this source code.  In place of
44538** a legal notice, here is a blessing:
44539**
44540**    May you do good and not evil.
44541**    May you find forgiveness for yourself and forgive others.
44542**    May you share freely, never taking more than you give.
44543**
44544*************************************************************************
44545** This file implements a external (disk-based) database using BTrees.
44546** See the header comment on "btreeInt.h" for additional information.
44547** Including a description of file format and an overview of operation.
44548*/
44549
44550/*
44551** The header string that appears at the beginning of every
44552** SQLite database.
44553*/
44554static const char zMagicHeader[] = SQLITE_FILE_HEADER;
44555
44556/*
44557** Set this global variable to 1 to enable tracing using the TRACE
44558** macro.
44559*/
44560#if 0
44561int sqlite3BtreeTrace=1;  /* True to enable tracing */
44562# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
44563#else
44564# define TRACE(X)
44565#endif
44566
44567/*
44568** Extract a 2-byte big-endian integer from an array of unsigned bytes.
44569** But if the value is zero, make it 65536.
44570**
44571** This routine is used to extract the "offset to cell content area" value
44572** from the header of a btree page.  If the page size is 65536 and the page
44573** is empty, the offset should be 65536, but the 2-byte value stores zero.
44574** This routine makes the necessary adjustment to 65536.
44575*/
44576#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
44577
44578#ifndef SQLITE_OMIT_SHARED_CACHE
44579/*
44580** A list of BtShared objects that are eligible for participation
44581** in shared cache.  This variable has file scope during normal builds,
44582** but the test harness needs to access it so we make it global for
44583** test builds.
44584**
44585** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
44586*/
44587#ifdef SQLITE_TEST
44588SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
44589#else
44590static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
44591#endif
44592#endif /* SQLITE_OMIT_SHARED_CACHE */
44593
44594#ifndef SQLITE_OMIT_SHARED_CACHE
44595/*
44596** Enable or disable the shared pager and schema features.
44597**
44598** This routine has no effect on existing database connections.
44599** The shared cache setting effects only future calls to
44600** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
44601*/
44602SQLITE_API int sqlite3_enable_shared_cache(int enable){
44603  sqlite3GlobalConfig.sharedCacheEnabled = enable;
44604  return SQLITE_OK;
44605}
44606#endif
44607
44608
44609
44610#ifdef SQLITE_OMIT_SHARED_CACHE
44611  /*
44612  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
44613  ** and clearAllSharedCacheTableLocks()
44614  ** manipulate entries in the BtShared.pLock linked list used to store
44615  ** shared-cache table level locks. If the library is compiled with the
44616  ** shared-cache feature disabled, then there is only ever one user
44617  ** of each BtShared structure and so this locking is not necessary.
44618  ** So define the lock related functions as no-ops.
44619  */
44620  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
44621  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
44622  #define clearAllSharedCacheTableLocks(a)
44623  #define downgradeAllSharedCacheTableLocks(a)
44624  #define hasSharedCacheTableLock(a,b,c,d) 1
44625  #define hasReadConflicts(a, b) 0
44626#endif
44627
44628#ifndef SQLITE_OMIT_SHARED_CACHE
44629
44630#ifdef SQLITE_DEBUG
44631/*
44632**** This function is only used as part of an assert() statement. ***
44633**
44634** Check to see if pBtree holds the required locks to read or write to the
44635** table with root page iRoot.   Return 1 if it does and 0 if not.
44636**
44637** For example, when writing to a table with root-page iRoot via
44638** Btree connection pBtree:
44639**
44640**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
44641**
44642** When writing to an index that resides in a sharable database, the
44643** caller should have first obtained a lock specifying the root page of
44644** the corresponding table. This makes things a bit more complicated,
44645** as this module treats each table as a separate structure. To determine
44646** the table corresponding to the index being written, this
44647** function has to search through the database schema.
44648**
44649** Instead of a lock on the table/index rooted at page iRoot, the caller may
44650** hold a write-lock on the schema table (root page 1). This is also
44651** acceptable.
44652*/
44653static int hasSharedCacheTableLock(
44654  Btree *pBtree,         /* Handle that must hold lock */
44655  Pgno iRoot,            /* Root page of b-tree */
44656  int isIndex,           /* True if iRoot is the root of an index b-tree */
44657  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
44658){
44659  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
44660  Pgno iTab = 0;
44661  BtLock *pLock;
44662
44663  /* If this database is not shareable, or if the client is reading
44664  ** and has the read-uncommitted flag set, then no lock is required.
44665  ** Return true immediately.
44666  */
44667  if( (pBtree->sharable==0)
44668   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
44669  ){
44670    return 1;
44671  }
44672
44673  /* If the client is reading  or writing an index and the schema is
44674  ** not loaded, then it is too difficult to actually check to see if
44675  ** the correct locks are held.  So do not bother - just return true.
44676  ** This case does not come up very often anyhow.
44677  */
44678  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
44679    return 1;
44680  }
44681
44682  /* Figure out the root-page that the lock should be held on. For table
44683  ** b-trees, this is just the root page of the b-tree being read or
44684  ** written. For index b-trees, it is the root page of the associated
44685  ** table.  */
44686  if( isIndex ){
44687    HashElem *p;
44688    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
44689      Index *pIdx = (Index *)sqliteHashData(p);
44690      if( pIdx->tnum==(int)iRoot ){
44691        iTab = pIdx->pTable->tnum;
44692      }
44693    }
44694  }else{
44695    iTab = iRoot;
44696  }
44697
44698  /* Search for the required lock. Either a write-lock on root-page iTab, a
44699  ** write-lock on the schema table, or (if the client is reading) a
44700  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
44701  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
44702    if( pLock->pBtree==pBtree
44703     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
44704     && pLock->eLock>=eLockType
44705    ){
44706      return 1;
44707    }
44708  }
44709
44710  /* Failed to find the required lock. */
44711  return 0;
44712}
44713#endif /* SQLITE_DEBUG */
44714
44715#ifdef SQLITE_DEBUG
44716/*
44717**** This function may be used as part of assert() statements only. ****
44718**
44719** Return true if it would be illegal for pBtree to write into the
44720** table or index rooted at iRoot because other shared connections are
44721** simultaneously reading that same table or index.
44722**
44723** It is illegal for pBtree to write if some other Btree object that
44724** shares the same BtShared object is currently reading or writing
44725** the iRoot table.  Except, if the other Btree object has the
44726** read-uncommitted flag set, then it is OK for the other object to
44727** have a read cursor.
44728**
44729** For example, before writing to any part of the table or index
44730** rooted at page iRoot, one should call:
44731**
44732**    assert( !hasReadConflicts(pBtree, iRoot) );
44733*/
44734static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
44735  BtCursor *p;
44736  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
44737    if( p->pgnoRoot==iRoot
44738     && p->pBtree!=pBtree
44739     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
44740    ){
44741      return 1;
44742    }
44743  }
44744  return 0;
44745}
44746#endif    /* #ifdef SQLITE_DEBUG */
44747
44748/*
44749** Query to see if Btree handle p may obtain a lock of type eLock
44750** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
44751** SQLITE_OK if the lock may be obtained (by calling
44752** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
44753*/
44754static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
44755  BtShared *pBt = p->pBt;
44756  BtLock *pIter;
44757
44758  assert( sqlite3BtreeHoldsMutex(p) );
44759  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
44760  assert( p->db!=0 );
44761  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
44762
44763  /* If requesting a write-lock, then the Btree must have an open write
44764  ** transaction on this file. And, obviously, for this to be so there
44765  ** must be an open write transaction on the file itself.
44766  */
44767  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
44768  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
44769
44770  /* This routine is a no-op if the shared-cache is not enabled */
44771  if( !p->sharable ){
44772    return SQLITE_OK;
44773  }
44774
44775  /* If some other connection is holding an exclusive lock, the
44776  ** requested lock may not be obtained.
44777  */
44778  if( pBt->pWriter!=p && pBt->isExclusive ){
44779    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
44780    return SQLITE_LOCKED_SHAREDCACHE;
44781  }
44782
44783  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
44784    /* The condition (pIter->eLock!=eLock) in the following if(...)
44785    ** statement is a simplification of:
44786    **
44787    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
44788    **
44789    ** since we know that if eLock==WRITE_LOCK, then no other connection
44790    ** may hold a WRITE_LOCK on any table in this file (since there can
44791    ** only be a single writer).
44792    */
44793    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
44794    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
44795    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
44796      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
44797      if( eLock==WRITE_LOCK ){
44798        assert( p==pBt->pWriter );
44799        pBt->isPending = 1;
44800      }
44801      return SQLITE_LOCKED_SHAREDCACHE;
44802    }
44803  }
44804  return SQLITE_OK;
44805}
44806#endif /* !SQLITE_OMIT_SHARED_CACHE */
44807
44808#ifndef SQLITE_OMIT_SHARED_CACHE
44809/*
44810** Add a lock on the table with root-page iTable to the shared-btree used
44811** by Btree handle p. Parameter eLock must be either READ_LOCK or
44812** WRITE_LOCK.
44813**
44814** This function assumes the following:
44815**
44816**   (a) The specified Btree object p is connected to a sharable
44817**       database (one with the BtShared.sharable flag set), and
44818**
44819**   (b) No other Btree objects hold a lock that conflicts
44820**       with the requested lock (i.e. querySharedCacheTableLock() has
44821**       already been called and returned SQLITE_OK).
44822**
44823** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
44824** is returned if a malloc attempt fails.
44825*/
44826static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
44827  BtShared *pBt = p->pBt;
44828  BtLock *pLock = 0;
44829  BtLock *pIter;
44830
44831  assert( sqlite3BtreeHoldsMutex(p) );
44832  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
44833  assert( p->db!=0 );
44834
44835  /* A connection with the read-uncommitted flag set will never try to
44836  ** obtain a read-lock using this function. The only read-lock obtained
44837  ** by a connection in read-uncommitted mode is on the sqlite_master
44838  ** table, and that lock is obtained in BtreeBeginTrans().  */
44839  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
44840
44841  /* This function should only be called on a sharable b-tree after it
44842  ** has been determined that no other b-tree holds a conflicting lock.  */
44843  assert( p->sharable );
44844  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
44845
44846  /* First search the list for an existing lock on this table. */
44847  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
44848    if( pIter->iTable==iTable && pIter->pBtree==p ){
44849      pLock = pIter;
44850      break;
44851    }
44852  }
44853
44854  /* If the above search did not find a BtLock struct associating Btree p
44855  ** with table iTable, allocate one and link it into the list.
44856  */
44857  if( !pLock ){
44858    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
44859    if( !pLock ){
44860      return SQLITE_NOMEM;
44861    }
44862    pLock->iTable = iTable;
44863    pLock->pBtree = p;
44864    pLock->pNext = pBt->pLock;
44865    pBt->pLock = pLock;
44866  }
44867
44868  /* Set the BtLock.eLock variable to the maximum of the current lock
44869  ** and the requested lock. This means if a write-lock was already held
44870  ** and a read-lock requested, we don't incorrectly downgrade the lock.
44871  */
44872  assert( WRITE_LOCK>READ_LOCK );
44873  if( eLock>pLock->eLock ){
44874    pLock->eLock = eLock;
44875  }
44876
44877  return SQLITE_OK;
44878}
44879#endif /* !SQLITE_OMIT_SHARED_CACHE */
44880
44881#ifndef SQLITE_OMIT_SHARED_CACHE
44882/*
44883** Release all the table locks (locks obtained via calls to
44884** the setSharedCacheTableLock() procedure) held by Btree object p.
44885**
44886** This function assumes that Btree p has an open read or write
44887** transaction. If it does not, then the BtShared.isPending variable
44888** may be incorrectly cleared.
44889*/
44890static void clearAllSharedCacheTableLocks(Btree *p){
44891  BtShared *pBt = p->pBt;
44892  BtLock **ppIter = &pBt->pLock;
44893
44894  assert( sqlite3BtreeHoldsMutex(p) );
44895  assert( p->sharable || 0==*ppIter );
44896  assert( p->inTrans>0 );
44897
44898  while( *ppIter ){
44899    BtLock *pLock = *ppIter;
44900    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
44901    assert( pLock->pBtree->inTrans>=pLock->eLock );
44902    if( pLock->pBtree==p ){
44903      *ppIter = pLock->pNext;
44904      assert( pLock->iTable!=1 || pLock==&p->lock );
44905      if( pLock->iTable!=1 ){
44906        sqlite3_free(pLock);
44907      }
44908    }else{
44909      ppIter = &pLock->pNext;
44910    }
44911  }
44912
44913  assert( pBt->isPending==0 || pBt->pWriter );
44914  if( pBt->pWriter==p ){
44915    pBt->pWriter = 0;
44916    pBt->isExclusive = 0;
44917    pBt->isPending = 0;
44918  }else if( pBt->nTransaction==2 ){
44919    /* This function is called when Btree p is concluding its
44920    ** transaction. If there currently exists a writer, and p is not
44921    ** that writer, then the number of locks held by connections other
44922    ** than the writer must be about to drop to zero. In this case
44923    ** set the isPending flag to 0.
44924    **
44925    ** If there is not currently a writer, then BtShared.isPending must
44926    ** be zero already. So this next line is harmless in that case.
44927    */
44928    pBt->isPending = 0;
44929  }
44930}
44931
44932/*
44933** This function changes all write-locks held by Btree p into read-locks.
44934*/
44935static void downgradeAllSharedCacheTableLocks(Btree *p){
44936  BtShared *pBt = p->pBt;
44937  if( pBt->pWriter==p ){
44938    BtLock *pLock;
44939    pBt->pWriter = 0;
44940    pBt->isExclusive = 0;
44941    pBt->isPending = 0;
44942    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
44943      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
44944      pLock->eLock = READ_LOCK;
44945    }
44946  }
44947}
44948
44949#endif /* SQLITE_OMIT_SHARED_CACHE */
44950
44951static void releasePage(MemPage *pPage);  /* Forward reference */
44952
44953/*
44954***** This routine is used inside of assert() only ****
44955**
44956** Verify that the cursor holds the mutex on its BtShared
44957*/
44958#ifdef SQLITE_DEBUG
44959static int cursorHoldsMutex(BtCursor *p){
44960  return sqlite3_mutex_held(p->pBt->mutex);
44961}
44962#endif
44963
44964
44965#ifndef SQLITE_OMIT_INCRBLOB
44966/*
44967** Invalidate the overflow page-list cache for cursor pCur, if any.
44968*/
44969static void invalidateOverflowCache(BtCursor *pCur){
44970  assert( cursorHoldsMutex(pCur) );
44971  sqlite3_free(pCur->aOverflow);
44972  pCur->aOverflow = 0;
44973}
44974
44975/*
44976** Invalidate the overflow page-list cache for all cursors opened
44977** on the shared btree structure pBt.
44978*/
44979static void invalidateAllOverflowCache(BtShared *pBt){
44980  BtCursor *p;
44981  assert( sqlite3_mutex_held(pBt->mutex) );
44982  for(p=pBt->pCursor; p; p=p->pNext){
44983    invalidateOverflowCache(p);
44984  }
44985}
44986
44987/*
44988** This function is called before modifying the contents of a table
44989** to invalidate any incrblob cursors that are open on the
44990** row or one of the rows being modified.
44991**
44992** If argument isClearTable is true, then the entire contents of the
44993** table is about to be deleted. In this case invalidate all incrblob
44994** cursors open on any row within the table with root-page pgnoRoot.
44995**
44996** Otherwise, if argument isClearTable is false, then the row with
44997** rowid iRow is being replaced or deleted. In this case invalidate
44998** only those incrblob cursors open on that specific row.
44999*/
45000static void invalidateIncrblobCursors(
45001  Btree *pBtree,          /* The database file to check */
45002  i64 iRow,               /* The rowid that might be changing */
45003  int isClearTable        /* True if all rows are being deleted */
45004){
45005  BtCursor *p;
45006  BtShared *pBt = pBtree->pBt;
45007  assert( sqlite3BtreeHoldsMutex(pBtree) );
45008  for(p=pBt->pCursor; p; p=p->pNext){
45009    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
45010      p->eState = CURSOR_INVALID;
45011    }
45012  }
45013}
45014
45015#else
45016  /* Stub functions when INCRBLOB is omitted */
45017  #define invalidateOverflowCache(x)
45018  #define invalidateAllOverflowCache(x)
45019  #define invalidateIncrblobCursors(x,y,z)
45020#endif /* SQLITE_OMIT_INCRBLOB */
45021
45022/*
45023** Set bit pgno of the BtShared.pHasContent bitvec. This is called
45024** when a page that previously contained data becomes a free-list leaf
45025** page.
45026**
45027** The BtShared.pHasContent bitvec exists to work around an obscure
45028** bug caused by the interaction of two useful IO optimizations surrounding
45029** free-list leaf pages:
45030**
45031**   1) When all data is deleted from a page and the page becomes
45032**      a free-list leaf page, the page is not written to the database
45033**      (as free-list leaf pages contain no meaningful data). Sometimes
45034**      such a page is not even journalled (as it will not be modified,
45035**      why bother journalling it?).
45036**
45037**   2) When a free-list leaf page is reused, its content is not read
45038**      from the database or written to the journal file (why should it
45039**      be, if it is not at all meaningful?).
45040**
45041** By themselves, these optimizations work fine and provide a handy
45042** performance boost to bulk delete or insert operations. However, if
45043** a page is moved to the free-list and then reused within the same
45044** transaction, a problem comes up. If the page is not journalled when
45045** it is moved to the free-list and it is also not journalled when it
45046** is extracted from the free-list and reused, then the original data
45047** may be lost. In the event of a rollback, it may not be possible
45048** to restore the database to its original configuration.
45049**
45050** The solution is the BtShared.pHasContent bitvec. Whenever a page is
45051** moved to become a free-list leaf page, the corresponding bit is
45052** set in the bitvec. Whenever a leaf page is extracted from the free-list,
45053** optimization 2 above is omitted if the corresponding bit is already
45054** set in BtShared.pHasContent. The contents of the bitvec are cleared
45055** at the end of every transaction.
45056*/
45057static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
45058  int rc = SQLITE_OK;
45059  if( !pBt->pHasContent ){
45060    assert( pgno<=pBt->nPage );
45061    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
45062    if( !pBt->pHasContent ){
45063      rc = SQLITE_NOMEM;
45064    }
45065  }
45066  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
45067    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
45068  }
45069  return rc;
45070}
45071
45072/*
45073** Query the BtShared.pHasContent vector.
45074**
45075** This function is called when a free-list leaf page is removed from the
45076** free-list for reuse. It returns false if it is safe to retrieve the
45077** page from the pager layer with the 'no-content' flag set. True otherwise.
45078*/
45079static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
45080  Bitvec *p = pBt->pHasContent;
45081  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
45082}
45083
45084/*
45085** Clear (destroy) the BtShared.pHasContent bitvec. This should be
45086** invoked at the conclusion of each write-transaction.
45087*/
45088static void btreeClearHasContent(BtShared *pBt){
45089  sqlite3BitvecDestroy(pBt->pHasContent);
45090  pBt->pHasContent = 0;
45091}
45092
45093/*
45094** Save the current cursor position in the variables BtCursor.nKey
45095** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
45096**
45097** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
45098** prior to calling this routine.
45099*/
45100static int saveCursorPosition(BtCursor *pCur){
45101  int rc;
45102
45103  assert( CURSOR_VALID==pCur->eState );
45104  assert( 0==pCur->pKey );
45105  assert( cursorHoldsMutex(pCur) );
45106
45107  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
45108  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
45109
45110  /* If this is an intKey table, then the above call to BtreeKeySize()
45111  ** stores the integer key in pCur->nKey. In this case this value is
45112  ** all that is required. Otherwise, if pCur is not open on an intKey
45113  ** table, then malloc space for and store the pCur->nKey bytes of key
45114  ** data.
45115  */
45116  if( 0==pCur->apPage[0]->intKey ){
45117    void *pKey = sqlite3Malloc( (int)pCur->nKey );
45118    if( pKey ){
45119      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
45120      if( rc==SQLITE_OK ){
45121        pCur->pKey = pKey;
45122      }else{
45123        sqlite3_free(pKey);
45124      }
45125    }else{
45126      rc = SQLITE_NOMEM;
45127    }
45128  }
45129  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
45130
45131  if( rc==SQLITE_OK ){
45132    int i;
45133    for(i=0; i<=pCur->iPage; i++){
45134      releasePage(pCur->apPage[i]);
45135      pCur->apPage[i] = 0;
45136    }
45137    pCur->iPage = -1;
45138    pCur->eState = CURSOR_REQUIRESEEK;
45139  }
45140
45141  invalidateOverflowCache(pCur);
45142  return rc;
45143}
45144
45145/*
45146** Save the positions of all cursors (except pExcept) that are open on
45147** the table  with root-page iRoot. Usually, this is called just before cursor
45148** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
45149*/
45150static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
45151  BtCursor *p;
45152  assert( sqlite3_mutex_held(pBt->mutex) );
45153  assert( pExcept==0 || pExcept->pBt==pBt );
45154  for(p=pBt->pCursor; p; p=p->pNext){
45155    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
45156        p->eState==CURSOR_VALID ){
45157      int rc = saveCursorPosition(p);
45158      if( SQLITE_OK!=rc ){
45159        return rc;
45160      }
45161    }
45162  }
45163  return SQLITE_OK;
45164}
45165
45166/*
45167** Clear the current cursor position.
45168*/
45169SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
45170  assert( cursorHoldsMutex(pCur) );
45171  sqlite3_free(pCur->pKey);
45172  pCur->pKey = 0;
45173  pCur->eState = CURSOR_INVALID;
45174}
45175
45176/*
45177** In this version of BtreeMoveto, pKey is a packed index record
45178** such as is generated by the OP_MakeRecord opcode.  Unpack the
45179** record and then call BtreeMovetoUnpacked() to do the work.
45180*/
45181static int btreeMoveto(
45182  BtCursor *pCur,     /* Cursor open on the btree to be searched */
45183  const void *pKey,   /* Packed key if the btree is an index */
45184  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
45185  int bias,           /* Bias search to the high end */
45186  int *pRes           /* Write search results here */
45187){
45188  int rc;                    /* Status code */
45189  UnpackedRecord *pIdxKey;   /* Unpacked index key */
45190  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
45191
45192  if( pKey ){
45193    assert( nKey==(i64)(int)nKey );
45194    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
45195                                      aSpace, sizeof(aSpace));
45196    if( pIdxKey==0 ) return SQLITE_NOMEM;
45197  }else{
45198    pIdxKey = 0;
45199  }
45200  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
45201  if( pKey ){
45202    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
45203  }
45204  return rc;
45205}
45206
45207/*
45208** Restore the cursor to the position it was in (or as close to as possible)
45209** when saveCursorPosition() was called. Note that this call deletes the
45210** saved position info stored by saveCursorPosition(), so there can be
45211** at most one effective restoreCursorPosition() call after each
45212** saveCursorPosition().
45213*/
45214static int btreeRestoreCursorPosition(BtCursor *pCur){
45215  int rc;
45216  assert( cursorHoldsMutex(pCur) );
45217  assert( pCur->eState>=CURSOR_REQUIRESEEK );
45218  if( pCur->eState==CURSOR_FAULT ){
45219    return pCur->skipNext;
45220  }
45221  pCur->eState = CURSOR_INVALID;
45222  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
45223  if( rc==SQLITE_OK ){
45224    sqlite3_free(pCur->pKey);
45225    pCur->pKey = 0;
45226    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
45227  }
45228  return rc;
45229}
45230
45231#define restoreCursorPosition(p) \
45232  (p->eState>=CURSOR_REQUIRESEEK ? \
45233         btreeRestoreCursorPosition(p) : \
45234         SQLITE_OK)
45235
45236/*
45237** Determine whether or not a cursor has moved from the position it
45238** was last placed at.  Cursors can move when the row they are pointing
45239** at is deleted out from under them.
45240**
45241** This routine returns an error code if something goes wrong.  The
45242** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
45243*/
45244SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
45245  int rc;
45246
45247  rc = restoreCursorPosition(pCur);
45248  if( rc ){
45249    *pHasMoved = 1;
45250    return rc;
45251  }
45252  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
45253    *pHasMoved = 1;
45254  }else{
45255    *pHasMoved = 0;
45256  }
45257  return SQLITE_OK;
45258}
45259
45260#ifndef SQLITE_OMIT_AUTOVACUUM
45261/*
45262** Given a page number of a regular database page, return the page
45263** number for the pointer-map page that contains the entry for the
45264** input page number.
45265**
45266** Return 0 (not a valid page) for pgno==1 since there is
45267** no pointer map associated with page 1.  The integrity_check logic
45268** requires that ptrmapPageno(*,1)!=1.
45269*/
45270static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
45271  int nPagesPerMapPage;
45272  Pgno iPtrMap, ret;
45273  assert( sqlite3_mutex_held(pBt->mutex) );
45274  if( pgno<2 ) return 0;
45275  nPagesPerMapPage = (pBt->usableSize/5)+1;
45276  iPtrMap = (pgno-2)/nPagesPerMapPage;
45277  ret = (iPtrMap*nPagesPerMapPage) + 2;
45278  if( ret==PENDING_BYTE_PAGE(pBt) ){
45279    ret++;
45280  }
45281  return ret;
45282}
45283
45284/*
45285** Write an entry into the pointer map.
45286**
45287** This routine updates the pointer map entry for page number 'key'
45288** so that it maps to type 'eType' and parent page number 'pgno'.
45289**
45290** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
45291** a no-op.  If an error occurs, the appropriate error code is written
45292** into *pRC.
45293*/
45294static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
45295  DbPage *pDbPage;  /* The pointer map page */
45296  u8 *pPtrmap;      /* The pointer map data */
45297  Pgno iPtrmap;     /* The pointer map page number */
45298  int offset;       /* Offset in pointer map page */
45299  int rc;           /* Return code from subfunctions */
45300
45301  if( *pRC ) return;
45302
45303  assert( sqlite3_mutex_held(pBt->mutex) );
45304  /* The master-journal page number must never be used as a pointer map page */
45305  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
45306
45307  assert( pBt->autoVacuum );
45308  if( key==0 ){
45309    *pRC = SQLITE_CORRUPT_BKPT;
45310    return;
45311  }
45312  iPtrmap = PTRMAP_PAGENO(pBt, key);
45313  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
45314  if( rc!=SQLITE_OK ){
45315    *pRC = rc;
45316    return;
45317  }
45318  offset = PTRMAP_PTROFFSET(iPtrmap, key);
45319  if( offset<0 ){
45320    *pRC = SQLITE_CORRUPT_BKPT;
45321    goto ptrmap_exit;
45322  }
45323  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
45324
45325  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
45326    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
45327    *pRC= rc = sqlite3PagerWrite(pDbPage);
45328    if( rc==SQLITE_OK ){
45329      pPtrmap[offset] = eType;
45330      put4byte(&pPtrmap[offset+1], parent);
45331    }
45332  }
45333
45334ptrmap_exit:
45335  sqlite3PagerUnref(pDbPage);
45336}
45337
45338/*
45339** Read an entry from the pointer map.
45340**
45341** This routine retrieves the pointer map entry for page 'key', writing
45342** the type and parent page number to *pEType and *pPgno respectively.
45343** An error code is returned if something goes wrong, otherwise SQLITE_OK.
45344*/
45345static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
45346  DbPage *pDbPage;   /* The pointer map page */
45347  int iPtrmap;       /* Pointer map page index */
45348  u8 *pPtrmap;       /* Pointer map page data */
45349  int offset;        /* Offset of entry in pointer map */
45350  int rc;
45351
45352  assert( sqlite3_mutex_held(pBt->mutex) );
45353
45354  iPtrmap = PTRMAP_PAGENO(pBt, key);
45355  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
45356  if( rc!=0 ){
45357    return rc;
45358  }
45359  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
45360
45361  offset = PTRMAP_PTROFFSET(iPtrmap, key);
45362  assert( pEType!=0 );
45363  *pEType = pPtrmap[offset];
45364  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
45365
45366  sqlite3PagerUnref(pDbPage);
45367  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
45368  return SQLITE_OK;
45369}
45370
45371#else /* if defined SQLITE_OMIT_AUTOVACUUM */
45372  #define ptrmapPut(w,x,y,z,rc)
45373  #define ptrmapGet(w,x,y,z) SQLITE_OK
45374  #define ptrmapPutOvflPtr(x, y, rc)
45375#endif
45376
45377/*
45378** Given a btree page and a cell index (0 means the first cell on
45379** the page, 1 means the second cell, and so forth) return a pointer
45380** to the cell content.
45381**
45382** This routine works only for pages that do not contain overflow cells.
45383*/
45384#define findCell(P,I) \
45385  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
45386
45387/*
45388** This a more complex version of findCell() that works for
45389** pages that do contain overflow cells.
45390*/
45391static u8 *findOverflowCell(MemPage *pPage, int iCell){
45392  int i;
45393  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45394  for(i=pPage->nOverflow-1; i>=0; i--){
45395    int k;
45396    struct _OvflCell *pOvfl;
45397    pOvfl = &pPage->aOvfl[i];
45398    k = pOvfl->idx;
45399    if( k<=iCell ){
45400      if( k==iCell ){
45401        return pOvfl->pCell;
45402      }
45403      iCell--;
45404    }
45405  }
45406  return findCell(pPage, iCell);
45407}
45408
45409/*
45410** Parse a cell content block and fill in the CellInfo structure.  There
45411** are two versions of this function.  btreeParseCell() takes a
45412** cell index as the second argument and btreeParseCellPtr()
45413** takes a pointer to the body of the cell as its second argument.
45414**
45415** Within this file, the parseCell() macro can be called instead of
45416** btreeParseCellPtr(). Using some compilers, this will be faster.
45417*/
45418static void btreeParseCellPtr(
45419  MemPage *pPage,         /* Page containing the cell */
45420  u8 *pCell,              /* Pointer to the cell text. */
45421  CellInfo *pInfo         /* Fill in this structure */
45422){
45423  u16 n;                  /* Number bytes in cell content header */
45424  u32 nPayload;           /* Number of bytes of cell payload */
45425
45426  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45427
45428  pInfo->pCell = pCell;
45429  assert( pPage->leaf==0 || pPage->leaf==1 );
45430  n = pPage->childPtrSize;
45431  assert( n==4-4*pPage->leaf );
45432  if( pPage->intKey ){
45433    if( pPage->hasData ){
45434      n += getVarint32(&pCell[n], nPayload);
45435    }else{
45436      nPayload = 0;
45437    }
45438    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
45439    pInfo->nData = nPayload;
45440  }else{
45441    pInfo->nData = 0;
45442    n += getVarint32(&pCell[n], nPayload);
45443    pInfo->nKey = nPayload;
45444  }
45445  pInfo->nPayload = nPayload;
45446  pInfo->nHeader = n;
45447  testcase( nPayload==pPage->maxLocal );
45448  testcase( nPayload==pPage->maxLocal+1 );
45449  if( likely(nPayload<=pPage->maxLocal) ){
45450    /* This is the (easy) common case where the entire payload fits
45451    ** on the local page.  No overflow is required.
45452    */
45453    int nSize;          /* Total size of cell content in bytes */
45454    nSize = nPayload + n;
45455    pInfo->nLocal = (u16)nPayload;
45456    pInfo->iOverflow = 0;
45457    if( (nSize & ~3)==0 ){
45458      nSize = 4;        /* Minimum cell size is 4 */
45459    }
45460    pInfo->nSize = (u16)nSize;
45461  }else{
45462    /* If the payload will not fit completely on the local page, we have
45463    ** to decide how much to store locally and how much to spill onto
45464    ** overflow pages.  The strategy is to minimize the amount of unused
45465    ** space on overflow pages while keeping the amount of local storage
45466    ** in between minLocal and maxLocal.
45467    **
45468    ** Warning:  changing the way overflow payload is distributed in any
45469    ** way will result in an incompatible file format.
45470    */
45471    int minLocal;  /* Minimum amount of payload held locally */
45472    int maxLocal;  /* Maximum amount of payload held locally */
45473    int surplus;   /* Overflow payload available for local storage */
45474
45475    minLocal = pPage->minLocal;
45476    maxLocal = pPage->maxLocal;
45477    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
45478    testcase( surplus==maxLocal );
45479    testcase( surplus==maxLocal+1 );
45480    if( surplus <= maxLocal ){
45481      pInfo->nLocal = (u16)surplus;
45482    }else{
45483      pInfo->nLocal = (u16)minLocal;
45484    }
45485    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
45486    pInfo->nSize = pInfo->iOverflow + 4;
45487  }
45488}
45489#define parseCell(pPage, iCell, pInfo) \
45490  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
45491static void btreeParseCell(
45492  MemPage *pPage,         /* Page containing the cell */
45493  int iCell,              /* The cell index.  First cell is 0 */
45494  CellInfo *pInfo         /* Fill in this structure */
45495){
45496  parseCell(pPage, iCell, pInfo);
45497}
45498
45499/*
45500** Compute the total number of bytes that a Cell needs in the cell
45501** data area of the btree-page.  The return number includes the cell
45502** data header and the local payload, but not any overflow page or
45503** the space used by the cell pointer.
45504*/
45505static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
45506  u8 *pIter = &pCell[pPage->childPtrSize];
45507  u32 nSize;
45508
45509#ifdef SQLITE_DEBUG
45510  /* The value returned by this function should always be the same as
45511  ** the (CellInfo.nSize) value found by doing a full parse of the
45512  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
45513  ** this function verifies that this invariant is not violated. */
45514  CellInfo debuginfo;
45515  btreeParseCellPtr(pPage, pCell, &debuginfo);
45516#endif
45517
45518  if( pPage->intKey ){
45519    u8 *pEnd;
45520    if( pPage->hasData ){
45521      pIter += getVarint32(pIter, nSize);
45522    }else{
45523      nSize = 0;
45524    }
45525
45526    /* pIter now points at the 64-bit integer key value, a variable length
45527    ** integer. The following block moves pIter to point at the first byte
45528    ** past the end of the key value. */
45529    pEnd = &pIter[9];
45530    while( (*pIter++)&0x80 && pIter<pEnd );
45531  }else{
45532    pIter += getVarint32(pIter, nSize);
45533  }
45534
45535  testcase( nSize==pPage->maxLocal );
45536  testcase( nSize==pPage->maxLocal+1 );
45537  if( nSize>pPage->maxLocal ){
45538    int minLocal = pPage->minLocal;
45539    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
45540    testcase( nSize==pPage->maxLocal );
45541    testcase( nSize==pPage->maxLocal+1 );
45542    if( nSize>pPage->maxLocal ){
45543      nSize = minLocal;
45544    }
45545    nSize += 4;
45546  }
45547  nSize += (u32)(pIter - pCell);
45548
45549  /* The minimum size of any cell is 4 bytes. */
45550  if( nSize<4 ){
45551    nSize = 4;
45552  }
45553
45554  assert( nSize==debuginfo.nSize );
45555  return (u16)nSize;
45556}
45557
45558#ifdef SQLITE_DEBUG
45559/* This variation on cellSizePtr() is used inside of assert() statements
45560** only. */
45561static u16 cellSize(MemPage *pPage, int iCell){
45562  return cellSizePtr(pPage, findCell(pPage, iCell));
45563}
45564#endif
45565
45566#ifndef SQLITE_OMIT_AUTOVACUUM
45567/*
45568** If the cell pCell, part of page pPage contains a pointer
45569** to an overflow page, insert an entry into the pointer-map
45570** for the overflow page.
45571*/
45572static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
45573  CellInfo info;
45574  if( *pRC ) return;
45575  assert( pCell!=0 );
45576  btreeParseCellPtr(pPage, pCell, &info);
45577  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
45578  if( info.iOverflow ){
45579    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
45580    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
45581  }
45582}
45583#endif
45584
45585
45586/*
45587** Defragment the page given.  All Cells are moved to the
45588** end of the page and all free space is collected into one
45589** big FreeBlk that occurs in between the header and cell
45590** pointer array and the cell content area.
45591*/
45592static int defragmentPage(MemPage *pPage){
45593  int i;                     /* Loop counter */
45594  int pc;                    /* Address of a i-th cell */
45595  int hdr;                   /* Offset to the page header */
45596  int size;                  /* Size of a cell */
45597  int usableSize;            /* Number of usable bytes on a page */
45598  int cellOffset;            /* Offset to the cell pointer array */
45599  int cbrk;                  /* Offset to the cell content area */
45600  int nCell;                 /* Number of cells on the page */
45601  unsigned char *data;       /* The page data */
45602  unsigned char *temp;       /* Temp area for cell content */
45603  int iCellFirst;            /* First allowable cell index */
45604  int iCellLast;             /* Last possible cell index */
45605
45606
45607  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45608  assert( pPage->pBt!=0 );
45609  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
45610  assert( pPage->nOverflow==0 );
45611  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45612  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
45613  data = pPage->aData;
45614  hdr = pPage->hdrOffset;
45615  cellOffset = pPage->cellOffset;
45616  nCell = pPage->nCell;
45617  assert( nCell==get2byte(&data[hdr+3]) );
45618  usableSize = pPage->pBt->usableSize;
45619  cbrk = get2byte(&data[hdr+5]);
45620  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
45621  cbrk = usableSize;
45622  iCellFirst = cellOffset + 2*nCell;
45623  iCellLast = usableSize - 4;
45624  for(i=0; i<nCell; i++){
45625    u8 *pAddr;     /* The i-th cell pointer */
45626    pAddr = &data[cellOffset + i*2];
45627    pc = get2byte(pAddr);
45628    testcase( pc==iCellFirst );
45629    testcase( pc==iCellLast );
45630#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
45631    /* These conditions have already been verified in btreeInitPage()
45632    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
45633    */
45634    if( pc<iCellFirst || pc>iCellLast ){
45635      return SQLITE_CORRUPT_BKPT;
45636    }
45637#endif
45638    assert( pc>=iCellFirst && pc<=iCellLast );
45639    size = cellSizePtr(pPage, &temp[pc]);
45640    cbrk -= size;
45641#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
45642    if( cbrk<iCellFirst ){
45643      return SQLITE_CORRUPT_BKPT;
45644    }
45645#else
45646    if( cbrk<iCellFirst || pc+size>usableSize ){
45647      return SQLITE_CORRUPT_BKPT;
45648    }
45649#endif
45650    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
45651    testcase( cbrk+size==usableSize );
45652    testcase( pc+size==usableSize );
45653    memcpy(&data[cbrk], &temp[pc], size);
45654    put2byte(pAddr, cbrk);
45655  }
45656  assert( cbrk>=iCellFirst );
45657  put2byte(&data[hdr+5], cbrk);
45658  data[hdr+1] = 0;
45659  data[hdr+2] = 0;
45660  data[hdr+7] = 0;
45661  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
45662  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45663  if( cbrk-iCellFirst!=pPage->nFree ){
45664    return SQLITE_CORRUPT_BKPT;
45665  }
45666  return SQLITE_OK;
45667}
45668
45669/*
45670** Allocate nByte bytes of space from within the B-Tree page passed
45671** as the first argument. Write into *pIdx the index into pPage->aData[]
45672** of the first byte of allocated space. Return either SQLITE_OK or
45673** an error code (usually SQLITE_CORRUPT).
45674**
45675** The caller guarantees that there is sufficient space to make the
45676** allocation.  This routine might need to defragment in order to bring
45677** all the space together, however.  This routine will avoid using
45678** the first two bytes past the cell pointer area since presumably this
45679** allocation is being made in order to insert a new cell, so we will
45680** also end up needing a new cell pointer.
45681*/
45682static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
45683  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
45684  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
45685  int nFrag;                           /* Number of fragmented bytes on pPage */
45686  int top;                             /* First byte of cell content area */
45687  int gap;        /* First byte of gap between cell pointers and cell content */
45688  int rc;         /* Integer return code */
45689  int usableSize; /* Usable size of the page */
45690
45691  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45692  assert( pPage->pBt );
45693  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45694  assert( nByte>=0 );  /* Minimum cell size is 4 */
45695  assert( pPage->nFree>=nByte );
45696  assert( pPage->nOverflow==0 );
45697  usableSize = pPage->pBt->usableSize;
45698  assert( nByte < usableSize-8 );
45699
45700  nFrag = data[hdr+7];
45701  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
45702  gap = pPage->cellOffset + 2*pPage->nCell;
45703  top = get2byteNotZero(&data[hdr+5]);
45704  if( gap>top ) return SQLITE_CORRUPT_BKPT;
45705  testcase( gap+2==top );
45706  testcase( gap+1==top );
45707  testcase( gap==top );
45708
45709  if( nFrag>=60 ){
45710    /* Always defragment highly fragmented pages */
45711    rc = defragmentPage(pPage);
45712    if( rc ) return rc;
45713    top = get2byteNotZero(&data[hdr+5]);
45714  }else if( gap+2<=top ){
45715    /* Search the freelist looking for a free slot big enough to satisfy
45716    ** the request. The allocation is made from the first free slot in
45717    ** the list that is large enough to accomadate it.
45718    */
45719    int pc, addr;
45720    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
45721      int size;            /* Size of the free slot */
45722      if( pc>usableSize-4 || pc<addr+4 ){
45723        return SQLITE_CORRUPT_BKPT;
45724      }
45725      size = get2byte(&data[pc+2]);
45726      if( size>=nByte ){
45727        int x = size - nByte;
45728        testcase( x==4 );
45729        testcase( x==3 );
45730        if( x<4 ){
45731          /* Remove the slot from the free-list. Update the number of
45732          ** fragmented bytes within the page. */
45733          memcpy(&data[addr], &data[pc], 2);
45734          data[hdr+7] = (u8)(nFrag + x);
45735        }else if( size+pc > usableSize ){
45736          return SQLITE_CORRUPT_BKPT;
45737        }else{
45738          /* The slot remains on the free-list. Reduce its size to account
45739          ** for the portion used by the new allocation. */
45740          put2byte(&data[pc+2], x);
45741        }
45742        *pIdx = pc + x;
45743        return SQLITE_OK;
45744      }
45745    }
45746  }
45747
45748  /* Check to make sure there is enough space in the gap to satisfy
45749  ** the allocation.  If not, defragment.
45750  */
45751  testcase( gap+2+nByte==top );
45752  if( gap+2+nByte>top ){
45753    rc = defragmentPage(pPage);
45754    if( rc ) return rc;
45755    top = get2byteNotZero(&data[hdr+5]);
45756    assert( gap+nByte<=top );
45757  }
45758
45759
45760  /* Allocate memory from the gap in between the cell pointer array
45761  ** and the cell content area.  The btreeInitPage() call has already
45762  ** validated the freelist.  Given that the freelist is valid, there
45763  ** is no way that the allocation can extend off the end of the page.
45764  ** The assert() below verifies the previous sentence.
45765  */
45766  top -= nByte;
45767  put2byte(&data[hdr+5], top);
45768  assert( top+nByte <= pPage->pBt->usableSize );
45769  *pIdx = top;
45770  return SQLITE_OK;
45771}
45772
45773/*
45774** Return a section of the pPage->aData to the freelist.
45775** The first byte of the new free block is pPage->aDisk[start]
45776** and the size of the block is "size" bytes.
45777**
45778** Most of the effort here is involved in coalesing adjacent
45779** free blocks into a single big free block.
45780*/
45781static int freeSpace(MemPage *pPage, int start, int size){
45782  int addr, pbegin, hdr;
45783  int iLast;                        /* Largest possible freeblock offset */
45784  unsigned char *data = pPage->aData;
45785
45786  assert( pPage->pBt!=0 );
45787  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45788  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
45789  assert( (start + size)<=pPage->pBt->usableSize );
45790  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45791  assert( size>=0 );   /* Minimum cell size is 4 */
45792
45793  if( pPage->pBt->secureDelete ){
45794    /* Overwrite deleted information with zeros when the secure_delete
45795    ** option is enabled */
45796    memset(&data[start], 0, size);
45797  }
45798
45799  /* Add the space back into the linked list of freeblocks.  Note that
45800  ** even though the freeblock list was checked by btreeInitPage(),
45801  ** btreeInitPage() did not detect overlapping cells or
45802  ** freeblocks that overlapped cells.   Nor does it detect when the
45803  ** cell content area exceeds the value in the page header.  If these
45804  ** situations arise, then subsequent insert operations might corrupt
45805  ** the freelist.  So we do need to check for corruption while scanning
45806  ** the freelist.
45807  */
45808  hdr = pPage->hdrOffset;
45809  addr = hdr + 1;
45810  iLast = pPage->pBt->usableSize - 4;
45811  assert( start<=iLast );
45812  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
45813    if( pbegin<addr+4 ){
45814      return SQLITE_CORRUPT_BKPT;
45815    }
45816    addr = pbegin;
45817  }
45818  if( pbegin>iLast ){
45819    return SQLITE_CORRUPT_BKPT;
45820  }
45821  assert( pbegin>addr || pbegin==0 );
45822  put2byte(&data[addr], start);
45823  put2byte(&data[start], pbegin);
45824  put2byte(&data[start+2], size);
45825  pPage->nFree = pPage->nFree + (u16)size;
45826
45827  /* Coalesce adjacent free blocks */
45828  addr = hdr + 1;
45829  while( (pbegin = get2byte(&data[addr]))>0 ){
45830    int pnext, psize, x;
45831    assert( pbegin>addr );
45832    assert( pbegin<=pPage->pBt->usableSize-4 );
45833    pnext = get2byte(&data[pbegin]);
45834    psize = get2byte(&data[pbegin+2]);
45835    if( pbegin + psize + 3 >= pnext && pnext>0 ){
45836      int frag = pnext - (pbegin+psize);
45837      if( (frag<0) || (frag>(int)data[hdr+7]) ){
45838        return SQLITE_CORRUPT_BKPT;
45839      }
45840      data[hdr+7] -= (u8)frag;
45841      x = get2byte(&data[pnext]);
45842      put2byte(&data[pbegin], x);
45843      x = pnext + get2byte(&data[pnext+2]) - pbegin;
45844      put2byte(&data[pbegin+2], x);
45845    }else{
45846      addr = pbegin;
45847    }
45848  }
45849
45850  /* If the cell content area begins with a freeblock, remove it. */
45851  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
45852    int top;
45853    pbegin = get2byte(&data[hdr+1]);
45854    memcpy(&data[hdr+1], &data[pbegin], 2);
45855    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
45856    put2byte(&data[hdr+5], top);
45857  }
45858  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
45859  return SQLITE_OK;
45860}
45861
45862/*
45863** Decode the flags byte (the first byte of the header) for a page
45864** and initialize fields of the MemPage structure accordingly.
45865**
45866** Only the following combinations are supported.  Anything different
45867** indicates a corrupt database files:
45868**
45869**         PTF_ZERODATA
45870**         PTF_ZERODATA | PTF_LEAF
45871**         PTF_LEAFDATA | PTF_INTKEY
45872**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
45873*/
45874static int decodeFlags(MemPage *pPage, int flagByte){
45875  BtShared *pBt;     /* A copy of pPage->pBt */
45876
45877  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
45878  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45879  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
45880  flagByte &= ~PTF_LEAF;
45881  pPage->childPtrSize = 4-4*pPage->leaf;
45882  pBt = pPage->pBt;
45883  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
45884    pPage->intKey = 1;
45885    pPage->hasData = pPage->leaf;
45886    pPage->maxLocal = pBt->maxLeaf;
45887    pPage->minLocal = pBt->minLeaf;
45888  }else if( flagByte==PTF_ZERODATA ){
45889    pPage->intKey = 0;
45890    pPage->hasData = 0;
45891    pPage->maxLocal = pBt->maxLocal;
45892    pPage->minLocal = pBt->minLocal;
45893  }else{
45894    return SQLITE_CORRUPT_BKPT;
45895  }
45896  return SQLITE_OK;
45897}
45898
45899/*
45900** Initialize the auxiliary information for a disk block.
45901**
45902** Return SQLITE_OK on success.  If we see that the page does
45903** not contain a well-formed database page, then return
45904** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
45905** guarantee that the page is well-formed.  It only shows that
45906** we failed to detect any corruption.
45907*/
45908static int btreeInitPage(MemPage *pPage){
45909
45910  assert( pPage->pBt!=0 );
45911  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
45912  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
45913  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
45914  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
45915
45916  if( !pPage->isInit ){
45917    u16 pc;            /* Address of a freeblock within pPage->aData[] */
45918    u8 hdr;            /* Offset to beginning of page header */
45919    u8 *data;          /* Equal to pPage->aData */
45920    BtShared *pBt;        /* The main btree structure */
45921    int usableSize;    /* Amount of usable space on each page */
45922    u16 cellOffset;    /* Offset from start of page to first cell pointer */
45923    int nFree;         /* Number of unused bytes on the page */
45924    int top;           /* First byte of the cell content area */
45925    int iCellFirst;    /* First allowable cell or freeblock offset */
45926    int iCellLast;     /* Last possible cell or freeblock offset */
45927
45928    pBt = pPage->pBt;
45929
45930    hdr = pPage->hdrOffset;
45931    data = pPage->aData;
45932    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
45933    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
45934    pPage->maskPage = (u16)(pBt->pageSize - 1);
45935    pPage->nOverflow = 0;
45936    usableSize = pBt->usableSize;
45937    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
45938    top = get2byteNotZero(&data[hdr+5]);
45939    pPage->nCell = get2byte(&data[hdr+3]);
45940    if( pPage->nCell>MX_CELL(pBt) ){
45941      /* To many cells for a single page.  The page must be corrupt */
45942      return SQLITE_CORRUPT_BKPT;
45943    }
45944    testcase( pPage->nCell==MX_CELL(pBt) );
45945
45946    /* A malformed database page might cause us to read past the end
45947    ** of page when parsing a cell.
45948    **
45949    ** The following block of code checks early to see if a cell extends
45950    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
45951    ** returned if it does.
45952    */
45953    iCellFirst = cellOffset + 2*pPage->nCell;
45954    iCellLast = usableSize - 4;
45955#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
45956    {
45957      int i;            /* Index into the cell pointer array */
45958      int sz;           /* Size of a cell */
45959
45960      if( !pPage->leaf ) iCellLast--;
45961      for(i=0; i<pPage->nCell; i++){
45962        pc = get2byte(&data[cellOffset+i*2]);
45963        testcase( pc==iCellFirst );
45964        testcase( pc==iCellLast );
45965        if( pc<iCellFirst || pc>iCellLast ){
45966          return SQLITE_CORRUPT_BKPT;
45967        }
45968        sz = cellSizePtr(pPage, &data[pc]);
45969        testcase( pc+sz==usableSize );
45970        if( pc+sz>usableSize ){
45971          return SQLITE_CORRUPT_BKPT;
45972        }
45973      }
45974      if( !pPage->leaf ) iCellLast++;
45975    }
45976#endif
45977
45978    /* Compute the total free space on the page */
45979    pc = get2byte(&data[hdr+1]);
45980    nFree = data[hdr+7] + top;
45981    while( pc>0 ){
45982      u16 next, size;
45983      if( pc<iCellFirst || pc>iCellLast ){
45984        /* Start of free block is off the page */
45985        return SQLITE_CORRUPT_BKPT;
45986      }
45987      next = get2byte(&data[pc]);
45988      size = get2byte(&data[pc+2]);
45989      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
45990        /* Free blocks must be in ascending order. And the last byte of
45991	** the free-block must lie on the database page.  */
45992        return SQLITE_CORRUPT_BKPT;
45993      }
45994      nFree = nFree + size;
45995      pc = next;
45996    }
45997
45998    /* At this point, nFree contains the sum of the offset to the start
45999    ** of the cell-content area plus the number of free bytes within
46000    ** the cell-content area. If this is greater than the usable-size
46001    ** of the page, then the page must be corrupted. This check also
46002    ** serves to verify that the offset to the start of the cell-content
46003    ** area, according to the page header, lies within the page.
46004    */
46005    if( nFree>usableSize ){
46006      return SQLITE_CORRUPT_BKPT;
46007    }
46008    pPage->nFree = (u16)(nFree - iCellFirst);
46009    pPage->isInit = 1;
46010  }
46011  return SQLITE_OK;
46012}
46013
46014/*
46015** Set up a raw page so that it looks like a database page holding
46016** no entries.
46017*/
46018static void zeroPage(MemPage *pPage, int flags){
46019  unsigned char *data = pPage->aData;
46020  BtShared *pBt = pPage->pBt;
46021  u8 hdr = pPage->hdrOffset;
46022  u16 first;
46023
46024  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
46025  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46026  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
46027  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46028  assert( sqlite3_mutex_held(pBt->mutex) );
46029  if( pBt->secureDelete ){
46030    memset(&data[hdr], 0, pBt->usableSize - hdr);
46031  }
46032  data[hdr] = (char)flags;
46033  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
46034  memset(&data[hdr+1], 0, 4);
46035  data[hdr+7] = 0;
46036  put2byte(&data[hdr+5], pBt->usableSize);
46037  pPage->nFree = (u16)(pBt->usableSize - first);
46038  decodeFlags(pPage, flags);
46039  pPage->hdrOffset = hdr;
46040  pPage->cellOffset = first;
46041  pPage->nOverflow = 0;
46042  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46043  pPage->maskPage = (u16)(pBt->pageSize - 1);
46044  pPage->nCell = 0;
46045  pPage->isInit = 1;
46046}
46047
46048
46049/*
46050** Convert a DbPage obtained from the pager into a MemPage used by
46051** the btree layer.
46052*/
46053static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
46054  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
46055  pPage->aData = sqlite3PagerGetData(pDbPage);
46056  pPage->pDbPage = pDbPage;
46057  pPage->pBt = pBt;
46058  pPage->pgno = pgno;
46059  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
46060  return pPage;
46061}
46062
46063/*
46064** Get a page from the pager.  Initialize the MemPage.pBt and
46065** MemPage.aData elements if needed.
46066**
46067** If the noContent flag is set, it means that we do not care about
46068** the content of the page at this time.  So do not go to the disk
46069** to fetch the content.  Just fill in the content with zeros for now.
46070** If in the future we call sqlite3PagerWrite() on this page, that
46071** means we have started to be concerned about content and the disk
46072** read should occur at that point.
46073*/
46074static int btreeGetPage(
46075  BtShared *pBt,       /* The btree */
46076  Pgno pgno,           /* Number of the page to fetch */
46077  MemPage **ppPage,    /* Return the page in this parameter */
46078  int noContent        /* Do not load page content if true */
46079){
46080  int rc;
46081  DbPage *pDbPage;
46082
46083  assert( sqlite3_mutex_held(pBt->mutex) );
46084  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
46085  if( rc ) return rc;
46086  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
46087  return SQLITE_OK;
46088}
46089
46090/*
46091** Retrieve a page from the pager cache. If the requested page is not
46092** already in the pager cache return NULL. Initialize the MemPage.pBt and
46093** MemPage.aData elements if needed.
46094*/
46095static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
46096  DbPage *pDbPage;
46097  assert( sqlite3_mutex_held(pBt->mutex) );
46098  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
46099  if( pDbPage ){
46100    return btreePageFromDbPage(pDbPage, pgno, pBt);
46101  }
46102  return 0;
46103}
46104
46105/*
46106** Return the size of the database file in pages. If there is any kind of
46107** error, return ((unsigned int)-1).
46108*/
46109static Pgno btreePagecount(BtShared *pBt){
46110  return pBt->nPage;
46111}
46112SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
46113  assert( sqlite3BtreeHoldsMutex(p) );
46114  assert( ((p->pBt->nPage)&0x8000000)==0 );
46115  return (int)btreePagecount(p->pBt);
46116}
46117
46118/*
46119** Get a page from the pager and initialize it.  This routine is just a
46120** convenience wrapper around separate calls to btreeGetPage() and
46121** btreeInitPage().
46122**
46123** If an error occurs, then the value *ppPage is set to is undefined. It
46124** may remain unchanged, or it may be set to an invalid value.
46125*/
46126static int getAndInitPage(
46127  BtShared *pBt,          /* The database file */
46128  Pgno pgno,           /* Number of the page to get */
46129  MemPage **ppPage     /* Write the page pointer here */
46130){
46131  int rc;
46132  assert( sqlite3_mutex_held(pBt->mutex) );
46133
46134  if( pgno>btreePagecount(pBt) ){
46135    rc = SQLITE_CORRUPT_BKPT;
46136  }else{
46137    rc = btreeGetPage(pBt, pgno, ppPage, 0);
46138    if( rc==SQLITE_OK ){
46139      rc = btreeInitPage(*ppPage);
46140      if( rc!=SQLITE_OK ){
46141        releasePage(*ppPage);
46142      }
46143    }
46144  }
46145
46146  testcase( pgno==0 );
46147  assert( pgno!=0 || rc==SQLITE_CORRUPT );
46148  return rc;
46149}
46150
46151/*
46152** Release a MemPage.  This should be called once for each prior
46153** call to btreeGetPage.
46154*/
46155static void releasePage(MemPage *pPage){
46156  if( pPage ){
46157    assert( pPage->aData );
46158    assert( pPage->pBt );
46159    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46160    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
46161    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46162    sqlite3PagerUnref(pPage->pDbPage);
46163  }
46164}
46165
46166/*
46167** During a rollback, when the pager reloads information into the cache
46168** so that the cache is restored to its original state at the start of
46169** the transaction, for each page restored this routine is called.
46170**
46171** This routine needs to reset the extra data section at the end of the
46172** page to agree with the restored data.
46173*/
46174static void pageReinit(DbPage *pData){
46175  MemPage *pPage;
46176  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
46177  assert( sqlite3PagerPageRefcount(pData)>0 );
46178  if( pPage->isInit ){
46179    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46180    pPage->isInit = 0;
46181    if( sqlite3PagerPageRefcount(pData)>1 ){
46182      /* pPage might not be a btree page;  it might be an overflow page
46183      ** or ptrmap page or a free page.  In those cases, the following
46184      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
46185      ** But no harm is done by this.  And it is very important that
46186      ** btreeInitPage() be called on every btree page so we make
46187      ** the call for every page that comes in for re-initing. */
46188      btreeInitPage(pPage);
46189    }
46190  }
46191}
46192
46193/*
46194** Invoke the busy handler for a btree.
46195*/
46196static int btreeInvokeBusyHandler(void *pArg){
46197  BtShared *pBt = (BtShared*)pArg;
46198  assert( pBt->db );
46199  assert( sqlite3_mutex_held(pBt->db->mutex) );
46200  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
46201}
46202
46203/*
46204** Open a database file.
46205**
46206** zFilename is the name of the database file.  If zFilename is NULL
46207** a new database with a random name is created.  This randomly named
46208** database file will be deleted when sqlite3BtreeClose() is called.
46209** If zFilename is ":memory:" then an in-memory database is created
46210** that is automatically destroyed when it is closed.
46211**
46212** If the database is already opened in the same database connection
46213** and we are in shared cache mode, then the open will fail with an
46214** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
46215** objects in the same database connection since doing so will lead
46216** to problems with locking.
46217*/
46218SQLITE_PRIVATE int sqlite3BtreeOpen(
46219  const char *zFilename,  /* Name of the file containing the BTree database */
46220  sqlite3 *db,            /* Associated database handle */
46221  Btree **ppBtree,        /* Pointer to new Btree object written here */
46222  int flags,              /* Options */
46223  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
46224){
46225  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
46226  BtShared *pBt = 0;             /* Shared part of btree structure */
46227  Btree *p;                      /* Handle to return */
46228  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
46229  int rc = SQLITE_OK;            /* Result code from this function */
46230  u8 nReserve;                   /* Byte of unused space on each page */
46231  unsigned char zDbHeader[100];  /* Database header content */
46232
46233  /* Set the variable isMemdb to true for an in-memory database, or
46234  ** false for a file-based database. This symbol is only required if
46235  ** either of the shared-data or autovacuum features are compiled
46236  ** into the library.
46237  */
46238#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
46239  #ifdef SQLITE_OMIT_MEMORYDB
46240    const int isMemdb = 0;
46241  #else
46242    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
46243  #endif
46244#endif
46245
46246  assert( db!=0 );
46247  assert( sqlite3_mutex_held(db->mutex) );
46248
46249  pVfs = db->pVfs;
46250  p = sqlite3MallocZero(sizeof(Btree));
46251  if( !p ){
46252    return SQLITE_NOMEM;
46253  }
46254  p->inTrans = TRANS_NONE;
46255  p->db = db;
46256#ifndef SQLITE_OMIT_SHARED_CACHE
46257  p->lock.pBtree = p;
46258  p->lock.iTable = 1;
46259#endif
46260
46261#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46262  /*
46263  ** If this Btree is a candidate for shared cache, try to find an
46264  ** existing BtShared object that we can share with
46265  */
46266  if( isMemdb==0 && zFilename && zFilename[0] ){
46267    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
46268      int nFullPathname = pVfs->mxPathname+1;
46269      char *zFullPathname = sqlite3Malloc(nFullPathname);
46270      sqlite3_mutex *mutexShared;
46271      p->sharable = 1;
46272      if( !zFullPathname ){
46273        sqlite3_free(p);
46274        return SQLITE_NOMEM;
46275      }
46276      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
46277      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
46278      sqlite3_mutex_enter(mutexOpen);
46279      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46280      sqlite3_mutex_enter(mutexShared);
46281      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
46282        assert( pBt->nRef>0 );
46283        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
46284                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
46285          int iDb;
46286          for(iDb=db->nDb-1; iDb>=0; iDb--){
46287            Btree *pExisting = db->aDb[iDb].pBt;
46288            if( pExisting && pExisting->pBt==pBt ){
46289              sqlite3_mutex_leave(mutexShared);
46290              sqlite3_mutex_leave(mutexOpen);
46291              sqlite3_free(zFullPathname);
46292              sqlite3_free(p);
46293              return SQLITE_CONSTRAINT;
46294            }
46295          }
46296          p->pBt = pBt;
46297          pBt->nRef++;
46298          break;
46299        }
46300      }
46301      sqlite3_mutex_leave(mutexShared);
46302      sqlite3_free(zFullPathname);
46303    }
46304#ifdef SQLITE_DEBUG
46305    else{
46306      /* In debug mode, we mark all persistent databases as sharable
46307      ** even when they are not.  This exercises the locking code and
46308      ** gives more opportunity for asserts(sqlite3_mutex_held())
46309      ** statements to find locking problems.
46310      */
46311      p->sharable = 1;
46312    }
46313#endif
46314  }
46315#endif
46316  if( pBt==0 ){
46317    /*
46318    ** The following asserts make sure that structures used by the btree are
46319    ** the right size.  This is to guard against size changes that result
46320    ** when compiling on a different architecture.
46321    */
46322    assert( sizeof(i64)==8 || sizeof(i64)==4 );
46323    assert( sizeof(u64)==8 || sizeof(u64)==4 );
46324    assert( sizeof(u32)==4 );
46325    assert( sizeof(u16)==2 );
46326    assert( sizeof(Pgno)==4 );
46327
46328    pBt = sqlite3MallocZero( sizeof(*pBt) );
46329    if( pBt==0 ){
46330      rc = SQLITE_NOMEM;
46331      goto btree_open_out;
46332    }
46333    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
46334                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
46335    if( rc==SQLITE_OK ){
46336      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
46337    }
46338    if( rc!=SQLITE_OK ){
46339      goto btree_open_out;
46340    }
46341    pBt->db = db;
46342    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
46343    p->pBt = pBt;
46344
46345    pBt->pCursor = 0;
46346    pBt->pPage1 = 0;
46347    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
46348#ifdef SQLITE_SECURE_DELETE
46349    pBt->secureDelete = 1;
46350#endif
46351    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
46352    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
46353         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
46354      pBt->pageSize = 0;
46355#ifndef SQLITE_OMIT_AUTOVACUUM
46356      /* If the magic name ":memory:" will create an in-memory database, then
46357      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
46358      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
46359      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
46360      ** regular file-name. In this case the auto-vacuum applies as per normal.
46361      */
46362      if( zFilename && !isMemdb ){
46363        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
46364        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
46365      }
46366#endif
46367      nReserve = 0;
46368    }else{
46369      nReserve = zDbHeader[20];
46370      pBt->pageSizeFixed = 1;
46371#ifndef SQLITE_OMIT_AUTOVACUUM
46372      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
46373      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
46374#endif
46375    }
46376    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
46377    if( rc ) goto btree_open_out;
46378    pBt->usableSize = pBt->pageSize - nReserve;
46379    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
46380
46381#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46382    /* Add the new BtShared object to the linked list sharable BtShareds.
46383    */
46384    if( p->sharable ){
46385      sqlite3_mutex *mutexShared;
46386      pBt->nRef = 1;
46387      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46388      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
46389        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
46390        if( pBt->mutex==0 ){
46391          rc = SQLITE_NOMEM;
46392          db->mallocFailed = 0;
46393          goto btree_open_out;
46394        }
46395      }
46396      sqlite3_mutex_enter(mutexShared);
46397      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
46398      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
46399      sqlite3_mutex_leave(mutexShared);
46400    }
46401#endif
46402  }
46403
46404#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46405  /* If the new Btree uses a sharable pBtShared, then link the new
46406  ** Btree into the list of all sharable Btrees for the same connection.
46407  ** The list is kept in ascending order by pBt address.
46408  */
46409  if( p->sharable ){
46410    int i;
46411    Btree *pSib;
46412    for(i=0; i<db->nDb; i++){
46413      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
46414        while( pSib->pPrev ){ pSib = pSib->pPrev; }
46415        if( p->pBt<pSib->pBt ){
46416          p->pNext = pSib;
46417          p->pPrev = 0;
46418          pSib->pPrev = p;
46419        }else{
46420          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
46421            pSib = pSib->pNext;
46422          }
46423          p->pNext = pSib->pNext;
46424          p->pPrev = pSib;
46425          if( p->pNext ){
46426            p->pNext->pPrev = p;
46427          }
46428          pSib->pNext = p;
46429        }
46430        break;
46431      }
46432    }
46433  }
46434#endif
46435  *ppBtree = p;
46436
46437btree_open_out:
46438  if( rc!=SQLITE_OK ){
46439    if( pBt && pBt->pPager ){
46440      sqlite3PagerClose(pBt->pPager);
46441    }
46442    sqlite3_free(pBt);
46443    sqlite3_free(p);
46444    *ppBtree = 0;
46445  }
46446  if( mutexOpen ){
46447    assert( sqlite3_mutex_held(mutexOpen) );
46448    sqlite3_mutex_leave(mutexOpen);
46449  }
46450  return rc;
46451}
46452
46453/*
46454** Decrement the BtShared.nRef counter.  When it reaches zero,
46455** remove the BtShared structure from the sharing list.  Return
46456** true if the BtShared.nRef counter reaches zero and return
46457** false if it is still positive.
46458*/
46459static int removeFromSharingList(BtShared *pBt){
46460#ifndef SQLITE_OMIT_SHARED_CACHE
46461  sqlite3_mutex *pMaster;
46462  BtShared *pList;
46463  int removed = 0;
46464
46465  assert( sqlite3_mutex_notheld(pBt->mutex) );
46466  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46467  sqlite3_mutex_enter(pMaster);
46468  pBt->nRef--;
46469  if( pBt->nRef<=0 ){
46470    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
46471      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
46472    }else{
46473      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
46474      while( ALWAYS(pList) && pList->pNext!=pBt ){
46475        pList=pList->pNext;
46476      }
46477      if( ALWAYS(pList) ){
46478        pList->pNext = pBt->pNext;
46479      }
46480    }
46481    if( SQLITE_THREADSAFE ){
46482      sqlite3_mutex_free(pBt->mutex);
46483    }
46484    removed = 1;
46485  }
46486  sqlite3_mutex_leave(pMaster);
46487  return removed;
46488#else
46489  return 1;
46490#endif
46491}
46492
46493/*
46494** Make sure pBt->pTmpSpace points to an allocation of
46495** MX_CELL_SIZE(pBt) bytes.
46496*/
46497static void allocateTempSpace(BtShared *pBt){
46498  if( !pBt->pTmpSpace ){
46499    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
46500  }
46501}
46502
46503/*
46504** Free the pBt->pTmpSpace allocation
46505*/
46506static void freeTempSpace(BtShared *pBt){
46507  sqlite3PageFree( pBt->pTmpSpace);
46508  pBt->pTmpSpace = 0;
46509}
46510
46511/*
46512** Close an open database and invalidate all cursors.
46513*/
46514SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
46515  BtShared *pBt = p->pBt;
46516  BtCursor *pCur;
46517
46518  /* Close all cursors opened via this handle.  */
46519  assert( sqlite3_mutex_held(p->db->mutex) );
46520  sqlite3BtreeEnter(p);
46521  pCur = pBt->pCursor;
46522  while( pCur ){
46523    BtCursor *pTmp = pCur;
46524    pCur = pCur->pNext;
46525    if( pTmp->pBtree==p ){
46526      sqlite3BtreeCloseCursor(pTmp);
46527    }
46528  }
46529
46530  /* Rollback any active transaction and free the handle structure.
46531  ** The call to sqlite3BtreeRollback() drops any table-locks held by
46532  ** this handle.
46533  */
46534  sqlite3BtreeRollback(p);
46535  sqlite3BtreeLeave(p);
46536
46537  /* If there are still other outstanding references to the shared-btree
46538  ** structure, return now. The remainder of this procedure cleans
46539  ** up the shared-btree.
46540  */
46541  assert( p->wantToLock==0 && p->locked==0 );
46542  if( !p->sharable || removeFromSharingList(pBt) ){
46543    /* The pBt is no longer on the sharing list, so we can access
46544    ** it without having to hold the mutex.
46545    **
46546    ** Clean out and delete the BtShared object.
46547    */
46548    assert( !pBt->pCursor );
46549    sqlite3PagerClose(pBt->pPager);
46550    if( pBt->xFreeSchema && pBt->pSchema ){
46551      pBt->xFreeSchema(pBt->pSchema);
46552    }
46553    sqlite3DbFree(0, pBt->pSchema);
46554    freeTempSpace(pBt);
46555    sqlite3_free(pBt);
46556  }
46557
46558#ifndef SQLITE_OMIT_SHARED_CACHE
46559  assert( p->wantToLock==0 );
46560  assert( p->locked==0 );
46561  if( p->pPrev ) p->pPrev->pNext = p->pNext;
46562  if( p->pNext ) p->pNext->pPrev = p->pPrev;
46563#endif
46564
46565  sqlite3_free(p);
46566  return SQLITE_OK;
46567}
46568
46569/*
46570** Change the limit on the number of pages allowed in the cache.
46571**
46572** The maximum number of cache pages is set to the absolute
46573** value of mxPage.  If mxPage is negative, the pager will
46574** operate asynchronously - it will not stop to do fsync()s
46575** to insure data is written to the disk surface before
46576** continuing.  Transactions still work if synchronous is off,
46577** and the database cannot be corrupted if this program
46578** crashes.  But if the operating system crashes or there is
46579** an abrupt power failure when synchronous is off, the database
46580** could be left in an inconsistent and unrecoverable state.
46581** Synchronous is on by default so database corruption is not
46582** normally a worry.
46583*/
46584SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
46585  BtShared *pBt = p->pBt;
46586  assert( sqlite3_mutex_held(p->db->mutex) );
46587  sqlite3BtreeEnter(p);
46588  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
46589  sqlite3BtreeLeave(p);
46590  return SQLITE_OK;
46591}
46592
46593/*
46594** Change the way data is synced to disk in order to increase or decrease
46595** how well the database resists damage due to OS crashes and power
46596** failures.  Level 1 is the same as asynchronous (no syncs() occur and
46597** there is a high probability of damage)  Level 2 is the default.  There
46598** is a very low but non-zero probability of damage.  Level 3 reduces the
46599** probability of damage to near zero but with a write performance reduction.
46600*/
46601#ifndef SQLITE_OMIT_PAGER_PRAGMAS
46602SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
46603  BtShared *pBt = p->pBt;
46604  assert( sqlite3_mutex_held(p->db->mutex) );
46605  sqlite3BtreeEnter(p);
46606  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
46607  sqlite3BtreeLeave(p);
46608  return SQLITE_OK;
46609}
46610#endif
46611
46612/*
46613** Return TRUE if the given btree is set to safety level 1.  In other
46614** words, return TRUE if no sync() occurs on the disk files.
46615*/
46616SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
46617  BtShared *pBt = p->pBt;
46618  int rc;
46619  assert( sqlite3_mutex_held(p->db->mutex) );
46620  sqlite3BtreeEnter(p);
46621  assert( pBt && pBt->pPager );
46622  rc = sqlite3PagerNosync(pBt->pPager);
46623  sqlite3BtreeLeave(p);
46624  return rc;
46625}
46626
46627#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
46628/*
46629** Change the default pages size and the number of reserved bytes per page.
46630** Or, if the page size has already been fixed, return SQLITE_READONLY
46631** without changing anything.
46632**
46633** The page size must be a power of 2 between 512 and 65536.  If the page
46634** size supplied does not meet this constraint then the page size is not
46635** changed.
46636**
46637** Page sizes are constrained to be a power of two so that the region
46638** of the database file used for locking (beginning at PENDING_BYTE,
46639** the first byte past the 1GB boundary, 0x40000000) needs to occur
46640** at the beginning of a page.
46641**
46642** If parameter nReserve is less than zero, then the number of reserved
46643** bytes per page is left unchanged.
46644**
46645** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
46646** and autovacuum mode can no longer be changed.
46647*/
46648SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
46649  int rc = SQLITE_OK;
46650  BtShared *pBt = p->pBt;
46651  assert( nReserve>=-1 && nReserve<=255 );
46652  sqlite3BtreeEnter(p);
46653  if( pBt->pageSizeFixed ){
46654    sqlite3BtreeLeave(p);
46655    return SQLITE_READONLY;
46656  }
46657  if( nReserve<0 ){
46658    nReserve = pBt->pageSize - pBt->usableSize;
46659  }
46660  assert( nReserve>=0 && nReserve<=255 );
46661  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
46662        ((pageSize-1)&pageSize)==0 ){
46663    assert( (pageSize & 7)==0 );
46664    assert( !pBt->pPage1 && !pBt->pCursor );
46665    pBt->pageSize = (u32)pageSize;
46666    freeTempSpace(pBt);
46667  }
46668  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
46669  pBt->usableSize = pBt->pageSize - (u16)nReserve;
46670  if( iFix ) pBt->pageSizeFixed = 1;
46671  sqlite3BtreeLeave(p);
46672  return rc;
46673}
46674
46675/*
46676** Return the currently defined page size
46677*/
46678SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
46679  return p->pBt->pageSize;
46680}
46681
46682/*
46683** Return the number of bytes of space at the end of every page that
46684** are intentually left unused.  This is the "reserved" space that is
46685** sometimes used by extensions.
46686*/
46687SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
46688  int n;
46689  sqlite3BtreeEnter(p);
46690  n = p->pBt->pageSize - p->pBt->usableSize;
46691  sqlite3BtreeLeave(p);
46692  return n;
46693}
46694
46695/*
46696** Set the maximum page count for a database if mxPage is positive.
46697** No changes are made if mxPage is 0 or negative.
46698** Regardless of the value of mxPage, return the maximum page count.
46699*/
46700SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
46701  int n;
46702  sqlite3BtreeEnter(p);
46703  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
46704  sqlite3BtreeLeave(p);
46705  return n;
46706}
46707
46708/*
46709** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
46710** then make no changes.  Always return the value of the secureDelete
46711** setting after the change.
46712*/
46713SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
46714  int b;
46715  if( p==0 ) return 0;
46716  sqlite3BtreeEnter(p);
46717  if( newFlag>=0 ){
46718    p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
46719  }
46720  b = p->pBt->secureDelete;
46721  sqlite3BtreeLeave(p);
46722  return b;
46723}
46724#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
46725
46726/*
46727** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
46728** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
46729** is disabled. The default value for the auto-vacuum property is
46730** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
46731*/
46732SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
46733#ifdef SQLITE_OMIT_AUTOVACUUM
46734  return SQLITE_READONLY;
46735#else
46736  BtShared *pBt = p->pBt;
46737  int rc = SQLITE_OK;
46738  u8 av = (u8)autoVacuum;
46739
46740  sqlite3BtreeEnter(p);
46741  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
46742    rc = SQLITE_READONLY;
46743  }else{
46744    pBt->autoVacuum = av ?1:0;
46745    pBt->incrVacuum = av==2 ?1:0;
46746  }
46747  sqlite3BtreeLeave(p);
46748  return rc;
46749#endif
46750}
46751
46752/*
46753** Return the value of the 'auto-vacuum' property. If auto-vacuum is
46754** enabled 1 is returned. Otherwise 0.
46755*/
46756SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
46757#ifdef SQLITE_OMIT_AUTOVACUUM
46758  return BTREE_AUTOVACUUM_NONE;
46759#else
46760  int rc;
46761  sqlite3BtreeEnter(p);
46762  rc = (
46763    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
46764    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
46765    BTREE_AUTOVACUUM_INCR
46766  );
46767  sqlite3BtreeLeave(p);
46768  return rc;
46769#endif
46770}
46771
46772
46773/*
46774** Get a reference to pPage1 of the database file.  This will
46775** also acquire a readlock on that file.
46776**
46777** SQLITE_OK is returned on success.  If the file is not a
46778** well-formed database file, then SQLITE_CORRUPT is returned.
46779** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
46780** is returned if we run out of memory.
46781*/
46782static int lockBtree(BtShared *pBt){
46783  int rc;              /* Result code from subfunctions */
46784  MemPage *pPage1;     /* Page 1 of the database file */
46785  int nPage;           /* Number of pages in the database */
46786  int nPageFile = 0;   /* Number of pages in the database file */
46787  int nPageHeader;     /* Number of pages in the database according to hdr */
46788
46789  assert( sqlite3_mutex_held(pBt->mutex) );
46790  assert( pBt->pPage1==0 );
46791  rc = sqlite3PagerSharedLock(pBt->pPager);
46792  if( rc!=SQLITE_OK ) return rc;
46793  rc = btreeGetPage(pBt, 1, &pPage1, 0);
46794  if( rc!=SQLITE_OK ) return rc;
46795
46796  /* Do some checking to help insure the file we opened really is
46797  ** a valid database file.
46798  */
46799  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
46800  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
46801  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
46802    nPage = nPageFile;
46803  }
46804  if( nPage>0 ){
46805    u32 pageSize;
46806    u32 usableSize;
46807    u8 *page1 = pPage1->aData;
46808    rc = SQLITE_NOTADB;
46809    if( memcmp(page1, zMagicHeader, 16)!=0 ){
46810      goto page1_init_failed;
46811    }
46812
46813#ifdef SQLITE_OMIT_WAL
46814    if( page1[18]>1 ){
46815      pBt->readOnly = 1;
46816    }
46817    if( page1[19]>1 ){
46818      goto page1_init_failed;
46819    }
46820#else
46821    if( page1[18]>2 ){
46822      pBt->readOnly = 1;
46823    }
46824    if( page1[19]>2 ){
46825      goto page1_init_failed;
46826    }
46827
46828    /* If the write version is set to 2, this database should be accessed
46829    ** in WAL mode. If the log is not already open, open it now. Then
46830    ** return SQLITE_OK and return without populating BtShared.pPage1.
46831    ** The caller detects this and calls this function again. This is
46832    ** required as the version of page 1 currently in the page1 buffer
46833    ** may not be the latest version - there may be a newer one in the log
46834    ** file.
46835    */
46836    if( page1[19]==2 && pBt->doNotUseWAL==0 ){
46837      int isOpen = 0;
46838      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
46839      if( rc!=SQLITE_OK ){
46840        goto page1_init_failed;
46841      }else if( isOpen==0 ){
46842        releasePage(pPage1);
46843        return SQLITE_OK;
46844      }
46845      rc = SQLITE_NOTADB;
46846    }
46847#endif
46848
46849    /* The maximum embedded fraction must be exactly 25%.  And the minimum
46850    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
46851    ** The original design allowed these amounts to vary, but as of
46852    ** version 3.6.0, we require them to be fixed.
46853    */
46854    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
46855      goto page1_init_failed;
46856    }
46857    pageSize = (page1[16]<<8) | (page1[17]<<16);
46858    if( ((pageSize-1)&pageSize)!=0
46859     || pageSize>SQLITE_MAX_PAGE_SIZE
46860     || pageSize<=256
46861    ){
46862      goto page1_init_failed;
46863    }
46864    assert( (pageSize & 7)==0 );
46865    usableSize = pageSize - page1[20];
46866    if( (u32)pageSize!=pBt->pageSize ){
46867      /* After reading the first page of the database assuming a page size
46868      ** of BtShared.pageSize, we have discovered that the page-size is
46869      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
46870      ** zero and return SQLITE_OK. The caller will call this function
46871      ** again with the correct page-size.
46872      */
46873      releasePage(pPage1);
46874      pBt->usableSize = usableSize;
46875      pBt->pageSize = pageSize;
46876      freeTempSpace(pBt);
46877      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
46878                                   pageSize-usableSize);
46879      return rc;
46880    }
46881    if( nPageHeader>nPageFile ){
46882      rc = SQLITE_CORRUPT_BKPT;
46883      goto page1_init_failed;
46884    }
46885    if( usableSize<480 ){
46886      goto page1_init_failed;
46887    }
46888    pBt->pageSize = pageSize;
46889    pBt->usableSize = usableSize;
46890#ifndef SQLITE_OMIT_AUTOVACUUM
46891    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
46892    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
46893#endif
46894  }
46895
46896  /* maxLocal is the maximum amount of payload to store locally for
46897  ** a cell.  Make sure it is small enough so that at least minFanout
46898  ** cells can will fit on one page.  We assume a 10-byte page header.
46899  ** Besides the payload, the cell must store:
46900  **     2-byte pointer to the cell
46901  **     4-byte child pointer
46902  **     9-byte nKey value
46903  **     4-byte nData value
46904  **     4-byte overflow page pointer
46905  ** So a cell consists of a 2-byte pointer, a header which is as much as
46906  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
46907  ** page pointer.
46908  */
46909  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
46910  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
46911  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
46912  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
46913  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
46914  pBt->pPage1 = pPage1;
46915  pBt->nPage = nPage;
46916  return SQLITE_OK;
46917
46918page1_init_failed:
46919  releasePage(pPage1);
46920  pBt->pPage1 = 0;
46921  return rc;
46922}
46923
46924/*
46925** If there are no outstanding cursors and we are not in the middle
46926** of a transaction but there is a read lock on the database, then
46927** this routine unrefs the first page of the database file which
46928** has the effect of releasing the read lock.
46929**
46930** If there is a transaction in progress, this routine is a no-op.
46931*/
46932static void unlockBtreeIfUnused(BtShared *pBt){
46933  assert( sqlite3_mutex_held(pBt->mutex) );
46934  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
46935  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
46936    assert( pBt->pPage1->aData );
46937    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
46938    assert( pBt->pPage1->aData );
46939    releasePage(pBt->pPage1);
46940    pBt->pPage1 = 0;
46941  }
46942}
46943
46944/*
46945** If pBt points to an empty file then convert that empty file
46946** into a new empty database by initializing the first page of
46947** the database.
46948*/
46949static int newDatabase(BtShared *pBt){
46950  MemPage *pP1;
46951  unsigned char *data;
46952  int rc;
46953
46954  assert( sqlite3_mutex_held(pBt->mutex) );
46955  if( pBt->nPage>0 ){
46956    return SQLITE_OK;
46957  }
46958  pP1 = pBt->pPage1;
46959  assert( pP1!=0 );
46960  data = pP1->aData;
46961  rc = sqlite3PagerWrite(pP1->pDbPage);
46962  if( rc ) return rc;
46963  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
46964  assert( sizeof(zMagicHeader)==16 );
46965  data[16] = (u8)((pBt->pageSize>>8)&0xff);
46966  data[17] = (u8)((pBt->pageSize>>16)&0xff);
46967  data[18] = 1;
46968  data[19] = 1;
46969  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
46970  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
46971  data[21] = 64;
46972  data[22] = 32;
46973  data[23] = 32;
46974  memset(&data[24], 0, 100-24);
46975  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
46976  pBt->pageSizeFixed = 1;
46977#ifndef SQLITE_OMIT_AUTOVACUUM
46978  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
46979  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
46980  put4byte(&data[36 + 4*4], pBt->autoVacuum);
46981  put4byte(&data[36 + 7*4], pBt->incrVacuum);
46982#endif
46983  pBt->nPage = 1;
46984  data[31] = 1;
46985  return SQLITE_OK;
46986}
46987
46988/*
46989** Attempt to start a new transaction. A write-transaction
46990** is started if the second argument is nonzero, otherwise a read-
46991** transaction.  If the second argument is 2 or more and exclusive
46992** transaction is started, meaning that no other process is allowed
46993** to access the database.  A preexisting transaction may not be
46994** upgraded to exclusive by calling this routine a second time - the
46995** exclusivity flag only works for a new transaction.
46996**
46997** A write-transaction must be started before attempting any
46998** changes to the database.  None of the following routines
46999** will work unless a transaction is started first:
47000**
47001**      sqlite3BtreeCreateTable()
47002**      sqlite3BtreeCreateIndex()
47003**      sqlite3BtreeClearTable()
47004**      sqlite3BtreeDropTable()
47005**      sqlite3BtreeInsert()
47006**      sqlite3BtreeDelete()
47007**      sqlite3BtreeUpdateMeta()
47008**
47009** If an initial attempt to acquire the lock fails because of lock contention
47010** and the database was previously unlocked, then invoke the busy handler
47011** if there is one.  But if there was previously a read-lock, do not
47012** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
47013** returned when there is already a read-lock in order to avoid a deadlock.
47014**
47015** Suppose there are two processes A and B.  A has a read lock and B has
47016** a reserved lock.  B tries to promote to exclusive but is blocked because
47017** of A's read lock.  A tries to promote to reserved but is blocked by B.
47018** One or the other of the two processes must give way or there can be
47019** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
47020** when A already has a read lock, we encourage A to give up and let B
47021** proceed.
47022*/
47023SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
47024  sqlite3 *pBlock = 0;
47025  BtShared *pBt = p->pBt;
47026  int rc = SQLITE_OK;
47027
47028  sqlite3BtreeEnter(p);
47029  btreeIntegrity(p);
47030
47031  /* If the btree is already in a write-transaction, or it
47032  ** is already in a read-transaction and a read-transaction
47033  ** is requested, this is a no-op.
47034  */
47035  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
47036    goto trans_begun;
47037  }
47038
47039  /* Write transactions are not possible on a read-only database */
47040  if( pBt->readOnly && wrflag ){
47041    rc = SQLITE_READONLY;
47042    goto trans_begun;
47043  }
47044
47045#ifndef SQLITE_OMIT_SHARED_CACHE
47046  /* If another database handle has already opened a write transaction
47047  ** on this shared-btree structure and a second write transaction is
47048  ** requested, return SQLITE_LOCKED.
47049  */
47050  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
47051    pBlock = pBt->pWriter->db;
47052  }else if( wrflag>1 ){
47053    BtLock *pIter;
47054    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47055      if( pIter->pBtree!=p ){
47056        pBlock = pIter->pBtree->db;
47057        break;
47058      }
47059    }
47060  }
47061  if( pBlock ){
47062    sqlite3ConnectionBlocked(p->db, pBlock);
47063    rc = SQLITE_LOCKED_SHAREDCACHE;
47064    goto trans_begun;
47065  }
47066#endif
47067
47068  /* Any read-only or read-write transaction implies a read-lock on
47069  ** page 1. So if some other shared-cache client already has a write-lock
47070  ** on page 1, the transaction cannot be opened. */
47071  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
47072  if( SQLITE_OK!=rc ) goto trans_begun;
47073
47074  pBt->initiallyEmpty = (u8)(pBt->nPage==0);
47075  do {
47076    /* Call lockBtree() until either pBt->pPage1 is populated or
47077    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
47078    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
47079    ** reading page 1 it discovers that the page-size of the database
47080    ** file is not pBt->pageSize. In this case lockBtree() will update
47081    ** pBt->pageSize to the page-size of the file on disk.
47082    */
47083    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
47084
47085    if( rc==SQLITE_OK && wrflag ){
47086      if( pBt->readOnly ){
47087        rc = SQLITE_READONLY;
47088      }else{
47089        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
47090        if( rc==SQLITE_OK ){
47091          rc = newDatabase(pBt);
47092        }
47093      }
47094    }
47095
47096    if( rc!=SQLITE_OK ){
47097      unlockBtreeIfUnused(pBt);
47098    }
47099  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
47100          btreeInvokeBusyHandler(pBt) );
47101
47102  if( rc==SQLITE_OK ){
47103    if( p->inTrans==TRANS_NONE ){
47104      pBt->nTransaction++;
47105#ifndef SQLITE_OMIT_SHARED_CACHE
47106      if( p->sharable ){
47107	assert( p->lock.pBtree==p && p->lock.iTable==1 );
47108        p->lock.eLock = READ_LOCK;
47109        p->lock.pNext = pBt->pLock;
47110        pBt->pLock = &p->lock;
47111      }
47112#endif
47113    }
47114    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
47115    if( p->inTrans>pBt->inTransaction ){
47116      pBt->inTransaction = p->inTrans;
47117    }
47118    if( wrflag ){
47119      MemPage *pPage1 = pBt->pPage1;
47120#ifndef SQLITE_OMIT_SHARED_CACHE
47121      assert( !pBt->pWriter );
47122      pBt->pWriter = p;
47123      pBt->isExclusive = (u8)(wrflag>1);
47124#endif
47125
47126      /* If the db-size header field is incorrect (as it may be if an old
47127      ** client has been writing the database file), update it now. Doing
47128      ** this sooner rather than later means the database size can safely
47129      ** re-read the database size from page 1 if a savepoint or transaction
47130      ** rollback occurs within the transaction.
47131      */
47132      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
47133        rc = sqlite3PagerWrite(pPage1->pDbPage);
47134        if( rc==SQLITE_OK ){
47135          put4byte(&pPage1->aData[28], pBt->nPage);
47136        }
47137      }
47138    }
47139  }
47140
47141
47142trans_begun:
47143  if( rc==SQLITE_OK && wrflag ){
47144    /* This call makes sure that the pager has the correct number of
47145    ** open savepoints. If the second parameter is greater than 0 and
47146    ** the sub-journal is not already open, then it will be opened here.
47147    */
47148    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
47149  }
47150
47151  btreeIntegrity(p);
47152  sqlite3BtreeLeave(p);
47153  return rc;
47154}
47155
47156#ifndef SQLITE_OMIT_AUTOVACUUM
47157
47158/*
47159** Set the pointer-map entries for all children of page pPage. Also, if
47160** pPage contains cells that point to overflow pages, set the pointer
47161** map entries for the overflow pages as well.
47162*/
47163static int setChildPtrmaps(MemPage *pPage){
47164  int i;                             /* Counter variable */
47165  int nCell;                         /* Number of cells in page pPage */
47166  int rc;                            /* Return code */
47167  BtShared *pBt = pPage->pBt;
47168  u8 isInitOrig = pPage->isInit;
47169  Pgno pgno = pPage->pgno;
47170
47171  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47172  rc = btreeInitPage(pPage);
47173  if( rc!=SQLITE_OK ){
47174    goto set_child_ptrmaps_out;
47175  }
47176  nCell = pPage->nCell;
47177
47178  for(i=0; i<nCell; i++){
47179    u8 *pCell = findCell(pPage, i);
47180
47181    ptrmapPutOvflPtr(pPage, pCell, &rc);
47182
47183    if( !pPage->leaf ){
47184      Pgno childPgno = get4byte(pCell);
47185      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
47186    }
47187  }
47188
47189  if( !pPage->leaf ){
47190    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47191    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
47192  }
47193
47194set_child_ptrmaps_out:
47195  pPage->isInit = isInitOrig;
47196  return rc;
47197}
47198
47199/*
47200** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
47201** that it points to iTo. Parameter eType describes the type of pointer to
47202** be modified, as  follows:
47203**
47204** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
47205**                   page of pPage.
47206**
47207** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
47208**                   page pointed to by one of the cells on pPage.
47209**
47210** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
47211**                   overflow page in the list.
47212*/
47213static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
47214  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47215  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
47216  if( eType==PTRMAP_OVERFLOW2 ){
47217    /* The pointer is always the first 4 bytes of the page in this case.  */
47218    if( get4byte(pPage->aData)!=iFrom ){
47219      return SQLITE_CORRUPT_BKPT;
47220    }
47221    put4byte(pPage->aData, iTo);
47222  }else{
47223    u8 isInitOrig = pPage->isInit;
47224    int i;
47225    int nCell;
47226
47227    btreeInitPage(pPage);
47228    nCell = pPage->nCell;
47229
47230    for(i=0; i<nCell; i++){
47231      u8 *pCell = findCell(pPage, i);
47232      if( eType==PTRMAP_OVERFLOW1 ){
47233        CellInfo info;
47234        btreeParseCellPtr(pPage, pCell, &info);
47235        if( info.iOverflow ){
47236          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
47237            put4byte(&pCell[info.iOverflow], iTo);
47238            break;
47239          }
47240        }
47241      }else{
47242        if( get4byte(pCell)==iFrom ){
47243          put4byte(pCell, iTo);
47244          break;
47245        }
47246      }
47247    }
47248
47249    if( i==nCell ){
47250      if( eType!=PTRMAP_BTREE ||
47251          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
47252        return SQLITE_CORRUPT_BKPT;
47253      }
47254      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
47255    }
47256
47257    pPage->isInit = isInitOrig;
47258  }
47259  return SQLITE_OK;
47260}
47261
47262
47263/*
47264** Move the open database page pDbPage to location iFreePage in the
47265** database. The pDbPage reference remains valid.
47266**
47267** The isCommit flag indicates that there is no need to remember that
47268** the journal needs to be sync()ed before database page pDbPage->pgno
47269** can be written to. The caller has already promised not to write to that
47270** page.
47271*/
47272static int relocatePage(
47273  BtShared *pBt,           /* Btree */
47274  MemPage *pDbPage,        /* Open page to move */
47275  u8 eType,                /* Pointer map 'type' entry for pDbPage */
47276  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
47277  Pgno iFreePage,          /* The location to move pDbPage to */
47278  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
47279){
47280  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
47281  Pgno iDbPage = pDbPage->pgno;
47282  Pager *pPager = pBt->pPager;
47283  int rc;
47284
47285  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
47286      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
47287  assert( sqlite3_mutex_held(pBt->mutex) );
47288  assert( pDbPage->pBt==pBt );
47289
47290  /* Move page iDbPage from its current location to page number iFreePage */
47291  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
47292      iDbPage, iFreePage, iPtrPage, eType));
47293  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
47294  if( rc!=SQLITE_OK ){
47295    return rc;
47296  }
47297  pDbPage->pgno = iFreePage;
47298
47299  /* If pDbPage was a btree-page, then it may have child pages and/or cells
47300  ** that point to overflow pages. The pointer map entries for all these
47301  ** pages need to be changed.
47302  **
47303  ** If pDbPage is an overflow page, then the first 4 bytes may store a
47304  ** pointer to a subsequent overflow page. If this is the case, then
47305  ** the pointer map needs to be updated for the subsequent overflow page.
47306  */
47307  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
47308    rc = setChildPtrmaps(pDbPage);
47309    if( rc!=SQLITE_OK ){
47310      return rc;
47311    }
47312  }else{
47313    Pgno nextOvfl = get4byte(pDbPage->aData);
47314    if( nextOvfl!=0 ){
47315      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
47316      if( rc!=SQLITE_OK ){
47317        return rc;
47318      }
47319    }
47320  }
47321
47322  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
47323  ** that it points at iFreePage. Also fix the pointer map entry for
47324  ** iPtrPage.
47325  */
47326  if( eType!=PTRMAP_ROOTPAGE ){
47327    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
47328    if( rc!=SQLITE_OK ){
47329      return rc;
47330    }
47331    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
47332    if( rc!=SQLITE_OK ){
47333      releasePage(pPtrPage);
47334      return rc;
47335    }
47336    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
47337    releasePage(pPtrPage);
47338    if( rc==SQLITE_OK ){
47339      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
47340    }
47341  }
47342  return rc;
47343}
47344
47345/* Forward declaration required by incrVacuumStep(). */
47346static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
47347
47348/*
47349** Perform a single step of an incremental-vacuum. If successful,
47350** return SQLITE_OK. If there is no work to do (and therefore no
47351** point in calling this function again), return SQLITE_DONE.
47352**
47353** More specificly, this function attempts to re-organize the
47354** database so that the last page of the file currently in use
47355** is no longer in use.
47356**
47357** If the nFin parameter is non-zero, this function assumes
47358** that the caller will keep calling incrVacuumStep() until
47359** it returns SQLITE_DONE or an error, and that nFin is the
47360** number of pages the database file will contain after this
47361** process is complete.  If nFin is zero, it is assumed that
47362** incrVacuumStep() will be called a finite amount of times
47363** which may or may not empty the freelist.  A full autovacuum
47364** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
47365*/
47366static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
47367  Pgno nFreeList;           /* Number of pages still on the free-list */
47368  int rc;
47369
47370  assert( sqlite3_mutex_held(pBt->mutex) );
47371  assert( iLastPg>nFin );
47372
47373  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
47374    u8 eType;
47375    Pgno iPtrPage;
47376
47377    nFreeList = get4byte(&pBt->pPage1->aData[36]);
47378    if( nFreeList==0 ){
47379      return SQLITE_DONE;
47380    }
47381
47382    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
47383    if( rc!=SQLITE_OK ){
47384      return rc;
47385    }
47386    if( eType==PTRMAP_ROOTPAGE ){
47387      return SQLITE_CORRUPT_BKPT;
47388    }
47389
47390    if( eType==PTRMAP_FREEPAGE ){
47391      if( nFin==0 ){
47392        /* Remove the page from the files free-list. This is not required
47393        ** if nFin is non-zero. In that case, the free-list will be
47394        ** truncated to zero after this function returns, so it doesn't
47395        ** matter if it still contains some garbage entries.
47396        */
47397        Pgno iFreePg;
47398        MemPage *pFreePg;
47399        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
47400        if( rc!=SQLITE_OK ){
47401          return rc;
47402        }
47403        assert( iFreePg==iLastPg );
47404        releasePage(pFreePg);
47405      }
47406    } else {
47407      Pgno iFreePg;             /* Index of free page to move pLastPg to */
47408      MemPage *pLastPg;
47409
47410      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
47411      if( rc!=SQLITE_OK ){
47412        return rc;
47413      }
47414
47415      /* If nFin is zero, this loop runs exactly once and page pLastPg
47416      ** is swapped with the first free page pulled off the free list.
47417      **
47418      ** On the other hand, if nFin is greater than zero, then keep
47419      ** looping until a free-page located within the first nFin pages
47420      ** of the file is found.
47421      */
47422      do {
47423        MemPage *pFreePg;
47424        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
47425        if( rc!=SQLITE_OK ){
47426          releasePage(pLastPg);
47427          return rc;
47428        }
47429        releasePage(pFreePg);
47430      }while( nFin!=0 && iFreePg>nFin );
47431      assert( iFreePg<iLastPg );
47432
47433      rc = sqlite3PagerWrite(pLastPg->pDbPage);
47434      if( rc==SQLITE_OK ){
47435        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
47436      }
47437      releasePage(pLastPg);
47438      if( rc!=SQLITE_OK ){
47439        return rc;
47440      }
47441    }
47442  }
47443
47444  if( nFin==0 ){
47445    iLastPg--;
47446    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
47447      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
47448        MemPage *pPg;
47449        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
47450        if( rc!=SQLITE_OK ){
47451          return rc;
47452        }
47453        rc = sqlite3PagerWrite(pPg->pDbPage);
47454        releasePage(pPg);
47455        if( rc!=SQLITE_OK ){
47456          return rc;
47457        }
47458      }
47459      iLastPg--;
47460    }
47461    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
47462    pBt->nPage = iLastPg;
47463  }
47464  return SQLITE_OK;
47465}
47466
47467/*
47468** A write-transaction must be opened before calling this function.
47469** It performs a single unit of work towards an incremental vacuum.
47470**
47471** If the incremental vacuum is finished after this function has run,
47472** SQLITE_DONE is returned. If it is not finished, but no error occurred,
47473** SQLITE_OK is returned. Otherwise an SQLite error code.
47474*/
47475SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
47476  int rc;
47477  BtShared *pBt = p->pBt;
47478
47479  sqlite3BtreeEnter(p);
47480  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
47481  if( !pBt->autoVacuum ){
47482    rc = SQLITE_DONE;
47483  }else{
47484    invalidateAllOverflowCache(pBt);
47485    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
47486    if( rc==SQLITE_OK ){
47487      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
47488      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
47489    }
47490  }
47491  sqlite3BtreeLeave(p);
47492  return rc;
47493}
47494
47495/*
47496** This routine is called prior to sqlite3PagerCommit when a transaction
47497** is commited for an auto-vacuum database.
47498**
47499** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
47500** the database file should be truncated to during the commit process.
47501** i.e. the database has been reorganized so that only the first *pnTrunc
47502** pages are in use.
47503*/
47504static int autoVacuumCommit(BtShared *pBt){
47505  int rc = SQLITE_OK;
47506  Pager *pPager = pBt->pPager;
47507  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
47508
47509  assert( sqlite3_mutex_held(pBt->mutex) );
47510  invalidateAllOverflowCache(pBt);
47511  assert(pBt->autoVacuum);
47512  if( !pBt->incrVacuum ){
47513    Pgno nFin;         /* Number of pages in database after autovacuuming */
47514    Pgno nFree;        /* Number of pages on the freelist initially */
47515    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
47516    Pgno iFree;        /* The next page to be freed */
47517    int nEntry;        /* Number of entries on one ptrmap page */
47518    Pgno nOrig;        /* Database size before freeing */
47519
47520    nOrig = btreePagecount(pBt);
47521    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
47522      /* It is not possible to create a database for which the final page
47523      ** is either a pointer-map page or the pending-byte page. If one
47524      ** is encountered, this indicates corruption.
47525      */
47526      return SQLITE_CORRUPT_BKPT;
47527    }
47528
47529    nFree = get4byte(&pBt->pPage1->aData[36]);
47530    nEntry = pBt->usableSize/5;
47531    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
47532    nFin = nOrig - nFree - nPtrmap;
47533    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
47534      nFin--;
47535    }
47536    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
47537      nFin--;
47538    }
47539    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
47540
47541    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
47542      rc = incrVacuumStep(pBt, nFin, iFree);
47543    }
47544    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
47545      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
47546      put4byte(&pBt->pPage1->aData[32], 0);
47547      put4byte(&pBt->pPage1->aData[36], 0);
47548      put4byte(&pBt->pPage1->aData[28], nFin);
47549      sqlite3PagerTruncateImage(pBt->pPager, nFin);
47550      pBt->nPage = nFin;
47551    }
47552    if( rc!=SQLITE_OK ){
47553      sqlite3PagerRollback(pPager);
47554    }
47555  }
47556
47557  assert( nRef==sqlite3PagerRefcount(pPager) );
47558  return rc;
47559}
47560
47561#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
47562# define setChildPtrmaps(x) SQLITE_OK
47563#endif
47564
47565/*
47566** This routine does the first phase of a two-phase commit.  This routine
47567** causes a rollback journal to be created (if it does not already exist)
47568** and populated with enough information so that if a power loss occurs
47569** the database can be restored to its original state by playing back
47570** the journal.  Then the contents of the journal are flushed out to
47571** the disk.  After the journal is safely on oxide, the changes to the
47572** database are written into the database file and flushed to oxide.
47573** At the end of this call, the rollback journal still exists on the
47574** disk and we are still holding all locks, so the transaction has not
47575** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
47576** commit process.
47577**
47578** This call is a no-op if no write-transaction is currently active on pBt.
47579**
47580** Otherwise, sync the database file for the btree pBt. zMaster points to
47581** the name of a master journal file that should be written into the
47582** individual journal file, or is NULL, indicating no master journal file
47583** (single database transaction).
47584**
47585** When this is called, the master journal should already have been
47586** created, populated with this journal pointer and synced to disk.
47587**
47588** Once this is routine has returned, the only thing required to commit
47589** the write-transaction for this database file is to delete the journal.
47590*/
47591SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
47592  int rc = SQLITE_OK;
47593  if( p->inTrans==TRANS_WRITE ){
47594    BtShared *pBt = p->pBt;
47595    sqlite3BtreeEnter(p);
47596#ifndef SQLITE_OMIT_AUTOVACUUM
47597    if( pBt->autoVacuum ){
47598      rc = autoVacuumCommit(pBt);
47599      if( rc!=SQLITE_OK ){
47600        sqlite3BtreeLeave(p);
47601        return rc;
47602      }
47603    }
47604#endif
47605    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
47606    sqlite3BtreeLeave(p);
47607  }
47608  return rc;
47609}
47610
47611/*
47612** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
47613** at the conclusion of a transaction.
47614*/
47615static void btreeEndTransaction(Btree *p){
47616  BtShared *pBt = p->pBt;
47617  assert( sqlite3BtreeHoldsMutex(p) );
47618
47619  btreeClearHasContent(pBt);
47620  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
47621    /* If there are other active statements that belong to this database
47622    ** handle, downgrade to a read-only transaction. The other statements
47623    ** may still be reading from the database.  */
47624    downgradeAllSharedCacheTableLocks(p);
47625    p->inTrans = TRANS_READ;
47626  }else{
47627    /* If the handle had any kind of transaction open, decrement the
47628    ** transaction count of the shared btree. If the transaction count
47629    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
47630    ** call below will unlock the pager.  */
47631    if( p->inTrans!=TRANS_NONE ){
47632      clearAllSharedCacheTableLocks(p);
47633      pBt->nTransaction--;
47634      if( 0==pBt->nTransaction ){
47635        pBt->inTransaction = TRANS_NONE;
47636      }
47637    }
47638
47639    /* Set the current transaction state to TRANS_NONE and unlock the
47640    ** pager if this call closed the only read or write transaction.  */
47641    p->inTrans = TRANS_NONE;
47642    unlockBtreeIfUnused(pBt);
47643  }
47644
47645  btreeIntegrity(p);
47646}
47647
47648/*
47649** Commit the transaction currently in progress.
47650**
47651** This routine implements the second phase of a 2-phase commit.  The
47652** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
47653** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
47654** routine did all the work of writing information out to disk and flushing the
47655** contents so that they are written onto the disk platter.  All this
47656** routine has to do is delete or truncate or zero the header in the
47657** the rollback journal (which causes the transaction to commit) and
47658** drop locks.
47659**
47660** This will release the write lock on the database file.  If there
47661** are no active cursors, it also releases the read lock.
47662*/
47663SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
47664  BtShared *pBt = p->pBt;
47665
47666  sqlite3BtreeEnter(p);
47667  btreeIntegrity(p);
47668
47669  /* If the handle has a write-transaction open, commit the shared-btrees
47670  ** transaction and set the shared state to TRANS_READ.
47671  */
47672  if( p->inTrans==TRANS_WRITE ){
47673    int rc;
47674    assert( pBt->inTransaction==TRANS_WRITE );
47675    assert( pBt->nTransaction>0 );
47676    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
47677    if( rc!=SQLITE_OK ){
47678      sqlite3BtreeLeave(p);
47679      return rc;
47680    }
47681    pBt->inTransaction = TRANS_READ;
47682  }
47683
47684  btreeEndTransaction(p);
47685  sqlite3BtreeLeave(p);
47686  return SQLITE_OK;
47687}
47688
47689/*
47690** Do both phases of a commit.
47691*/
47692SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
47693  int rc;
47694  sqlite3BtreeEnter(p);
47695  rc = sqlite3BtreeCommitPhaseOne(p, 0);
47696  if( rc==SQLITE_OK ){
47697    rc = sqlite3BtreeCommitPhaseTwo(p);
47698  }
47699  sqlite3BtreeLeave(p);
47700  return rc;
47701}
47702
47703#ifndef NDEBUG
47704/*
47705** Return the number of write-cursors open on this handle. This is for use
47706** in assert() expressions, so it is only compiled if NDEBUG is not
47707** defined.
47708**
47709** For the purposes of this routine, a write-cursor is any cursor that
47710** is capable of writing to the databse.  That means the cursor was
47711** originally opened for writing and the cursor has not be disabled
47712** by having its state changed to CURSOR_FAULT.
47713*/
47714static int countWriteCursors(BtShared *pBt){
47715  BtCursor *pCur;
47716  int r = 0;
47717  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
47718    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
47719  }
47720  return r;
47721}
47722#endif
47723
47724/*
47725** This routine sets the state to CURSOR_FAULT and the error
47726** code to errCode for every cursor on BtShared that pBtree
47727** references.
47728**
47729** Every cursor is tripped, including cursors that belong
47730** to other database connections that happen to be sharing
47731** the cache with pBtree.
47732**
47733** This routine gets called when a rollback occurs.
47734** All cursors using the same cache must be tripped
47735** to prevent them from trying to use the btree after
47736** the rollback.  The rollback may have deleted tables
47737** or moved root pages, so it is not sufficient to
47738** save the state of the cursor.  The cursor must be
47739** invalidated.
47740*/
47741SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
47742  BtCursor *p;
47743  sqlite3BtreeEnter(pBtree);
47744  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47745    int i;
47746    sqlite3BtreeClearCursor(p);
47747    p->eState = CURSOR_FAULT;
47748    p->skipNext = errCode;
47749    for(i=0; i<=p->iPage; i++){
47750      releasePage(p->apPage[i]);
47751      p->apPage[i] = 0;
47752    }
47753  }
47754  sqlite3BtreeLeave(pBtree);
47755}
47756
47757/*
47758** Rollback the transaction in progress.  All cursors will be
47759** invalided by this operation.  Any attempt to use a cursor
47760** that was open at the beginning of this operation will result
47761** in an error.
47762**
47763** This will release the write lock on the database file.  If there
47764** are no active cursors, it also releases the read lock.
47765*/
47766SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
47767  int rc;
47768  BtShared *pBt = p->pBt;
47769  MemPage *pPage1;
47770
47771  sqlite3BtreeEnter(p);
47772  rc = saveAllCursors(pBt, 0, 0);
47773#ifndef SQLITE_OMIT_SHARED_CACHE
47774  if( rc!=SQLITE_OK ){
47775    /* This is a horrible situation. An IO or malloc() error occurred whilst
47776    ** trying to save cursor positions. If this is an automatic rollback (as
47777    ** the result of a constraint, malloc() failure or IO error) then
47778    ** the cache may be internally inconsistent (not contain valid trees) so
47779    ** we cannot simply return the error to the caller. Instead, abort
47780    ** all queries that may be using any of the cursors that failed to save.
47781    */
47782    sqlite3BtreeTripAllCursors(p, rc);
47783  }
47784#endif
47785  btreeIntegrity(p);
47786
47787  if( p->inTrans==TRANS_WRITE ){
47788    int rc2;
47789
47790    assert( TRANS_WRITE==pBt->inTransaction );
47791    rc2 = sqlite3PagerRollback(pBt->pPager);
47792    if( rc2!=SQLITE_OK ){
47793      rc = rc2;
47794    }
47795
47796    /* The rollback may have destroyed the pPage1->aData value.  So
47797    ** call btreeGetPage() on page 1 again to make
47798    ** sure pPage1->aData is set correctly. */
47799    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
47800      int nPage = get4byte(28+(u8*)pPage1->aData);
47801      testcase( nPage==0 );
47802      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
47803      testcase( pBt->nPage!=nPage );
47804      pBt->nPage = nPage;
47805      releasePage(pPage1);
47806    }
47807    assert( countWriteCursors(pBt)==0 );
47808    pBt->inTransaction = TRANS_READ;
47809  }
47810
47811  btreeEndTransaction(p);
47812  sqlite3BtreeLeave(p);
47813  return rc;
47814}
47815
47816/*
47817** Start a statement subtransaction. The subtransaction can can be rolled
47818** back independently of the main transaction. You must start a transaction
47819** before starting a subtransaction. The subtransaction is ended automatically
47820** if the main transaction commits or rolls back.
47821**
47822** Statement subtransactions are used around individual SQL statements
47823** that are contained within a BEGIN...COMMIT block.  If a constraint
47824** error occurs within the statement, the effect of that one statement
47825** can be rolled back without having to rollback the entire transaction.
47826**
47827** A statement sub-transaction is implemented as an anonymous savepoint. The
47828** value passed as the second parameter is the total number of savepoints,
47829** including the new anonymous savepoint, open on the B-Tree. i.e. if there
47830** are no active savepoints and no other statement-transactions open,
47831** iStatement is 1. This anonymous savepoint can be released or rolled back
47832** using the sqlite3BtreeSavepoint() function.
47833*/
47834SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
47835  int rc;
47836  BtShared *pBt = p->pBt;
47837  sqlite3BtreeEnter(p);
47838  assert( p->inTrans==TRANS_WRITE );
47839  assert( pBt->readOnly==0 );
47840  assert( iStatement>0 );
47841  assert( iStatement>p->db->nSavepoint );
47842  assert( pBt->inTransaction==TRANS_WRITE );
47843  /* At the pager level, a statement transaction is a savepoint with
47844  ** an index greater than all savepoints created explicitly using
47845  ** SQL statements. It is illegal to open, release or rollback any
47846  ** such savepoints while the statement transaction savepoint is active.
47847  */
47848  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
47849  sqlite3BtreeLeave(p);
47850  return rc;
47851}
47852
47853/*
47854** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
47855** or SAVEPOINT_RELEASE. This function either releases or rolls back the
47856** savepoint identified by parameter iSavepoint, depending on the value
47857** of op.
47858**
47859** Normally, iSavepoint is greater than or equal to zero. However, if op is
47860** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
47861** contents of the entire transaction are rolled back. This is different
47862** from a normal transaction rollback, as no locks are released and the
47863** transaction remains open.
47864*/
47865SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
47866  int rc = SQLITE_OK;
47867  if( p && p->inTrans==TRANS_WRITE ){
47868    BtShared *pBt = p->pBt;
47869    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
47870    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
47871    sqlite3BtreeEnter(p);
47872    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
47873    if( rc==SQLITE_OK ){
47874      if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
47875      rc = newDatabase(pBt);
47876      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
47877
47878      /* The database size was written into the offset 28 of the header
47879      ** when the transaction started, so we know that the value at offset
47880      ** 28 is nonzero. */
47881      assert( pBt->nPage>0 );
47882    }
47883    sqlite3BtreeLeave(p);
47884  }
47885  return rc;
47886}
47887
47888/*
47889** Create a new cursor for the BTree whose root is on the page
47890** iTable. If a read-only cursor is requested, it is assumed that
47891** the caller already has at least a read-only transaction open
47892** on the database already. If a write-cursor is requested, then
47893** the caller is assumed to have an open write transaction.
47894**
47895** If wrFlag==0, then the cursor can only be used for reading.
47896** If wrFlag==1, then the cursor can be used for reading or for
47897** writing if other conditions for writing are also met.  These
47898** are the conditions that must be met in order for writing to
47899** be allowed:
47900**
47901** 1:  The cursor must have been opened with wrFlag==1
47902**
47903** 2:  Other database connections that share the same pager cache
47904**     but which are not in the READ_UNCOMMITTED state may not have
47905**     cursors open with wrFlag==0 on the same table.  Otherwise
47906**     the changes made by this write cursor would be visible to
47907**     the read cursors in the other database connection.
47908**
47909** 3:  The database must be writable (not on read-only media)
47910**
47911** 4:  There must be an active transaction.
47912**
47913** No checking is done to make sure that page iTable really is the
47914** root page of a b-tree.  If it is not, then the cursor acquired
47915** will not work correctly.
47916**
47917** It is assumed that the sqlite3BtreeCursorZero() has been called
47918** on pCur to initialize the memory space prior to invoking this routine.
47919*/
47920static int btreeCursor(
47921  Btree *p,                              /* The btree */
47922  int iTable,                            /* Root page of table to open */
47923  int wrFlag,                            /* 1 to write. 0 read-only */
47924  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
47925  BtCursor *pCur                         /* Space for new cursor */
47926){
47927  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
47928
47929  assert( sqlite3BtreeHoldsMutex(p) );
47930  assert( wrFlag==0 || wrFlag==1 );
47931
47932  /* The following assert statements verify that if this is a sharable
47933  ** b-tree database, the connection is holding the required table locks,
47934  ** and that no other connection has any open cursor that conflicts with
47935  ** this lock.  */
47936  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
47937  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
47938
47939  /* Assert that the caller has opened the required transaction. */
47940  assert( p->inTrans>TRANS_NONE );
47941  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
47942  assert( pBt->pPage1 && pBt->pPage1->aData );
47943
47944  if( NEVER(wrFlag && pBt->readOnly) ){
47945    return SQLITE_READONLY;
47946  }
47947  if( iTable==1 && btreePagecount(pBt)==0 ){
47948    return SQLITE_EMPTY;
47949  }
47950
47951  /* Now that no other errors can occur, finish filling in the BtCursor
47952  ** variables and link the cursor into the BtShared list.  */
47953  pCur->pgnoRoot = (Pgno)iTable;
47954  pCur->iPage = -1;
47955  pCur->pKeyInfo = pKeyInfo;
47956  pCur->pBtree = p;
47957  pCur->pBt = pBt;
47958  pCur->wrFlag = (u8)wrFlag;
47959  pCur->pNext = pBt->pCursor;
47960  if( pCur->pNext ){
47961    pCur->pNext->pPrev = pCur;
47962  }
47963  pBt->pCursor = pCur;
47964  pCur->eState = CURSOR_INVALID;
47965  pCur->cachedRowid = 0;
47966  return SQLITE_OK;
47967}
47968SQLITE_PRIVATE int sqlite3BtreeCursor(
47969  Btree *p,                                   /* The btree */
47970  int iTable,                                 /* Root page of table to open */
47971  int wrFlag,                                 /* 1 to write. 0 read-only */
47972  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
47973  BtCursor *pCur                              /* Write new cursor here */
47974){
47975  int rc;
47976  sqlite3BtreeEnter(p);
47977  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
47978  sqlite3BtreeLeave(p);
47979  return rc;
47980}
47981
47982/*
47983** Return the size of a BtCursor object in bytes.
47984**
47985** This interfaces is needed so that users of cursors can preallocate
47986** sufficient storage to hold a cursor.  The BtCursor object is opaque
47987** to users so they cannot do the sizeof() themselves - they must call
47988** this routine.
47989*/
47990SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
47991  return ROUND8(sizeof(BtCursor));
47992}
47993
47994/*
47995** Initialize memory that will be converted into a BtCursor object.
47996**
47997** The simple approach here would be to memset() the entire object
47998** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
47999** do not need to be zeroed and they are large, so we can save a lot
48000** of run-time by skipping the initialization of those elements.
48001*/
48002SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
48003  memset(p, 0, offsetof(BtCursor, iPage));
48004}
48005
48006/*
48007** Set the cached rowid value of every cursor in the same database file
48008** as pCur and having the same root page number as pCur.  The value is
48009** set to iRowid.
48010**
48011** Only positive rowid values are considered valid for this cache.
48012** The cache is initialized to zero, indicating an invalid cache.
48013** A btree will work fine with zero or negative rowids.  We just cannot
48014** cache zero or negative rowids, which means tables that use zero or
48015** negative rowids might run a little slower.  But in practice, zero
48016** or negative rowids are very uncommon so this should not be a problem.
48017*/
48018SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
48019  BtCursor *p;
48020  for(p=pCur->pBt->pCursor; p; p=p->pNext){
48021    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
48022  }
48023  assert( pCur->cachedRowid==iRowid );
48024}
48025
48026/*
48027** Return the cached rowid for the given cursor.  A negative or zero
48028** return value indicates that the rowid cache is invalid and should be
48029** ignored.  If the rowid cache has never before been set, then a
48030** zero is returned.
48031*/
48032SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
48033  return pCur->cachedRowid;
48034}
48035
48036/*
48037** Close a cursor.  The read lock on the database file is released
48038** when the last cursor is closed.
48039*/
48040SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
48041  Btree *pBtree = pCur->pBtree;
48042  if( pBtree ){
48043    int i;
48044    BtShared *pBt = pCur->pBt;
48045    sqlite3BtreeEnter(pBtree);
48046    sqlite3BtreeClearCursor(pCur);
48047    if( pCur->pPrev ){
48048      pCur->pPrev->pNext = pCur->pNext;
48049    }else{
48050      pBt->pCursor = pCur->pNext;
48051    }
48052    if( pCur->pNext ){
48053      pCur->pNext->pPrev = pCur->pPrev;
48054    }
48055    for(i=0; i<=pCur->iPage; i++){
48056      releasePage(pCur->apPage[i]);
48057    }
48058    unlockBtreeIfUnused(pBt);
48059    invalidateOverflowCache(pCur);
48060    /* sqlite3_free(pCur); */
48061    sqlite3BtreeLeave(pBtree);
48062  }
48063  return SQLITE_OK;
48064}
48065
48066/*
48067** Make sure the BtCursor* given in the argument has a valid
48068** BtCursor.info structure.  If it is not already valid, call
48069** btreeParseCell() to fill it in.
48070**
48071** BtCursor.info is a cache of the information in the current cell.
48072** Using this cache reduces the number of calls to btreeParseCell().
48073**
48074** 2007-06-25:  There is a bug in some versions of MSVC that cause the
48075** compiler to crash when getCellInfo() is implemented as a macro.
48076** But there is a measureable speed advantage to using the macro on gcc
48077** (when less compiler optimizations like -Os or -O0 are used and the
48078** compiler is not doing agressive inlining.)  So we use a real function
48079** for MSVC and a macro for everything else.  Ticket #2457.
48080*/
48081#ifndef NDEBUG
48082  static void assertCellInfo(BtCursor *pCur){
48083    CellInfo info;
48084    int iPage = pCur->iPage;
48085    memset(&info, 0, sizeof(info));
48086    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
48087    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
48088  }
48089#else
48090  #define assertCellInfo(x)
48091#endif
48092#ifdef _MSC_VER
48093  /* Use a real function in MSVC to work around bugs in that compiler. */
48094  static void getCellInfo(BtCursor *pCur){
48095    if( pCur->info.nSize==0 ){
48096      int iPage = pCur->iPage;
48097      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
48098      pCur->validNKey = 1;
48099    }else{
48100      assertCellInfo(pCur);
48101    }
48102  }
48103#else /* if not _MSC_VER */
48104  /* Use a macro in all other compilers so that the function is inlined */
48105#define getCellInfo(pCur)                                                      \
48106  if( pCur->info.nSize==0 ){                                                   \
48107    int iPage = pCur->iPage;                                                   \
48108    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
48109    pCur->validNKey = 1;                                                       \
48110  }else{                                                                       \
48111    assertCellInfo(pCur);                                                      \
48112  }
48113#endif /* _MSC_VER */
48114
48115#ifndef NDEBUG  /* The next routine used only within assert() statements */
48116/*
48117** Return true if the given BtCursor is valid.  A valid cursor is one
48118** that is currently pointing to a row in a (non-empty) table.
48119** This is a verification routine is used only within assert() statements.
48120*/
48121SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
48122  return pCur && pCur->eState==CURSOR_VALID;
48123}
48124#endif /* NDEBUG */
48125
48126/*
48127** Set *pSize to the size of the buffer needed to hold the value of
48128** the key for the current entry.  If the cursor is not pointing
48129** to a valid entry, *pSize is set to 0.
48130**
48131** For a table with the INTKEY flag set, this routine returns the key
48132** itself, not the number of bytes in the key.
48133**
48134** The caller must position the cursor prior to invoking this routine.
48135**
48136** This routine cannot fail.  It always returns SQLITE_OK.
48137*/
48138SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
48139  assert( cursorHoldsMutex(pCur) );
48140  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
48141  if( pCur->eState!=CURSOR_VALID ){
48142    *pSize = 0;
48143  }else{
48144    getCellInfo(pCur);
48145    *pSize = pCur->info.nKey;
48146  }
48147  return SQLITE_OK;
48148}
48149
48150/*
48151** Set *pSize to the number of bytes of data in the entry the
48152** cursor currently points to.
48153**
48154** The caller must guarantee that the cursor is pointing to a non-NULL
48155** valid entry.  In other words, the calling procedure must guarantee
48156** that the cursor has Cursor.eState==CURSOR_VALID.
48157**
48158** Failure is not possible.  This function always returns SQLITE_OK.
48159** It might just as well be a procedure (returning void) but we continue
48160** to return an integer result code for historical reasons.
48161*/
48162SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
48163  assert( cursorHoldsMutex(pCur) );
48164  assert( pCur->eState==CURSOR_VALID );
48165  getCellInfo(pCur);
48166  *pSize = pCur->info.nData;
48167  return SQLITE_OK;
48168}
48169
48170/*
48171** Given the page number of an overflow page in the database (parameter
48172** ovfl), this function finds the page number of the next page in the
48173** linked list of overflow pages. If possible, it uses the auto-vacuum
48174** pointer-map data instead of reading the content of page ovfl to do so.
48175**
48176** If an error occurs an SQLite error code is returned. Otherwise:
48177**
48178** The page number of the next overflow page in the linked list is
48179** written to *pPgnoNext. If page ovfl is the last page in its linked
48180** list, *pPgnoNext is set to zero.
48181**
48182** If ppPage is not NULL, and a reference to the MemPage object corresponding
48183** to page number pOvfl was obtained, then *ppPage is set to point to that
48184** reference. It is the responsibility of the caller to call releasePage()
48185** on *ppPage to free the reference. In no reference was obtained (because
48186** the pointer-map was used to obtain the value for *pPgnoNext), then
48187** *ppPage is set to zero.
48188*/
48189static int getOverflowPage(
48190  BtShared *pBt,               /* The database file */
48191  Pgno ovfl,                   /* Current overflow page number */
48192  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
48193  Pgno *pPgnoNext              /* OUT: Next overflow page number */
48194){
48195  Pgno next = 0;
48196  MemPage *pPage = 0;
48197  int rc = SQLITE_OK;
48198
48199  assert( sqlite3_mutex_held(pBt->mutex) );
48200  assert(pPgnoNext);
48201
48202#ifndef SQLITE_OMIT_AUTOVACUUM
48203  /* Try to find the next page in the overflow list using the
48204  ** autovacuum pointer-map pages. Guess that the next page in
48205  ** the overflow list is page number (ovfl+1). If that guess turns
48206  ** out to be wrong, fall back to loading the data of page
48207  ** number ovfl to determine the next page number.
48208  */
48209  if( pBt->autoVacuum ){
48210    Pgno pgno;
48211    Pgno iGuess = ovfl+1;
48212    u8 eType;
48213
48214    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
48215      iGuess++;
48216    }
48217
48218    if( iGuess<=btreePagecount(pBt) ){
48219      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
48220      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
48221        next = iGuess;
48222        rc = SQLITE_DONE;
48223      }
48224    }
48225  }
48226#endif
48227
48228  assert( next==0 || rc==SQLITE_DONE );
48229  if( rc==SQLITE_OK ){
48230    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
48231    assert( rc==SQLITE_OK || pPage==0 );
48232    if( rc==SQLITE_OK ){
48233      next = get4byte(pPage->aData);
48234    }
48235  }
48236
48237  *pPgnoNext = next;
48238  if( ppPage ){
48239    *ppPage = pPage;
48240  }else{
48241    releasePage(pPage);
48242  }
48243  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
48244}
48245
48246/*
48247** Copy data from a buffer to a page, or from a page to a buffer.
48248**
48249** pPayload is a pointer to data stored on database page pDbPage.
48250** If argument eOp is false, then nByte bytes of data are copied
48251** from pPayload to the buffer pointed at by pBuf. If eOp is true,
48252** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
48253** of data are copied from the buffer pBuf to pPayload.
48254**
48255** SQLITE_OK is returned on success, otherwise an error code.
48256*/
48257static int copyPayload(
48258  void *pPayload,           /* Pointer to page data */
48259  void *pBuf,               /* Pointer to buffer */
48260  int nByte,                /* Number of bytes to copy */
48261  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
48262  DbPage *pDbPage           /* Page containing pPayload */
48263){
48264  if( eOp ){
48265    /* Copy data from buffer to page (a write operation) */
48266    int rc = sqlite3PagerWrite(pDbPage);
48267    if( rc!=SQLITE_OK ){
48268      return rc;
48269    }
48270    memcpy(pPayload, pBuf, nByte);
48271  }else{
48272    /* Copy data from page to buffer (a read operation) */
48273    memcpy(pBuf, pPayload, nByte);
48274  }
48275  return SQLITE_OK;
48276}
48277
48278/*
48279** This function is used to read or overwrite payload information
48280** for the entry that the pCur cursor is pointing to. If the eOp
48281** parameter is 0, this is a read operation (data copied into
48282** buffer pBuf). If it is non-zero, a write (data copied from
48283** buffer pBuf).
48284**
48285** A total of "amt" bytes are read or written beginning at "offset".
48286** Data is read to or from the buffer pBuf.
48287**
48288** The content being read or written might appear on the main page
48289** or be scattered out on multiple overflow pages.
48290**
48291** If the BtCursor.isIncrblobHandle flag is set, and the current
48292** cursor entry uses one or more overflow pages, this function
48293** allocates space for and lazily popluates the overflow page-list
48294** cache array (BtCursor.aOverflow). Subsequent calls use this
48295** cache to make seeking to the supplied offset more efficient.
48296**
48297** Once an overflow page-list cache has been allocated, it may be
48298** invalidated if some other cursor writes to the same table, or if
48299** the cursor is moved to a different row. Additionally, in auto-vacuum
48300** mode, the following events may invalidate an overflow page-list cache.
48301**
48302**   * An incremental vacuum,
48303**   * A commit in auto_vacuum="full" mode,
48304**   * Creating a table (may require moving an overflow page).
48305*/
48306static int accessPayload(
48307  BtCursor *pCur,      /* Cursor pointing to entry to read from */
48308  u32 offset,          /* Begin reading this far into payload */
48309  u32 amt,             /* Read this many bytes */
48310  unsigned char *pBuf, /* Write the bytes into this buffer */
48311  int eOp              /* zero to read. non-zero to write. */
48312){
48313  unsigned char *aPayload;
48314  int rc = SQLITE_OK;
48315  u32 nKey;
48316  int iIdx = 0;
48317  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
48318  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
48319
48320  assert( pPage );
48321  assert( pCur->eState==CURSOR_VALID );
48322  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
48323  assert( cursorHoldsMutex(pCur) );
48324
48325  getCellInfo(pCur);
48326  aPayload = pCur->info.pCell + pCur->info.nHeader;
48327  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
48328
48329  if( NEVER(offset+amt > nKey+pCur->info.nData)
48330   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
48331  ){
48332    /* Trying to read or write past the end of the data is an error */
48333    return SQLITE_CORRUPT_BKPT;
48334  }
48335
48336  /* Check if data must be read/written to/from the btree page itself. */
48337  if( offset<pCur->info.nLocal ){
48338    int a = amt;
48339    if( a+offset>pCur->info.nLocal ){
48340      a = pCur->info.nLocal - offset;
48341    }
48342    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
48343    offset = 0;
48344    pBuf += a;
48345    amt -= a;
48346  }else{
48347    offset -= pCur->info.nLocal;
48348  }
48349
48350  if( rc==SQLITE_OK && amt>0 ){
48351    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
48352    Pgno nextPage;
48353
48354    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
48355
48356#ifndef SQLITE_OMIT_INCRBLOB
48357    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
48358    ** has not been allocated, allocate it now. The array is sized at
48359    ** one entry for each overflow page in the overflow chain. The
48360    ** page number of the first overflow page is stored in aOverflow[0],
48361    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
48362    ** (the cache is lazily populated).
48363    */
48364    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
48365      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
48366      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
48367      /* nOvfl is always positive.  If it were zero, fetchPayload would have
48368      ** been used instead of this routine. */
48369      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
48370        rc = SQLITE_NOMEM;
48371      }
48372    }
48373
48374    /* If the overflow page-list cache has been allocated and the
48375    ** entry for the first required overflow page is valid, skip
48376    ** directly to it.
48377    */
48378    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
48379      iIdx = (offset/ovflSize);
48380      nextPage = pCur->aOverflow[iIdx];
48381      offset = (offset%ovflSize);
48382    }
48383#endif
48384
48385    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
48386
48387#ifndef SQLITE_OMIT_INCRBLOB
48388      /* If required, populate the overflow page-list cache. */
48389      if( pCur->aOverflow ){
48390        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
48391        pCur->aOverflow[iIdx] = nextPage;
48392      }
48393#endif
48394
48395      if( offset>=ovflSize ){
48396        /* The only reason to read this page is to obtain the page
48397        ** number for the next page in the overflow chain. The page
48398        ** data is not required. So first try to lookup the overflow
48399        ** page-list cache, if any, then fall back to the getOverflowPage()
48400        ** function.
48401        */
48402#ifndef SQLITE_OMIT_INCRBLOB
48403        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
48404          nextPage = pCur->aOverflow[iIdx+1];
48405        } else
48406#endif
48407          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
48408        offset -= ovflSize;
48409      }else{
48410        /* Need to read this page properly. It contains some of the
48411        ** range of data that is being read (eOp==0) or written (eOp!=0).
48412        */
48413        DbPage *pDbPage;
48414        int a = amt;
48415        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
48416        if( rc==SQLITE_OK ){
48417          aPayload = sqlite3PagerGetData(pDbPage);
48418          nextPage = get4byte(aPayload);
48419          if( a + offset > ovflSize ){
48420            a = ovflSize - offset;
48421          }
48422          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
48423          sqlite3PagerUnref(pDbPage);
48424          offset = 0;
48425          amt -= a;
48426          pBuf += a;
48427        }
48428      }
48429    }
48430  }
48431
48432  if( rc==SQLITE_OK && amt>0 ){
48433    return SQLITE_CORRUPT_BKPT;
48434  }
48435  return rc;
48436}
48437
48438/*
48439** Read part of the key associated with cursor pCur.  Exactly
48440** "amt" bytes will be transfered into pBuf[].  The transfer
48441** begins at "offset".
48442**
48443** The caller must ensure that pCur is pointing to a valid row
48444** in the table.
48445**
48446** Return SQLITE_OK on success or an error code if anything goes
48447** wrong.  An error is returned if "offset+amt" is larger than
48448** the available payload.
48449*/
48450SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
48451  assert( cursorHoldsMutex(pCur) );
48452  assert( pCur->eState==CURSOR_VALID );
48453  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
48454  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
48455  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
48456}
48457
48458/*
48459** Read part of the data associated with cursor pCur.  Exactly
48460** "amt" bytes will be transfered into pBuf[].  The transfer
48461** begins at "offset".
48462**
48463** Return SQLITE_OK on success or an error code if anything goes
48464** wrong.  An error is returned if "offset+amt" is larger than
48465** the available payload.
48466*/
48467SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
48468  int rc;
48469
48470#ifndef SQLITE_OMIT_INCRBLOB
48471  if ( pCur->eState==CURSOR_INVALID ){
48472    return SQLITE_ABORT;
48473  }
48474#endif
48475
48476  assert( cursorHoldsMutex(pCur) );
48477  rc = restoreCursorPosition(pCur);
48478  if( rc==SQLITE_OK ){
48479    assert( pCur->eState==CURSOR_VALID );
48480    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
48481    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
48482    rc = accessPayload(pCur, offset, amt, pBuf, 0);
48483  }
48484  return rc;
48485}
48486
48487/*
48488** Return a pointer to payload information from the entry that the
48489** pCur cursor is pointing to.  The pointer is to the beginning of
48490** the key if skipKey==0 and it points to the beginning of data if
48491** skipKey==1.  The number of bytes of available key/data is written
48492** into *pAmt.  If *pAmt==0, then the value returned will not be
48493** a valid pointer.
48494**
48495** This routine is an optimization.  It is common for the entire key
48496** and data to fit on the local page and for there to be no overflow
48497** pages.  When that is so, this routine can be used to access the
48498** key and data without making a copy.  If the key and/or data spills
48499** onto overflow pages, then accessPayload() must be used to reassemble
48500** the key/data and copy it into a preallocated buffer.
48501**
48502** The pointer returned by this routine looks directly into the cached
48503** page of the database.  The data might change or move the next time
48504** any btree routine is called.
48505*/
48506static const unsigned char *fetchPayload(
48507  BtCursor *pCur,      /* Cursor pointing to entry to read from */
48508  int *pAmt,           /* Write the number of available bytes here */
48509  int skipKey          /* read beginning at data if this is true */
48510){
48511  unsigned char *aPayload;
48512  MemPage *pPage;
48513  u32 nKey;
48514  u32 nLocal;
48515
48516  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
48517  assert( pCur->eState==CURSOR_VALID );
48518  assert( cursorHoldsMutex(pCur) );
48519  pPage = pCur->apPage[pCur->iPage];
48520  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
48521  if( NEVER(pCur->info.nSize==0) ){
48522    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
48523                   &pCur->info);
48524  }
48525  aPayload = pCur->info.pCell;
48526  aPayload += pCur->info.nHeader;
48527  if( pPage->intKey ){
48528    nKey = 0;
48529  }else{
48530    nKey = (int)pCur->info.nKey;
48531  }
48532  if( skipKey ){
48533    aPayload += nKey;
48534    nLocal = pCur->info.nLocal - nKey;
48535  }else{
48536    nLocal = pCur->info.nLocal;
48537    assert( nLocal<=nKey );
48538  }
48539  *pAmt = nLocal;
48540  return aPayload;
48541}
48542
48543
48544/*
48545** For the entry that cursor pCur is point to, return as
48546** many bytes of the key or data as are available on the local
48547** b-tree page.  Write the number of available bytes into *pAmt.
48548**
48549** The pointer returned is ephemeral.  The key/data may move
48550** or be destroyed on the next call to any Btree routine,
48551** including calls from other threads against the same cache.
48552** Hence, a mutex on the BtShared should be held prior to calling
48553** this routine.
48554**
48555** These routines is used to get quick access to key and data
48556** in the common case where no overflow pages are used.
48557*/
48558SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
48559  const void *p = 0;
48560  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48561  assert( cursorHoldsMutex(pCur) );
48562  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
48563    p = (const void*)fetchPayload(pCur, pAmt, 0);
48564  }
48565  return p;
48566}
48567SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
48568  const void *p = 0;
48569  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48570  assert( cursorHoldsMutex(pCur) );
48571  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
48572    p = (const void*)fetchPayload(pCur, pAmt, 1);
48573  }
48574  return p;
48575}
48576
48577
48578/*
48579** Move the cursor down to a new child page.  The newPgno argument is the
48580** page number of the child page to move to.
48581**
48582** This function returns SQLITE_CORRUPT if the page-header flags field of
48583** the new child page does not match the flags field of the parent (i.e.
48584** if an intkey page appears to be the parent of a non-intkey page, or
48585** vice-versa).
48586*/
48587static int moveToChild(BtCursor *pCur, u32 newPgno){
48588  int rc;
48589  int i = pCur->iPage;
48590  MemPage *pNewPage;
48591  BtShared *pBt = pCur->pBt;
48592
48593  assert( cursorHoldsMutex(pCur) );
48594  assert( pCur->eState==CURSOR_VALID );
48595  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
48596  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
48597    return SQLITE_CORRUPT_BKPT;
48598  }
48599  rc = getAndInitPage(pBt, newPgno, &pNewPage);
48600  if( rc ) return rc;
48601  pCur->apPage[i+1] = pNewPage;
48602  pCur->aiIdx[i+1] = 0;
48603  pCur->iPage++;
48604
48605  pCur->info.nSize = 0;
48606  pCur->validNKey = 0;
48607  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
48608    return SQLITE_CORRUPT_BKPT;
48609  }
48610  return SQLITE_OK;
48611}
48612
48613#ifndef NDEBUG
48614/*
48615** Page pParent is an internal (non-leaf) tree page. This function
48616** asserts that page number iChild is the left-child if the iIdx'th
48617** cell in page pParent. Or, if iIdx is equal to the total number of
48618** cells in pParent, that page number iChild is the right-child of
48619** the page.
48620*/
48621static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
48622  assert( iIdx<=pParent->nCell );
48623  if( iIdx==pParent->nCell ){
48624    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
48625  }else{
48626    assert( get4byte(findCell(pParent, iIdx))==iChild );
48627  }
48628}
48629#else
48630#  define assertParentIndex(x,y,z)
48631#endif
48632
48633/*
48634** Move the cursor up to the parent page.
48635**
48636** pCur->idx is set to the cell index that contains the pointer
48637** to the page we are coming from.  If we are coming from the
48638** right-most child page then pCur->idx is set to one more than
48639** the largest cell index.
48640*/
48641static void moveToParent(BtCursor *pCur){
48642  assert( cursorHoldsMutex(pCur) );
48643  assert( pCur->eState==CURSOR_VALID );
48644  assert( pCur->iPage>0 );
48645  assert( pCur->apPage[pCur->iPage] );
48646  assertParentIndex(
48647    pCur->apPage[pCur->iPage-1],
48648    pCur->aiIdx[pCur->iPage-1],
48649    pCur->apPage[pCur->iPage]->pgno
48650  );
48651  releasePage(pCur->apPage[pCur->iPage]);
48652  pCur->iPage--;
48653  pCur->info.nSize = 0;
48654  pCur->validNKey = 0;
48655}
48656
48657/*
48658** Move the cursor to point to the root page of its b-tree structure.
48659**
48660** If the table has a virtual root page, then the cursor is moved to point
48661** to the virtual root page instead of the actual root page. A table has a
48662** virtual root page when the actual root page contains no cells and a
48663** single child page. This can only happen with the table rooted at page 1.
48664**
48665** If the b-tree structure is empty, the cursor state is set to
48666** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
48667** cell located on the root (or virtual root) page and the cursor state
48668** is set to CURSOR_VALID.
48669**
48670** If this function returns successfully, it may be assumed that the
48671** page-header flags indicate that the [virtual] root-page is the expected
48672** kind of b-tree page (i.e. if when opening the cursor the caller did not
48673** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
48674** indicating a table b-tree, or if the caller did specify a KeyInfo
48675** structure the flags byte is set to 0x02 or 0x0A, indicating an index
48676** b-tree).
48677*/
48678static int moveToRoot(BtCursor *pCur){
48679  MemPage *pRoot;
48680  int rc = SQLITE_OK;
48681  Btree *p = pCur->pBtree;
48682  BtShared *pBt = p->pBt;
48683
48684  assert( cursorHoldsMutex(pCur) );
48685  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
48686  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
48687  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
48688  if( pCur->eState>=CURSOR_REQUIRESEEK ){
48689    if( pCur->eState==CURSOR_FAULT ){
48690      assert( pCur->skipNext!=SQLITE_OK );
48691      return pCur->skipNext;
48692    }
48693    sqlite3BtreeClearCursor(pCur);
48694  }
48695
48696  if( pCur->iPage>=0 ){
48697    int i;
48698    for(i=1; i<=pCur->iPage; i++){
48699      releasePage(pCur->apPage[i]);
48700    }
48701    pCur->iPage = 0;
48702  }else{
48703    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
48704    if( rc!=SQLITE_OK ){
48705      pCur->eState = CURSOR_INVALID;
48706      return rc;
48707    }
48708    pCur->iPage = 0;
48709
48710    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
48711    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
48712    ** NULL, the caller expects a table b-tree. If this is not the case,
48713    ** return an SQLITE_CORRUPT error.  */
48714    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
48715    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
48716      return SQLITE_CORRUPT_BKPT;
48717    }
48718  }
48719
48720  /* Assert that the root page is of the correct type. This must be the
48721  ** case as the call to this function that loaded the root-page (either
48722  ** this call or a previous invocation) would have detected corruption
48723  ** if the assumption were not true, and it is not possible for the flags
48724  ** byte to have been modified while this cursor is holding a reference
48725  ** to the page.  */
48726  pRoot = pCur->apPage[0];
48727  assert( pRoot->pgno==pCur->pgnoRoot );
48728  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
48729
48730  pCur->aiIdx[0] = 0;
48731  pCur->info.nSize = 0;
48732  pCur->atLast = 0;
48733  pCur->validNKey = 0;
48734
48735  if( pRoot->nCell==0 && !pRoot->leaf ){
48736    Pgno subpage;
48737    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
48738    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
48739    pCur->eState = CURSOR_VALID;
48740    rc = moveToChild(pCur, subpage);
48741  }else{
48742    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
48743  }
48744  return rc;
48745}
48746
48747/*
48748** Move the cursor down to the left-most leaf entry beneath the
48749** entry to which it is currently pointing.
48750**
48751** The left-most leaf is the one with the smallest key - the first
48752** in ascending order.
48753*/
48754static int moveToLeftmost(BtCursor *pCur){
48755  Pgno pgno;
48756  int rc = SQLITE_OK;
48757  MemPage *pPage;
48758
48759  assert( cursorHoldsMutex(pCur) );
48760  assert( pCur->eState==CURSOR_VALID );
48761  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
48762    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
48763    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
48764    rc = moveToChild(pCur, pgno);
48765  }
48766  return rc;
48767}
48768
48769/*
48770** Move the cursor down to the right-most leaf entry beneath the
48771** page to which it is currently pointing.  Notice the difference
48772** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
48773** finds the left-most entry beneath the *entry* whereas moveToRightmost()
48774** finds the right-most entry beneath the *page*.
48775**
48776** The right-most entry is the one with the largest key - the last
48777** key in ascending order.
48778*/
48779static int moveToRightmost(BtCursor *pCur){
48780  Pgno pgno;
48781  int rc = SQLITE_OK;
48782  MemPage *pPage = 0;
48783
48784  assert( cursorHoldsMutex(pCur) );
48785  assert( pCur->eState==CURSOR_VALID );
48786  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
48787    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
48788    pCur->aiIdx[pCur->iPage] = pPage->nCell;
48789    rc = moveToChild(pCur, pgno);
48790  }
48791  if( rc==SQLITE_OK ){
48792    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
48793    pCur->info.nSize = 0;
48794    pCur->validNKey = 0;
48795  }
48796  return rc;
48797}
48798
48799/* Move the cursor to the first entry in the table.  Return SQLITE_OK
48800** on success.  Set *pRes to 0 if the cursor actually points to something
48801** or set *pRes to 1 if the table is empty.
48802*/
48803SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
48804  int rc;
48805
48806  assert( cursorHoldsMutex(pCur) );
48807  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48808  rc = moveToRoot(pCur);
48809  if( rc==SQLITE_OK ){
48810    if( pCur->eState==CURSOR_INVALID ){
48811      assert( pCur->apPage[pCur->iPage]->nCell==0 );
48812      *pRes = 1;
48813    }else{
48814      assert( pCur->apPage[pCur->iPage]->nCell>0 );
48815      *pRes = 0;
48816      rc = moveToLeftmost(pCur);
48817    }
48818  }
48819  return rc;
48820}
48821
48822/* Move the cursor to the last entry in the table.  Return SQLITE_OK
48823** on success.  Set *pRes to 0 if the cursor actually points to something
48824** or set *pRes to 1 if the table is empty.
48825*/
48826SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
48827  int rc;
48828
48829  assert( cursorHoldsMutex(pCur) );
48830  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48831
48832  /* If the cursor already points to the last entry, this is a no-op. */
48833  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
48834#ifdef SQLITE_DEBUG
48835    /* This block serves to assert() that the cursor really does point
48836    ** to the last entry in the b-tree. */
48837    int ii;
48838    for(ii=0; ii<pCur->iPage; ii++){
48839      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
48840    }
48841    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
48842    assert( pCur->apPage[pCur->iPage]->leaf );
48843#endif
48844    return SQLITE_OK;
48845  }
48846
48847  rc = moveToRoot(pCur);
48848  if( rc==SQLITE_OK ){
48849    if( CURSOR_INVALID==pCur->eState ){
48850      assert( pCur->apPage[pCur->iPage]->nCell==0 );
48851      *pRes = 1;
48852    }else{
48853      assert( pCur->eState==CURSOR_VALID );
48854      *pRes = 0;
48855      rc = moveToRightmost(pCur);
48856      pCur->atLast = rc==SQLITE_OK ?1:0;
48857    }
48858  }
48859  return rc;
48860}
48861
48862/* Move the cursor so that it points to an entry near the key
48863** specified by pIdxKey or intKey.   Return a success code.
48864**
48865** For INTKEY tables, the intKey parameter is used.  pIdxKey
48866** must be NULL.  For index tables, pIdxKey is used and intKey
48867** is ignored.
48868**
48869** If an exact match is not found, then the cursor is always
48870** left pointing at a leaf page which would hold the entry if it
48871** were present.  The cursor might point to an entry that comes
48872** before or after the key.
48873**
48874** An integer is written into *pRes which is the result of
48875** comparing the key with the entry to which the cursor is
48876** pointing.  The meaning of the integer written into
48877** *pRes is as follows:
48878**
48879**     *pRes<0      The cursor is left pointing at an entry that
48880**                  is smaller than intKey/pIdxKey or if the table is empty
48881**                  and the cursor is therefore left point to nothing.
48882**
48883**     *pRes==0     The cursor is left pointing at an entry that
48884**                  exactly matches intKey/pIdxKey.
48885**
48886**     *pRes>0      The cursor is left pointing at an entry that
48887**                  is larger than intKey/pIdxKey.
48888**
48889*/
48890SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
48891  BtCursor *pCur,          /* The cursor to be moved */
48892  UnpackedRecord *pIdxKey, /* Unpacked index key */
48893  i64 intKey,              /* The table key */
48894  int biasRight,           /* If true, bias the search to the high end */
48895  int *pRes                /* Write search results here */
48896){
48897  int rc;
48898
48899  assert( cursorHoldsMutex(pCur) );
48900  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
48901  assert( pRes );
48902  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
48903
48904  /* If the cursor is already positioned at the point we are trying
48905  ** to move to, then just return without doing any work */
48906  if( pCur->eState==CURSOR_VALID && pCur->validNKey
48907   && pCur->apPage[0]->intKey
48908  ){
48909    if( pCur->info.nKey==intKey ){
48910      *pRes = 0;
48911      return SQLITE_OK;
48912    }
48913    if( pCur->atLast && pCur->info.nKey<intKey ){
48914      *pRes = -1;
48915      return SQLITE_OK;
48916    }
48917  }
48918
48919  rc = moveToRoot(pCur);
48920  if( rc ){
48921    return rc;
48922  }
48923  assert( pCur->apPage[pCur->iPage] );
48924  assert( pCur->apPage[pCur->iPage]->isInit );
48925  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
48926  if( pCur->eState==CURSOR_INVALID ){
48927    *pRes = -1;
48928    assert( pCur->apPage[pCur->iPage]->nCell==0 );
48929    return SQLITE_OK;
48930  }
48931  assert( pCur->apPage[0]->intKey || pIdxKey );
48932  for(;;){
48933    int lwr, upr;
48934    Pgno chldPg;
48935    MemPage *pPage = pCur->apPage[pCur->iPage];
48936    int c;
48937
48938    /* pPage->nCell must be greater than zero. If this is the root-page
48939    ** the cursor would have been INVALID above and this for(;;) loop
48940    ** not run. If this is not the root-page, then the moveToChild() routine
48941    ** would have already detected db corruption. Similarly, pPage must
48942    ** be the right kind (index or table) of b-tree page. Otherwise
48943    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
48944    assert( pPage->nCell>0 );
48945    assert( pPage->intKey==(pIdxKey==0) );
48946    lwr = 0;
48947    upr = pPage->nCell-1;
48948    if( biasRight ){
48949      pCur->aiIdx[pCur->iPage] = (u16)upr;
48950    }else{
48951      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
48952    }
48953    for(;;){
48954      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
48955      u8 *pCell;                          /* Pointer to current cell in pPage */
48956
48957      pCur->info.nSize = 0;
48958      pCell = findCell(pPage, idx) + pPage->childPtrSize;
48959      if( pPage->intKey ){
48960        i64 nCellKey;
48961        if( pPage->hasData ){
48962          u32 dummy;
48963          pCell += getVarint32(pCell, dummy);
48964        }
48965        getVarint(pCell, (u64*)&nCellKey);
48966        if( nCellKey==intKey ){
48967          c = 0;
48968        }else if( nCellKey<intKey ){
48969          c = -1;
48970        }else{
48971          assert( nCellKey>intKey );
48972          c = +1;
48973        }
48974        pCur->validNKey = 1;
48975        pCur->info.nKey = nCellKey;
48976      }else{
48977        /* The maximum supported page-size is 65536 bytes. This means that
48978        ** the maximum number of record bytes stored on an index B-Tree
48979        ** page is less than 16384 bytes and may be stored as a 2-byte
48980        ** varint. This information is used to attempt to avoid parsing
48981        ** the entire cell by checking for the cases where the record is
48982        ** stored entirely within the b-tree page by inspecting the first
48983        ** 2 bytes of the cell.
48984        */
48985        int nCell = pCell[0];
48986        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
48987          /* This branch runs if the record-size field of the cell is a
48988          ** single byte varint and the record fits entirely on the main
48989          ** b-tree page.  */
48990          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
48991        }else if( !(pCell[1] & 0x80)
48992          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
48993        ){
48994          /* The record-size field is a 2 byte varint and the record
48995          ** fits entirely on the main b-tree page.  */
48996          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
48997        }else{
48998          /* The record flows over onto one or more overflow pages. In
48999          ** this case the whole cell needs to be parsed, a buffer allocated
49000          ** and accessPayload() used to retrieve the record into the
49001          ** buffer before VdbeRecordCompare() can be called. */
49002          void *pCellKey;
49003          u8 * const pCellBody = pCell - pPage->childPtrSize;
49004          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
49005          nCell = (int)pCur->info.nKey;
49006          pCellKey = sqlite3Malloc( nCell );
49007          if( pCellKey==0 ){
49008            rc = SQLITE_NOMEM;
49009            goto moveto_finish;
49010          }
49011          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
49012          if( rc ){
49013            sqlite3_free(pCellKey);
49014            goto moveto_finish;
49015          }
49016          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
49017          sqlite3_free(pCellKey);
49018        }
49019      }
49020      if( c==0 ){
49021        if( pPage->intKey && !pPage->leaf ){
49022          lwr = idx;
49023          upr = lwr - 1;
49024          break;
49025        }else{
49026          *pRes = 0;
49027          rc = SQLITE_OK;
49028          goto moveto_finish;
49029        }
49030      }
49031      if( c<0 ){
49032        lwr = idx+1;
49033      }else{
49034        upr = idx-1;
49035      }
49036      if( lwr>upr ){
49037        break;
49038      }
49039      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
49040    }
49041    assert( lwr==upr+1 );
49042    assert( pPage->isInit );
49043    if( pPage->leaf ){
49044      chldPg = 0;
49045    }else if( lwr>=pPage->nCell ){
49046      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49047    }else{
49048      chldPg = get4byte(findCell(pPage, lwr));
49049    }
49050    if( chldPg==0 ){
49051      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49052      *pRes = c;
49053      rc = SQLITE_OK;
49054      goto moveto_finish;
49055    }
49056    pCur->aiIdx[pCur->iPage] = (u16)lwr;
49057    pCur->info.nSize = 0;
49058    pCur->validNKey = 0;
49059    rc = moveToChild(pCur, chldPg);
49060    if( rc ) goto moveto_finish;
49061  }
49062moveto_finish:
49063  return rc;
49064}
49065
49066
49067/*
49068** Return TRUE if the cursor is not pointing at an entry of the table.
49069**
49070** TRUE will be returned after a call to sqlite3BtreeNext() moves
49071** past the last entry in the table or sqlite3BtreePrev() moves past
49072** the first entry.  TRUE is also returned if the table is empty.
49073*/
49074SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
49075  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
49076  ** have been deleted? This API will need to change to return an error code
49077  ** as well as the boolean result value.
49078  */
49079  return (CURSOR_VALID!=pCur->eState);
49080}
49081
49082/*
49083** Advance the cursor to the next entry in the database.  If
49084** successful then set *pRes=0.  If the cursor
49085** was already pointing to the last entry in the database before
49086** this routine was called, then set *pRes=1.
49087*/
49088SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
49089  int rc;
49090  int idx;
49091  MemPage *pPage;
49092
49093  assert( cursorHoldsMutex(pCur) );
49094  rc = restoreCursorPosition(pCur);
49095  if( rc!=SQLITE_OK ){
49096    return rc;
49097  }
49098  assert( pRes!=0 );
49099  if( CURSOR_INVALID==pCur->eState ){
49100    *pRes = 1;
49101    return SQLITE_OK;
49102  }
49103  if( pCur->skipNext>0 ){
49104    pCur->skipNext = 0;
49105    *pRes = 0;
49106    return SQLITE_OK;
49107  }
49108  pCur->skipNext = 0;
49109
49110  pPage = pCur->apPage[pCur->iPage];
49111  idx = ++pCur->aiIdx[pCur->iPage];
49112  assert( pPage->isInit );
49113  assert( idx<=pPage->nCell );
49114
49115  pCur->info.nSize = 0;
49116  pCur->validNKey = 0;
49117  if( idx>=pPage->nCell ){
49118    if( !pPage->leaf ){
49119      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
49120      if( rc ) return rc;
49121      rc = moveToLeftmost(pCur);
49122      *pRes = 0;
49123      return rc;
49124    }
49125    do{
49126      if( pCur->iPage==0 ){
49127        *pRes = 1;
49128        pCur->eState = CURSOR_INVALID;
49129        return SQLITE_OK;
49130      }
49131      moveToParent(pCur);
49132      pPage = pCur->apPage[pCur->iPage];
49133    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
49134    *pRes = 0;
49135    if( pPage->intKey ){
49136      rc = sqlite3BtreeNext(pCur, pRes);
49137    }else{
49138      rc = SQLITE_OK;
49139    }
49140    return rc;
49141  }
49142  *pRes = 0;
49143  if( pPage->leaf ){
49144    return SQLITE_OK;
49145  }
49146  rc = moveToLeftmost(pCur);
49147  return rc;
49148}
49149
49150
49151/*
49152** Step the cursor to the back to the previous entry in the database.  If
49153** successful then set *pRes=0.  If the cursor
49154** was already pointing to the first entry in the database before
49155** this routine was called, then set *pRes=1.
49156*/
49157SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
49158  int rc;
49159  MemPage *pPage;
49160
49161  assert( cursorHoldsMutex(pCur) );
49162  rc = restoreCursorPosition(pCur);
49163  if( rc!=SQLITE_OK ){
49164    return rc;
49165  }
49166  pCur->atLast = 0;
49167  if( CURSOR_INVALID==pCur->eState ){
49168    *pRes = 1;
49169    return SQLITE_OK;
49170  }
49171  if( pCur->skipNext<0 ){
49172    pCur->skipNext = 0;
49173    *pRes = 0;
49174    return SQLITE_OK;
49175  }
49176  pCur->skipNext = 0;
49177
49178  pPage = pCur->apPage[pCur->iPage];
49179  assert( pPage->isInit );
49180  if( !pPage->leaf ){
49181    int idx = pCur->aiIdx[pCur->iPage];
49182    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
49183    if( rc ){
49184      return rc;
49185    }
49186    rc = moveToRightmost(pCur);
49187  }else{
49188    while( pCur->aiIdx[pCur->iPage]==0 ){
49189      if( pCur->iPage==0 ){
49190        pCur->eState = CURSOR_INVALID;
49191        *pRes = 1;
49192        return SQLITE_OK;
49193      }
49194      moveToParent(pCur);
49195    }
49196    pCur->info.nSize = 0;
49197    pCur->validNKey = 0;
49198
49199    pCur->aiIdx[pCur->iPage]--;
49200    pPage = pCur->apPage[pCur->iPage];
49201    if( pPage->intKey && !pPage->leaf ){
49202      rc = sqlite3BtreePrevious(pCur, pRes);
49203    }else{
49204      rc = SQLITE_OK;
49205    }
49206  }
49207  *pRes = 0;
49208  return rc;
49209}
49210
49211/*
49212** Allocate a new page from the database file.
49213**
49214** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
49215** has already been called on the new page.)  The new page has also
49216** been referenced and the calling routine is responsible for calling
49217** sqlite3PagerUnref() on the new page when it is done.
49218**
49219** SQLITE_OK is returned on success.  Any other return value indicates
49220** an error.  *ppPage and *pPgno are undefined in the event of an error.
49221** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
49222**
49223** If the "nearby" parameter is not 0, then a (feeble) effort is made to
49224** locate a page close to the page number "nearby".  This can be used in an
49225** attempt to keep related pages close to each other in the database file,
49226** which in turn can make database access faster.
49227**
49228** If the "exact" parameter is not 0, and the page-number nearby exists
49229** anywhere on the free-list, then it is guarenteed to be returned. This
49230** is only used by auto-vacuum databases when allocating a new table.
49231*/
49232static int allocateBtreePage(
49233  BtShared *pBt,
49234  MemPage **ppPage,
49235  Pgno *pPgno,
49236  Pgno nearby,
49237  u8 exact
49238){
49239  MemPage *pPage1;
49240  int rc;
49241  u32 n;     /* Number of pages on the freelist */
49242  u32 k;     /* Number of leaves on the trunk of the freelist */
49243  MemPage *pTrunk = 0;
49244  MemPage *pPrevTrunk = 0;
49245  Pgno mxPage;     /* Total size of the database file */
49246
49247  assert( sqlite3_mutex_held(pBt->mutex) );
49248  pPage1 = pBt->pPage1;
49249  mxPage = btreePagecount(pBt);
49250  n = get4byte(&pPage1->aData[36]);
49251  testcase( n==mxPage-1 );
49252  if( n>=mxPage ){
49253    return SQLITE_CORRUPT_BKPT;
49254  }
49255  if( n>0 ){
49256    /* There are pages on the freelist.  Reuse one of those pages. */
49257    Pgno iTrunk;
49258    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
49259
49260    /* If the 'exact' parameter was true and a query of the pointer-map
49261    ** shows that the page 'nearby' is somewhere on the free-list, then
49262    ** the entire-list will be searched for that page.
49263    */
49264#ifndef SQLITE_OMIT_AUTOVACUUM
49265    if( exact && nearby<=mxPage ){
49266      u8 eType;
49267      assert( nearby>0 );
49268      assert( pBt->autoVacuum );
49269      rc = ptrmapGet(pBt, nearby, &eType, 0);
49270      if( rc ) return rc;
49271      if( eType==PTRMAP_FREEPAGE ){
49272        searchList = 1;
49273      }
49274      *pPgno = nearby;
49275    }
49276#endif
49277
49278    /* Decrement the free-list count by 1. Set iTrunk to the index of the
49279    ** first free-list trunk page. iPrevTrunk is initially 1.
49280    */
49281    rc = sqlite3PagerWrite(pPage1->pDbPage);
49282    if( rc ) return rc;
49283    put4byte(&pPage1->aData[36], n-1);
49284
49285    /* The code within this loop is run only once if the 'searchList' variable
49286    ** is not true. Otherwise, it runs once for each trunk-page on the
49287    ** free-list until the page 'nearby' is located.
49288    */
49289    do {
49290      pPrevTrunk = pTrunk;
49291      if( pPrevTrunk ){
49292        iTrunk = get4byte(&pPrevTrunk->aData[0]);
49293      }else{
49294        iTrunk = get4byte(&pPage1->aData[32]);
49295      }
49296      testcase( iTrunk==mxPage );
49297      if( iTrunk>mxPage ){
49298        rc = SQLITE_CORRUPT_BKPT;
49299      }else{
49300        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
49301      }
49302      if( rc ){
49303        pTrunk = 0;
49304        goto end_allocate_page;
49305      }
49306
49307      k = get4byte(&pTrunk->aData[4]);
49308      if( k==0 && !searchList ){
49309        /* The trunk has no leaves and the list is not being searched.
49310        ** So extract the trunk page itself and use it as the newly
49311        ** allocated page */
49312        assert( pPrevTrunk==0 );
49313        rc = sqlite3PagerWrite(pTrunk->pDbPage);
49314        if( rc ){
49315          goto end_allocate_page;
49316        }
49317        *pPgno = iTrunk;
49318        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
49319        *ppPage = pTrunk;
49320        pTrunk = 0;
49321        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
49322      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
49323        /* Value of k is out of range.  Database corruption */
49324        rc = SQLITE_CORRUPT_BKPT;
49325        goto end_allocate_page;
49326#ifndef SQLITE_OMIT_AUTOVACUUM
49327      }else if( searchList && nearby==iTrunk ){
49328        /* The list is being searched and this trunk page is the page
49329        ** to allocate, regardless of whether it has leaves.
49330        */
49331        assert( *pPgno==iTrunk );
49332        *ppPage = pTrunk;
49333        searchList = 0;
49334        rc = sqlite3PagerWrite(pTrunk->pDbPage);
49335        if( rc ){
49336          goto end_allocate_page;
49337        }
49338        if( k==0 ){
49339          if( !pPrevTrunk ){
49340            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
49341          }else{
49342            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
49343            if( rc!=SQLITE_OK ){
49344              goto end_allocate_page;
49345            }
49346            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
49347          }
49348        }else{
49349          /* The trunk page is required by the caller but it contains
49350          ** pointers to free-list leaves. The first leaf becomes a trunk
49351          ** page in this case.
49352          */
49353          MemPage *pNewTrunk;
49354          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
49355          if( iNewTrunk>mxPage ){
49356            rc = SQLITE_CORRUPT_BKPT;
49357            goto end_allocate_page;
49358          }
49359          testcase( iNewTrunk==mxPage );
49360          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
49361          if( rc!=SQLITE_OK ){
49362            goto end_allocate_page;
49363          }
49364          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
49365          if( rc!=SQLITE_OK ){
49366            releasePage(pNewTrunk);
49367            goto end_allocate_page;
49368          }
49369          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
49370          put4byte(&pNewTrunk->aData[4], k-1);
49371          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
49372          releasePage(pNewTrunk);
49373          if( !pPrevTrunk ){
49374            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
49375            put4byte(&pPage1->aData[32], iNewTrunk);
49376          }else{
49377            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
49378            if( rc ){
49379              goto end_allocate_page;
49380            }
49381            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
49382          }
49383        }
49384        pTrunk = 0;
49385        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
49386#endif
49387      }else if( k>0 ){
49388        /* Extract a leaf from the trunk */
49389        u32 closest;
49390        Pgno iPage;
49391        unsigned char *aData = pTrunk->aData;
49392        rc = sqlite3PagerWrite(pTrunk->pDbPage);
49393        if( rc ){
49394          goto end_allocate_page;
49395        }
49396        if( nearby>0 ){
49397          u32 i;
49398          int dist;
49399          closest = 0;
49400          dist = get4byte(&aData[8]) - nearby;
49401          if( dist<0 ) dist = -dist;
49402          for(i=1; i<k; i++){
49403            int d2 = get4byte(&aData[8+i*4]) - nearby;
49404            if( d2<0 ) d2 = -d2;
49405            if( d2<dist ){
49406              closest = i;
49407              dist = d2;
49408            }
49409          }
49410        }else{
49411          closest = 0;
49412        }
49413
49414        iPage = get4byte(&aData[8+closest*4]);
49415        testcase( iPage==mxPage );
49416        if( iPage>mxPage ){
49417          rc = SQLITE_CORRUPT_BKPT;
49418          goto end_allocate_page;
49419        }
49420        testcase( iPage==mxPage );
49421        if( !searchList || iPage==nearby ){
49422          int noContent;
49423          *pPgno = iPage;
49424          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
49425                 ": %d more free pages\n",
49426                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
49427          if( closest<k-1 ){
49428            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
49429          }
49430          put4byte(&aData[4], k-1);
49431          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
49432          noContent = !btreeGetHasContent(pBt, *pPgno);
49433          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
49434          if( rc==SQLITE_OK ){
49435            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
49436            if( rc!=SQLITE_OK ){
49437              releasePage(*ppPage);
49438            }
49439          }
49440          searchList = 0;
49441        }
49442      }
49443      releasePage(pPrevTrunk);
49444      pPrevTrunk = 0;
49445    }while( searchList );
49446  }else{
49447    /* There are no pages on the freelist, so create a new page at the
49448    ** end of the file */
49449    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
49450    if( rc ) return rc;
49451    pBt->nPage++;
49452    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
49453
49454#ifndef SQLITE_OMIT_AUTOVACUUM
49455    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
49456      /* If *pPgno refers to a pointer-map page, allocate two new pages
49457      ** at the end of the file instead of one. The first allocated page
49458      ** becomes a new pointer-map page, the second is used by the caller.
49459      */
49460      MemPage *pPg = 0;
49461      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
49462      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
49463      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
49464      if( rc==SQLITE_OK ){
49465        rc = sqlite3PagerWrite(pPg->pDbPage);
49466        releasePage(pPg);
49467      }
49468      if( rc ) return rc;
49469      pBt->nPage++;
49470      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
49471    }
49472#endif
49473    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
49474    *pPgno = pBt->nPage;
49475
49476    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
49477    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
49478    if( rc ) return rc;
49479    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
49480    if( rc!=SQLITE_OK ){
49481      releasePage(*ppPage);
49482    }
49483    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
49484  }
49485
49486  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
49487
49488end_allocate_page:
49489  releasePage(pTrunk);
49490  releasePage(pPrevTrunk);
49491  if( rc==SQLITE_OK ){
49492    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
49493      releasePage(*ppPage);
49494      return SQLITE_CORRUPT_BKPT;
49495    }
49496    (*ppPage)->isInit = 0;
49497  }else{
49498    *ppPage = 0;
49499  }
49500  return rc;
49501}
49502
49503/*
49504** This function is used to add page iPage to the database file free-list.
49505** It is assumed that the page is not already a part of the free-list.
49506**
49507** The value passed as the second argument to this function is optional.
49508** If the caller happens to have a pointer to the MemPage object
49509** corresponding to page iPage handy, it may pass it as the second value.
49510** Otherwise, it may pass NULL.
49511**
49512** If a pointer to a MemPage object is passed as the second argument,
49513** its reference count is not altered by this function.
49514*/
49515static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
49516  MemPage *pTrunk = 0;                /* Free-list trunk page */
49517  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
49518  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
49519  MemPage *pPage;                     /* Page being freed. May be NULL. */
49520  int rc;                             /* Return Code */
49521  int nFree;                          /* Initial number of pages on free-list */
49522
49523  assert( sqlite3_mutex_held(pBt->mutex) );
49524  assert( iPage>1 );
49525  assert( !pMemPage || pMemPage->pgno==iPage );
49526
49527  if( pMemPage ){
49528    pPage = pMemPage;
49529    sqlite3PagerRef(pPage->pDbPage);
49530  }else{
49531    pPage = btreePageLookup(pBt, iPage);
49532  }
49533
49534  /* Increment the free page count on pPage1 */
49535  rc = sqlite3PagerWrite(pPage1->pDbPage);
49536  if( rc ) goto freepage_out;
49537  nFree = get4byte(&pPage1->aData[36]);
49538  put4byte(&pPage1->aData[36], nFree+1);
49539
49540  if( pBt->secureDelete ){
49541    /* If the secure_delete option is enabled, then
49542    ** always fully overwrite deleted information with zeros.
49543    */
49544    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
49545     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
49546    ){
49547      goto freepage_out;
49548    }
49549    memset(pPage->aData, 0, pPage->pBt->pageSize);
49550  }
49551
49552  /* If the database supports auto-vacuum, write an entry in the pointer-map
49553  ** to indicate that the page is free.
49554  */
49555  if( ISAUTOVACUUM ){
49556    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
49557    if( rc ) goto freepage_out;
49558  }
49559
49560  /* Now manipulate the actual database free-list structure. There are two
49561  ** possibilities. If the free-list is currently empty, or if the first
49562  ** trunk page in the free-list is full, then this page will become a
49563  ** new free-list trunk page. Otherwise, it will become a leaf of the
49564  ** first trunk page in the current free-list. This block tests if it
49565  ** is possible to add the page as a new free-list leaf.
49566  */
49567  if( nFree!=0 ){
49568    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
49569
49570    iTrunk = get4byte(&pPage1->aData[32]);
49571    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
49572    if( rc!=SQLITE_OK ){
49573      goto freepage_out;
49574    }
49575
49576    nLeaf = get4byte(&pTrunk->aData[4]);
49577    assert( pBt->usableSize>32 );
49578    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
49579      rc = SQLITE_CORRUPT_BKPT;
49580      goto freepage_out;
49581    }
49582    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
49583      /* In this case there is room on the trunk page to insert the page
49584      ** being freed as a new leaf.
49585      **
49586      ** Note that the trunk page is not really full until it contains
49587      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
49588      ** coded.  But due to a coding error in versions of SQLite prior to
49589      ** 3.6.0, databases with freelist trunk pages holding more than
49590      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
49591      ** to maintain backwards compatibility with older versions of SQLite,
49592      ** we will continue to restrict the number of entries to usableSize/4 - 8
49593      ** for now.  At some point in the future (once everyone has upgraded
49594      ** to 3.6.0 or later) we should consider fixing the conditional above
49595      ** to read "usableSize/4-2" instead of "usableSize/4-8".
49596      */
49597      rc = sqlite3PagerWrite(pTrunk->pDbPage);
49598      if( rc==SQLITE_OK ){
49599        put4byte(&pTrunk->aData[4], nLeaf+1);
49600        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
49601        if( pPage && !pBt->secureDelete ){
49602          sqlite3PagerDontWrite(pPage->pDbPage);
49603        }
49604        rc = btreeSetHasContent(pBt, iPage);
49605      }
49606      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
49607      goto freepage_out;
49608    }
49609  }
49610
49611  /* If control flows to this point, then it was not possible to add the
49612  ** the page being freed as a leaf page of the first trunk in the free-list.
49613  ** Possibly because the free-list is empty, or possibly because the
49614  ** first trunk in the free-list is full. Either way, the page being freed
49615  ** will become the new first trunk page in the free-list.
49616  */
49617  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
49618    goto freepage_out;
49619  }
49620  rc = sqlite3PagerWrite(pPage->pDbPage);
49621  if( rc!=SQLITE_OK ){
49622    goto freepage_out;
49623  }
49624  put4byte(pPage->aData, iTrunk);
49625  put4byte(&pPage->aData[4], 0);
49626  put4byte(&pPage1->aData[32], iPage);
49627  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
49628
49629freepage_out:
49630  if( pPage ){
49631    pPage->isInit = 0;
49632  }
49633  releasePage(pPage);
49634  releasePage(pTrunk);
49635  return rc;
49636}
49637static void freePage(MemPage *pPage, int *pRC){
49638  if( (*pRC)==SQLITE_OK ){
49639    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
49640  }
49641}
49642
49643/*
49644** Free any overflow pages associated with the given Cell.
49645*/
49646static int clearCell(MemPage *pPage, unsigned char *pCell){
49647  BtShared *pBt = pPage->pBt;
49648  CellInfo info;
49649  Pgno ovflPgno;
49650  int rc;
49651  int nOvfl;
49652  u32 ovflPageSize;
49653
49654  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49655  btreeParseCellPtr(pPage, pCell, &info);
49656  if( info.iOverflow==0 ){
49657    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
49658  }
49659  ovflPgno = get4byte(&pCell[info.iOverflow]);
49660  assert( pBt->usableSize > 4 );
49661  ovflPageSize = pBt->usableSize - 4;
49662  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
49663  assert( ovflPgno==0 || nOvfl>0 );
49664  while( nOvfl-- ){
49665    Pgno iNext = 0;
49666    MemPage *pOvfl = 0;
49667    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
49668      /* 0 is not a legal page number and page 1 cannot be an
49669      ** overflow page. Therefore if ovflPgno<2 or past the end of the
49670      ** file the database must be corrupt. */
49671      return SQLITE_CORRUPT_BKPT;
49672    }
49673    if( nOvfl ){
49674      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
49675      if( rc ) return rc;
49676    }
49677
49678    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
49679     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
49680    ){
49681      /* There is no reason any cursor should have an outstanding reference
49682      ** to an overflow page belonging to a cell that is being deleted/updated.
49683      ** So if there exists more than one reference to this page, then it
49684      ** must not really be an overflow page and the database must be corrupt.
49685      ** It is helpful to detect this before calling freePage2(), as
49686      ** freePage2() may zero the page contents if secure-delete mode is
49687      ** enabled. If this 'overflow' page happens to be a page that the
49688      ** caller is iterating through or using in some other way, this
49689      ** can be problematic.
49690      */
49691      rc = SQLITE_CORRUPT_BKPT;
49692    }else{
49693      rc = freePage2(pBt, pOvfl, ovflPgno);
49694    }
49695
49696    if( pOvfl ){
49697      sqlite3PagerUnref(pOvfl->pDbPage);
49698    }
49699    if( rc ) return rc;
49700    ovflPgno = iNext;
49701  }
49702  return SQLITE_OK;
49703}
49704
49705/*
49706** Create the byte sequence used to represent a cell on page pPage
49707** and write that byte sequence into pCell[].  Overflow pages are
49708** allocated and filled in as necessary.  The calling procedure
49709** is responsible for making sure sufficient space has been allocated
49710** for pCell[].
49711**
49712** Note that pCell does not necessary need to point to the pPage->aData
49713** area.  pCell might point to some temporary storage.  The cell will
49714** be constructed in this temporary area then copied into pPage->aData
49715** later.
49716*/
49717static int fillInCell(
49718  MemPage *pPage,                /* The page that contains the cell */
49719  unsigned char *pCell,          /* Complete text of the cell */
49720  const void *pKey, i64 nKey,    /* The key */
49721  const void *pData,int nData,   /* The data */
49722  int nZero,                     /* Extra zero bytes to append to pData */
49723  int *pnSize                    /* Write cell size here */
49724){
49725  int nPayload;
49726  const u8 *pSrc;
49727  int nSrc, n, rc;
49728  int spaceLeft;
49729  MemPage *pOvfl = 0;
49730  MemPage *pToRelease = 0;
49731  unsigned char *pPrior;
49732  unsigned char *pPayload;
49733  BtShared *pBt = pPage->pBt;
49734  Pgno pgnoOvfl = 0;
49735  int nHeader;
49736  CellInfo info;
49737
49738  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49739
49740  /* pPage is not necessarily writeable since pCell might be auxiliary
49741  ** buffer space that is separate from the pPage buffer area */
49742  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
49743            || sqlite3PagerIswriteable(pPage->pDbPage) );
49744
49745  /* Fill in the header. */
49746  nHeader = 0;
49747  if( !pPage->leaf ){
49748    nHeader += 4;
49749  }
49750  if( pPage->hasData ){
49751    nHeader += putVarint(&pCell[nHeader], nData+nZero);
49752  }else{
49753    nData = nZero = 0;
49754  }
49755  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
49756  btreeParseCellPtr(pPage, pCell, &info);
49757  assert( info.nHeader==nHeader );
49758  assert( info.nKey==nKey );
49759  assert( info.nData==(u32)(nData+nZero) );
49760
49761  /* Fill in the payload */
49762  nPayload = nData + nZero;
49763  if( pPage->intKey ){
49764    pSrc = pData;
49765    nSrc = nData;
49766    nData = 0;
49767  }else{
49768    if( NEVER(nKey>0x7fffffff || pKey==0) ){
49769      return SQLITE_CORRUPT_BKPT;
49770    }
49771    nPayload += (int)nKey;
49772    pSrc = pKey;
49773    nSrc = (int)nKey;
49774  }
49775  *pnSize = info.nSize;
49776  spaceLeft = info.nLocal;
49777  pPayload = &pCell[nHeader];
49778  pPrior = &pCell[info.iOverflow];
49779
49780  while( nPayload>0 ){
49781    if( spaceLeft==0 ){
49782#ifndef SQLITE_OMIT_AUTOVACUUM
49783      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
49784      if( pBt->autoVacuum ){
49785        do{
49786          pgnoOvfl++;
49787        } while(
49788          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
49789        );
49790      }
49791#endif
49792      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
49793#ifndef SQLITE_OMIT_AUTOVACUUM
49794      /* If the database supports auto-vacuum, and the second or subsequent
49795      ** overflow page is being allocated, add an entry to the pointer-map
49796      ** for that page now.
49797      **
49798      ** If this is the first overflow page, then write a partial entry
49799      ** to the pointer-map. If we write nothing to this pointer-map slot,
49800      ** then the optimistic overflow chain processing in clearCell()
49801      ** may misinterpret the uninitialised values and delete the
49802      ** wrong pages from the database.
49803      */
49804      if( pBt->autoVacuum && rc==SQLITE_OK ){
49805        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
49806        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
49807        if( rc ){
49808          releasePage(pOvfl);
49809        }
49810      }
49811#endif
49812      if( rc ){
49813        releasePage(pToRelease);
49814        return rc;
49815      }
49816
49817      /* If pToRelease is not zero than pPrior points into the data area
49818      ** of pToRelease.  Make sure pToRelease is still writeable. */
49819      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
49820
49821      /* If pPrior is part of the data area of pPage, then make sure pPage
49822      ** is still writeable */
49823      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
49824            || sqlite3PagerIswriteable(pPage->pDbPage) );
49825
49826      put4byte(pPrior, pgnoOvfl);
49827      releasePage(pToRelease);
49828      pToRelease = pOvfl;
49829      pPrior = pOvfl->aData;
49830      put4byte(pPrior, 0);
49831      pPayload = &pOvfl->aData[4];
49832      spaceLeft = pBt->usableSize - 4;
49833    }
49834    n = nPayload;
49835    if( n>spaceLeft ) n = spaceLeft;
49836
49837    /* If pToRelease is not zero than pPayload points into the data area
49838    ** of pToRelease.  Make sure pToRelease is still writeable. */
49839    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
49840
49841    /* If pPayload is part of the data area of pPage, then make sure pPage
49842    ** is still writeable */
49843    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
49844            || sqlite3PagerIswriteable(pPage->pDbPage) );
49845
49846    if( nSrc>0 ){
49847      if( n>nSrc ) n = nSrc;
49848      assert( pSrc );
49849      memcpy(pPayload, pSrc, n);
49850    }else{
49851      memset(pPayload, 0, n);
49852    }
49853    nPayload -= n;
49854    pPayload += n;
49855    pSrc += n;
49856    nSrc -= n;
49857    spaceLeft -= n;
49858    if( nSrc==0 ){
49859      nSrc = nData;
49860      pSrc = pData;
49861    }
49862  }
49863  releasePage(pToRelease);
49864  return SQLITE_OK;
49865}
49866
49867/*
49868** Remove the i-th cell from pPage.  This routine effects pPage only.
49869** The cell content is not freed or deallocated.  It is assumed that
49870** the cell content has been copied someplace else.  This routine just
49871** removes the reference to the cell from pPage.
49872**
49873** "sz" must be the number of bytes in the cell.
49874*/
49875static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
49876  int i;          /* Loop counter */
49877  u32 pc;         /* Offset to cell content of cell being deleted */
49878  u8 *data;       /* pPage->aData */
49879  u8 *ptr;        /* Used to move bytes around within data[] */
49880  int rc;         /* The return code */
49881  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
49882
49883  if( *pRC ) return;
49884
49885  assert( idx>=0 && idx<pPage->nCell );
49886  assert( sz==cellSize(pPage, idx) );
49887  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49888  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49889  data = pPage->aData;
49890  ptr = &data[pPage->cellOffset + 2*idx];
49891  pc = get2byte(ptr);
49892  hdr = pPage->hdrOffset;
49893  testcase( pc==get2byte(&data[hdr+5]) );
49894  testcase( pc+sz==pPage->pBt->usableSize );
49895  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
49896    *pRC = SQLITE_CORRUPT_BKPT;
49897    return;
49898  }
49899  rc = freeSpace(pPage, pc, sz);
49900  if( rc ){
49901    *pRC = rc;
49902    return;
49903  }
49904  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
49905    ptr[0] = ptr[2];
49906    ptr[1] = ptr[3];
49907  }
49908  pPage->nCell--;
49909  put2byte(&data[hdr+3], pPage->nCell);
49910  pPage->nFree += 2;
49911}
49912
49913/*
49914** Insert a new cell on pPage at cell index "i".  pCell points to the
49915** content of the cell.
49916**
49917** If the cell content will fit on the page, then put it there.  If it
49918** will not fit, then make a copy of the cell content into pTemp if
49919** pTemp is not null.  Regardless of pTemp, allocate a new entry
49920** in pPage->aOvfl[] and make it point to the cell content (either
49921** in pTemp or the original pCell) and also record its index.
49922** Allocating a new entry in pPage->aCell[] implies that
49923** pPage->nOverflow is incremented.
49924**
49925** If nSkip is non-zero, then do not copy the first nSkip bytes of the
49926** cell. The caller will overwrite them after this function returns. If
49927** nSkip is non-zero, then pCell may not point to an invalid memory location
49928** (but pCell+nSkip is always valid).
49929*/
49930static void insertCell(
49931  MemPage *pPage,   /* Page into which we are copying */
49932  int i,            /* New cell becomes the i-th cell of the page */
49933  u8 *pCell,        /* Content of the new cell */
49934  int sz,           /* Bytes of content in pCell */
49935  u8 *pTemp,        /* Temp storage space for pCell, if needed */
49936  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
49937  int *pRC          /* Read and write return code from here */
49938){
49939  int idx = 0;      /* Where to write new cell content in data[] */
49940  int j;            /* Loop counter */
49941  int end;          /* First byte past the last cell pointer in data[] */
49942  int ins;          /* Index in data[] where new cell pointer is inserted */
49943  int cellOffset;   /* Address of first cell pointer in data[] */
49944  u8 *data;         /* The content of the whole page */
49945  u8 *ptr;          /* Used for moving information around in data[] */
49946
49947  int nSkip = (iChild ? 4 : 0);
49948
49949  if( *pRC ) return;
49950
49951  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
49952  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
49953  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
49954  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49955  /* The cell should normally be sized correctly.  However, when moving a
49956  ** malformed cell from a leaf page to an interior page, if the cell size
49957  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
49958  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
49959  ** the term after the || in the following assert(). */
49960  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
49961  if( pPage->nOverflow || sz+2>pPage->nFree ){
49962    if( pTemp ){
49963      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
49964      pCell = pTemp;
49965    }
49966    if( iChild ){
49967      put4byte(pCell, iChild);
49968    }
49969    j = pPage->nOverflow++;
49970    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
49971    pPage->aOvfl[j].pCell = pCell;
49972    pPage->aOvfl[j].idx = (u16)i;
49973  }else{
49974    int rc = sqlite3PagerWrite(pPage->pDbPage);
49975    if( rc!=SQLITE_OK ){
49976      *pRC = rc;
49977      return;
49978    }
49979    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49980    data = pPage->aData;
49981    cellOffset = pPage->cellOffset;
49982    end = cellOffset + 2*pPage->nCell;
49983    ins = cellOffset + 2*i;
49984    rc = allocateSpace(pPage, sz, &idx);
49985    if( rc ){ *pRC = rc; return; }
49986    /* The allocateSpace() routine guarantees the following two properties
49987    ** if it returns success */
49988    assert( idx >= end+2 );
49989    assert( idx+sz <= pPage->pBt->usableSize );
49990    pPage->nCell++;
49991    pPage->nFree -= (u16)(2 + sz);
49992    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
49993    if( iChild ){
49994      put4byte(&data[idx], iChild);
49995    }
49996    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
49997      ptr[0] = ptr[-2];
49998      ptr[1] = ptr[-1];
49999    }
50000    put2byte(&data[ins], idx);
50001    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
50002#ifndef SQLITE_OMIT_AUTOVACUUM
50003    if( pPage->pBt->autoVacuum ){
50004      /* The cell may contain a pointer to an overflow page. If so, write
50005      ** the entry for the overflow page into the pointer map.
50006      */
50007      ptrmapPutOvflPtr(pPage, pCell, pRC);
50008    }
50009#endif
50010  }
50011}
50012
50013/*
50014** Add a list of cells to a page.  The page should be initially empty.
50015** The cells are guaranteed to fit on the page.
50016*/
50017static void assemblePage(
50018  MemPage *pPage,   /* The page to be assemblied */
50019  int nCell,        /* The number of cells to add to this page */
50020  u8 **apCell,      /* Pointers to cell bodies */
50021  u16 *aSize        /* Sizes of the cells */
50022){
50023  int i;            /* Loop counter */
50024  u8 *pCellptr;     /* Address of next cell pointer */
50025  int cellbody;     /* Address of next cell body */
50026  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
50027  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
50028  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
50029
50030  assert( pPage->nOverflow==0 );
50031  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50032  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921);
50033  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50034
50035  /* Check that the page has just been zeroed by zeroPage() */
50036  assert( pPage->nCell==0 );
50037  assert( get2byteNotZero(&data[hdr+5])==nUsable );
50038
50039  pCellptr = &data[pPage->cellOffset + nCell*2];
50040  cellbody = nUsable;
50041  for(i=nCell-1; i>=0; i--){
50042    pCellptr -= 2;
50043    cellbody -= aSize[i];
50044    put2byte(pCellptr, cellbody);
50045    memcpy(&data[cellbody], apCell[i], aSize[i]);
50046  }
50047  put2byte(&data[hdr+3], nCell);
50048  put2byte(&data[hdr+5], cellbody);
50049  pPage->nFree -= (nCell*2 + nUsable - cellbody);
50050  pPage->nCell = (u16)nCell;
50051}
50052
50053/*
50054** The following parameters determine how many adjacent pages get involved
50055** in a balancing operation.  NN is the number of neighbors on either side
50056** of the page that participate in the balancing operation.  NB is the
50057** total number of pages that participate, including the target page and
50058** NN neighbors on either side.
50059**
50060** The minimum value of NN is 1 (of course).  Increasing NN above 1
50061** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
50062** in exchange for a larger degradation in INSERT and UPDATE performance.
50063** The value of NN appears to give the best results overall.
50064*/
50065#define NN 1             /* Number of neighbors on either side of pPage */
50066#define NB (NN*2+1)      /* Total pages involved in the balance */
50067
50068
50069#ifndef SQLITE_OMIT_QUICKBALANCE
50070/*
50071** This version of balance() handles the common special case where
50072** a new entry is being inserted on the extreme right-end of the
50073** tree, in other words, when the new entry will become the largest
50074** entry in the tree.
50075**
50076** Instead of trying to balance the 3 right-most leaf pages, just add
50077** a new page to the right-hand side and put the one new entry in
50078** that page.  This leaves the right side of the tree somewhat
50079** unbalanced.  But odds are that we will be inserting new entries
50080** at the end soon afterwards so the nearly empty page will quickly
50081** fill up.  On average.
50082**
50083** pPage is the leaf page which is the right-most page in the tree.
50084** pParent is its parent.  pPage must have a single overflow entry
50085** which is also the right-most entry on the page.
50086**
50087** The pSpace buffer is used to store a temporary copy of the divider
50088** cell that will be inserted into pParent. Such a cell consists of a 4
50089** byte page number followed by a variable length integer. In other
50090** words, at most 13 bytes. Hence the pSpace buffer must be at
50091** least 13 bytes in size.
50092*/
50093static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
50094  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
50095  MemPage *pNew;                       /* Newly allocated page */
50096  int rc;                              /* Return Code */
50097  Pgno pgnoNew;                        /* Page number of pNew */
50098
50099  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50100  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50101  assert( pPage->nOverflow==1 );
50102
50103  /* This error condition is now caught prior to reaching this function */
50104  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
50105
50106  /* Allocate a new page. This page will become the right-sibling of
50107  ** pPage. Make the parent page writable, so that the new divider cell
50108  ** may be inserted. If both these operations are successful, proceed.
50109  */
50110  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
50111
50112  if( rc==SQLITE_OK ){
50113
50114    u8 *pOut = &pSpace[4];
50115    u8 *pCell = pPage->aOvfl[0].pCell;
50116    u16 szCell = cellSizePtr(pPage, pCell);
50117    u8 *pStop;
50118
50119    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
50120    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
50121    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
50122    assemblePage(pNew, 1, &pCell, &szCell);
50123
50124    /* If this is an auto-vacuum database, update the pointer map
50125    ** with entries for the new page, and any pointer from the
50126    ** cell on the page to an overflow page. If either of these
50127    ** operations fails, the return code is set, but the contents
50128    ** of the parent page are still manipulated by thh code below.
50129    ** That is Ok, at this point the parent page is guaranteed to
50130    ** be marked as dirty. Returning an error code will cause a
50131    ** rollback, undoing any changes made to the parent page.
50132    */
50133    if( ISAUTOVACUUM ){
50134      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
50135      if( szCell>pNew->minLocal ){
50136        ptrmapPutOvflPtr(pNew, pCell, &rc);
50137      }
50138    }
50139
50140    /* Create a divider cell to insert into pParent. The divider cell
50141    ** consists of a 4-byte page number (the page number of pPage) and
50142    ** a variable length key value (which must be the same value as the
50143    ** largest key on pPage).
50144    **
50145    ** To find the largest key value on pPage, first find the right-most
50146    ** cell on pPage. The first two fields of this cell are the
50147    ** record-length (a variable length integer at most 32-bits in size)
50148    ** and the key value (a variable length integer, may have any value).
50149    ** The first of the while(...) loops below skips over the record-length
50150    ** field. The second while(...) loop copies the key value from the
50151    ** cell on pPage into the pSpace buffer.
50152    */
50153    pCell = findCell(pPage, pPage->nCell-1);
50154    pStop = &pCell[9];
50155    while( (*(pCell++)&0x80) && pCell<pStop );
50156    pStop = &pCell[9];
50157    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
50158
50159    /* Insert the new divider cell into pParent. */
50160    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
50161               0, pPage->pgno, &rc);
50162
50163    /* Set the right-child pointer of pParent to point to the new page. */
50164    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
50165
50166    /* Release the reference to the new page. */
50167    releasePage(pNew);
50168  }
50169
50170  return rc;
50171}
50172#endif /* SQLITE_OMIT_QUICKBALANCE */
50173
50174#if 0
50175/*
50176** This function does not contribute anything to the operation of SQLite.
50177** it is sometimes activated temporarily while debugging code responsible
50178** for setting pointer-map entries.
50179*/
50180static int ptrmapCheckPages(MemPage **apPage, int nPage){
50181  int i, j;
50182  for(i=0; i<nPage; i++){
50183    Pgno n;
50184    u8 e;
50185    MemPage *pPage = apPage[i];
50186    BtShared *pBt = pPage->pBt;
50187    assert( pPage->isInit );
50188
50189    for(j=0; j<pPage->nCell; j++){
50190      CellInfo info;
50191      u8 *z;
50192
50193      z = findCell(pPage, j);
50194      btreeParseCellPtr(pPage, z, &info);
50195      if( info.iOverflow ){
50196        Pgno ovfl = get4byte(&z[info.iOverflow]);
50197        ptrmapGet(pBt, ovfl, &e, &n);
50198        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
50199      }
50200      if( !pPage->leaf ){
50201        Pgno child = get4byte(z);
50202        ptrmapGet(pBt, child, &e, &n);
50203        assert( n==pPage->pgno && e==PTRMAP_BTREE );
50204      }
50205    }
50206    if( !pPage->leaf ){
50207      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50208      ptrmapGet(pBt, child, &e, &n);
50209      assert( n==pPage->pgno && e==PTRMAP_BTREE );
50210    }
50211  }
50212  return 1;
50213}
50214#endif
50215
50216/*
50217** This function is used to copy the contents of the b-tree node stored
50218** on page pFrom to page pTo. If page pFrom was not a leaf page, then
50219** the pointer-map entries for each child page are updated so that the
50220** parent page stored in the pointer map is page pTo. If pFrom contained
50221** any cells with overflow page pointers, then the corresponding pointer
50222** map entries are also updated so that the parent page is page pTo.
50223**
50224** If pFrom is currently carrying any overflow cells (entries in the
50225** MemPage.aOvfl[] array), they are not copied to pTo.
50226**
50227** Before returning, page pTo is reinitialized using btreeInitPage().
50228**
50229** The performance of this function is not critical. It is only used by
50230** the balance_shallower() and balance_deeper() procedures, neither of
50231** which are called often under normal circumstances.
50232*/
50233static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
50234  if( (*pRC)==SQLITE_OK ){
50235    BtShared * const pBt = pFrom->pBt;
50236    u8 * const aFrom = pFrom->aData;
50237    u8 * const aTo = pTo->aData;
50238    int const iFromHdr = pFrom->hdrOffset;
50239    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
50240    int rc;
50241    int iData;
50242
50243
50244    assert( pFrom->isInit );
50245    assert( pFrom->nFree>=iToHdr );
50246    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
50247
50248    /* Copy the b-tree node content from page pFrom to page pTo. */
50249    iData = get2byte(&aFrom[iFromHdr+5]);
50250    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
50251    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
50252
50253    /* Reinitialize page pTo so that the contents of the MemPage structure
50254    ** match the new data. The initialization of pTo can actually fail under
50255    ** fairly obscure circumstances, even though it is a copy of initialized
50256    ** page pFrom.
50257    */
50258    pTo->isInit = 0;
50259    rc = btreeInitPage(pTo);
50260    if( rc!=SQLITE_OK ){
50261      *pRC = rc;
50262      return;
50263    }
50264
50265    /* If this is an auto-vacuum database, update the pointer-map entries
50266    ** for any b-tree or overflow pages that pTo now contains the pointers to.
50267    */
50268    if( ISAUTOVACUUM ){
50269      *pRC = setChildPtrmaps(pTo);
50270    }
50271  }
50272}
50273
50274/*
50275** This routine redistributes cells on the iParentIdx'th child of pParent
50276** (hereafter "the page") and up to 2 siblings so that all pages have about the
50277** same amount of free space. Usually a single sibling on either side of the
50278** page are used in the balancing, though both siblings might come from one
50279** side if the page is the first or last child of its parent. If the page
50280** has fewer than 2 siblings (something which can only happen if the page
50281** is a root page or a child of a root page) then all available siblings
50282** participate in the balancing.
50283**
50284** The number of siblings of the page might be increased or decreased by
50285** one or two in an effort to keep pages nearly full but not over full.
50286**
50287** Note that when this routine is called, some of the cells on the page
50288** might not actually be stored in MemPage.aData[]. This can happen
50289** if the page is overfull. This routine ensures that all cells allocated
50290** to the page and its siblings fit into MemPage.aData[] before returning.
50291**
50292** In the course of balancing the page and its siblings, cells may be
50293** inserted into or removed from the parent page (pParent). Doing so
50294** may cause the parent page to become overfull or underfull. If this
50295** happens, it is the responsibility of the caller to invoke the correct
50296** balancing routine to fix this problem (see the balance() routine).
50297**
50298** If this routine fails for any reason, it might leave the database
50299** in a corrupted state. So if this routine fails, the database should
50300** be rolled back.
50301**
50302** The third argument to this function, aOvflSpace, is a pointer to a
50303** buffer big enough to hold one page. If while inserting cells into the parent
50304** page (pParent) the parent page becomes overfull, this buffer is
50305** used to store the parent's overflow cells. Because this function inserts
50306** a maximum of four divider cells into the parent page, and the maximum
50307** size of a cell stored within an internal node is always less than 1/4
50308** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
50309** enough for all overflow cells.
50310**
50311** If aOvflSpace is set to a null pointer, this function returns
50312** SQLITE_NOMEM.
50313*/
50314static int balance_nonroot(
50315  MemPage *pParent,               /* Parent page of siblings being balanced */
50316  int iParentIdx,                 /* Index of "the page" in pParent */
50317  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
50318  int isRoot                      /* True if pParent is a root-page */
50319){
50320  BtShared *pBt;               /* The whole database */
50321  int nCell = 0;               /* Number of cells in apCell[] */
50322  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
50323  int nNew = 0;                /* Number of pages in apNew[] */
50324  int nOld;                    /* Number of pages in apOld[] */
50325  int i, j, k;                 /* Loop counters */
50326  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
50327  int rc = SQLITE_OK;          /* The return code */
50328  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
50329  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
50330  int usableSpace;             /* Bytes in pPage beyond the header */
50331  int pageFlags;               /* Value of pPage->aData[0] */
50332  int subtotal;                /* Subtotal of bytes in cells on one page */
50333  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
50334  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
50335  int szScratch;               /* Size of scratch memory requested */
50336  MemPage *apOld[NB];          /* pPage and up to two siblings */
50337  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
50338  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
50339  u8 *pRight;                  /* Location in parent of right-sibling pointer */
50340  u8 *apDiv[NB-1];             /* Divider cells in pParent */
50341  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
50342  int szNew[NB+2];             /* Combined size of cells place on i-th page */
50343  u8 **apCell = 0;             /* All cells begin balanced */
50344  u16 *szCell;                 /* Local size of all cells in apCell[] */
50345  u8 *aSpace1;                 /* Space for copies of dividers cells */
50346  Pgno pgno;                   /* Temp var to store a page number in */
50347
50348  pBt = pParent->pBt;
50349  assert( sqlite3_mutex_held(pBt->mutex) );
50350  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50351
50352#if 0
50353  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
50354#endif
50355
50356  /* At this point pParent may have at most one overflow cell. And if
50357  ** this overflow cell is present, it must be the cell with
50358  ** index iParentIdx. This scenario comes about when this function
50359  ** is called (indirectly) from sqlite3BtreeDelete().
50360  */
50361  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
50362  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
50363
50364  if( !aOvflSpace ){
50365    return SQLITE_NOMEM;
50366  }
50367
50368  /* Find the sibling pages to balance. Also locate the cells in pParent
50369  ** that divide the siblings. An attempt is made to find NN siblings on
50370  ** either side of pPage. More siblings are taken from one side, however,
50371  ** if there are fewer than NN siblings on the other side. If pParent
50372  ** has NB or fewer children then all children of pParent are taken.
50373  **
50374  ** This loop also drops the divider cells from the parent page. This
50375  ** way, the remainder of the function does not have to deal with any
50376  ** overflow cells in the parent page, since if any existed they will
50377  ** have already been removed.
50378  */
50379  i = pParent->nOverflow + pParent->nCell;
50380  if( i<2 ){
50381    nxDiv = 0;
50382    nOld = i+1;
50383  }else{
50384    nOld = 3;
50385    if( iParentIdx==0 ){
50386      nxDiv = 0;
50387    }else if( iParentIdx==i ){
50388      nxDiv = i-2;
50389    }else{
50390      nxDiv = iParentIdx-1;
50391    }
50392    i = 2;
50393  }
50394  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
50395    pRight = &pParent->aData[pParent->hdrOffset+8];
50396  }else{
50397    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
50398  }
50399  pgno = get4byte(pRight);
50400  while( 1 ){
50401    rc = getAndInitPage(pBt, pgno, &apOld[i]);
50402    if( rc ){
50403      memset(apOld, 0, (i+1)*sizeof(MemPage*));
50404      goto balance_cleanup;
50405    }
50406    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
50407    if( (i--)==0 ) break;
50408
50409    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
50410      apDiv[i] = pParent->aOvfl[0].pCell;
50411      pgno = get4byte(apDiv[i]);
50412      szNew[i] = cellSizePtr(pParent, apDiv[i]);
50413      pParent->nOverflow = 0;
50414    }else{
50415      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
50416      pgno = get4byte(apDiv[i]);
50417      szNew[i] = cellSizePtr(pParent, apDiv[i]);
50418
50419      /* Drop the cell from the parent page. apDiv[i] still points to
50420      ** the cell within the parent, even though it has been dropped.
50421      ** This is safe because dropping a cell only overwrites the first
50422      ** four bytes of it, and this function does not need the first
50423      ** four bytes of the divider cell. So the pointer is safe to use
50424      ** later on.
50425      **
50426      ** Unless SQLite is compiled in secure-delete mode. In this case,
50427      ** the dropCell() routine will overwrite the entire cell with zeroes.
50428      ** In this case, temporarily copy the cell into the aOvflSpace[]
50429      ** buffer. It will be copied out again as soon as the aSpace[] buffer
50430      ** is allocated.  */
50431      if( pBt->secureDelete ){
50432        int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
50433        if( (iOff+szNew[i])>(int)pBt->usableSize ){
50434          rc = SQLITE_CORRUPT_BKPT;
50435          memset(apOld, 0, (i+1)*sizeof(MemPage*));
50436          goto balance_cleanup;
50437        }else{
50438          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
50439          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
50440        }
50441      }
50442      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
50443    }
50444  }
50445
50446  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
50447  ** alignment */
50448  nMaxCells = (nMaxCells + 3)&~3;
50449
50450  /*
50451  ** Allocate space for memory structures
50452  */
50453  k = pBt->pageSize + ROUND8(sizeof(MemPage));
50454  szScratch =
50455       nMaxCells*sizeof(u8*)                       /* apCell */
50456     + nMaxCells*sizeof(u16)                       /* szCell */
50457     + pBt->pageSize                               /* aSpace1 */
50458     + k*nOld;                                     /* Page copies (apCopy) */
50459  apCell = sqlite3ScratchMalloc( szScratch );
50460  if( apCell==0 ){
50461    rc = SQLITE_NOMEM;
50462    goto balance_cleanup;
50463  }
50464  szCell = (u16*)&apCell[nMaxCells];
50465  aSpace1 = (u8*)&szCell[nMaxCells];
50466  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
50467
50468  /*
50469  ** Load pointers to all cells on sibling pages and the divider cells
50470  ** into the local apCell[] array.  Make copies of the divider cells
50471  ** into space obtained from aSpace1[] and remove the the divider Cells
50472  ** from pParent.
50473  **
50474  ** If the siblings are on leaf pages, then the child pointers of the
50475  ** divider cells are stripped from the cells before they are copied
50476  ** into aSpace1[].  In this way, all cells in apCell[] are without
50477  ** child pointers.  If siblings are not leaves, then all cell in
50478  ** apCell[] include child pointers.  Either way, all cells in apCell[]
50479  ** are alike.
50480  **
50481  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
50482  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
50483  */
50484  leafCorrection = apOld[0]->leaf*4;
50485  leafData = apOld[0]->hasData;
50486  for(i=0; i<nOld; i++){
50487    int limit;
50488
50489    /* Before doing anything else, take a copy of the i'th original sibling
50490    ** The rest of this function will use data from the copies rather
50491    ** that the original pages since the original pages will be in the
50492    ** process of being overwritten.  */
50493    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
50494    memcpy(pOld, apOld[i], sizeof(MemPage));
50495    pOld->aData = (void*)&pOld[1];
50496    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
50497
50498    limit = pOld->nCell+pOld->nOverflow;
50499    for(j=0; j<limit; j++){
50500      assert( nCell<nMaxCells );
50501      apCell[nCell] = findOverflowCell(pOld, j);
50502      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
50503      nCell++;
50504    }
50505    if( i<nOld-1 && !leafData){
50506      u16 sz = (u16)szNew[i];
50507      u8 *pTemp;
50508      assert( nCell<nMaxCells );
50509      szCell[nCell] = sz;
50510      pTemp = &aSpace1[iSpace1];
50511      iSpace1 += sz;
50512      assert( sz<=pBt->maxLocal+23 );
50513      assert( iSpace1<=pBt->pageSize );
50514      memcpy(pTemp, apDiv[i], sz);
50515      apCell[nCell] = pTemp+leafCorrection;
50516      assert( leafCorrection==0 || leafCorrection==4 );
50517      szCell[nCell] = szCell[nCell] - leafCorrection;
50518      if( !pOld->leaf ){
50519        assert( leafCorrection==0 );
50520        assert( pOld->hdrOffset==0 );
50521        /* The right pointer of the child page pOld becomes the left
50522        ** pointer of the divider cell */
50523        memcpy(apCell[nCell], &pOld->aData[8], 4);
50524      }else{
50525        assert( leafCorrection==4 );
50526        if( szCell[nCell]<4 ){
50527          /* Do not allow any cells smaller than 4 bytes. */
50528          szCell[nCell] = 4;
50529        }
50530      }
50531      nCell++;
50532    }
50533  }
50534
50535  /*
50536  ** Figure out the number of pages needed to hold all nCell cells.
50537  ** Store this number in "k".  Also compute szNew[] which is the total
50538  ** size of all cells on the i-th page and cntNew[] which is the index
50539  ** in apCell[] of the cell that divides page i from page i+1.
50540  ** cntNew[k] should equal nCell.
50541  **
50542  ** Values computed by this block:
50543  **
50544  **           k: The total number of sibling pages
50545  **    szNew[i]: Spaced used on the i-th sibling page.
50546  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
50547  **              the right of the i-th sibling page.
50548  ** usableSpace: Number of bytes of space available on each sibling.
50549  **
50550  */
50551  usableSpace = pBt->usableSize - 12 + leafCorrection;
50552  for(subtotal=k=i=0; i<nCell; i++){
50553    assert( i<nMaxCells );
50554    subtotal += szCell[i] + 2;
50555    if( subtotal > usableSpace ){
50556      szNew[k] = subtotal - szCell[i];
50557      cntNew[k] = i;
50558      if( leafData ){ i--; }
50559      subtotal = 0;
50560      k++;
50561      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
50562    }
50563  }
50564  szNew[k] = subtotal;
50565  cntNew[k] = nCell;
50566  k++;
50567
50568  /*
50569  ** The packing computed by the previous block is biased toward the siblings
50570  ** on the left side.  The left siblings are always nearly full, while the
50571  ** right-most sibling might be nearly empty.  This block of code attempts
50572  ** to adjust the packing of siblings to get a better balance.
50573  **
50574  ** This adjustment is more than an optimization.  The packing above might
50575  ** be so out of balance as to be illegal.  For example, the right-most
50576  ** sibling might be completely empty.  This adjustment is not optional.
50577  */
50578  for(i=k-1; i>0; i--){
50579    int szRight = szNew[i];  /* Size of sibling on the right */
50580    int szLeft = szNew[i-1]; /* Size of sibling on the left */
50581    int r;              /* Index of right-most cell in left sibling */
50582    int d;              /* Index of first cell to the left of right sibling */
50583
50584    r = cntNew[i-1] - 1;
50585    d = r + 1 - leafData;
50586    assert( d<nMaxCells );
50587    assert( r<nMaxCells );
50588    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
50589      szRight += szCell[d] + 2;
50590      szLeft -= szCell[r] + 2;
50591      cntNew[i-1]--;
50592      r = cntNew[i-1] - 1;
50593      d = r + 1 - leafData;
50594    }
50595    szNew[i] = szRight;
50596    szNew[i-1] = szLeft;
50597  }
50598
50599  /* Either we found one or more cells (cntnew[0])>0) or pPage is
50600  ** a virtual root page.  A virtual root page is when the real root
50601  ** page is page 1 and we are the only child of that page.
50602  */
50603  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
50604
50605  TRACE(("BALANCE: old: %d %d %d  ",
50606    apOld[0]->pgno,
50607    nOld>=2 ? apOld[1]->pgno : 0,
50608    nOld>=3 ? apOld[2]->pgno : 0
50609  ));
50610
50611  /*
50612  ** Allocate k new pages.  Reuse old pages where possible.
50613  */
50614  if( apOld[0]->pgno<=1 ){
50615    rc = SQLITE_CORRUPT_BKPT;
50616    goto balance_cleanup;
50617  }
50618  pageFlags = apOld[0]->aData[0];
50619  for(i=0; i<k; i++){
50620    MemPage *pNew;
50621    if( i<nOld ){
50622      pNew = apNew[i] = apOld[i];
50623      apOld[i] = 0;
50624      rc = sqlite3PagerWrite(pNew->pDbPage);
50625      nNew++;
50626      if( rc ) goto balance_cleanup;
50627    }else{
50628      assert( i>0 );
50629      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
50630      if( rc ) goto balance_cleanup;
50631      apNew[i] = pNew;
50632      nNew++;
50633
50634      /* Set the pointer-map entry for the new sibling page. */
50635      if( ISAUTOVACUUM ){
50636        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
50637        if( rc!=SQLITE_OK ){
50638          goto balance_cleanup;
50639        }
50640      }
50641    }
50642  }
50643
50644  /* Free any old pages that were not reused as new pages.
50645  */
50646  while( i<nOld ){
50647    freePage(apOld[i], &rc);
50648    if( rc ) goto balance_cleanup;
50649    releasePage(apOld[i]);
50650    apOld[i] = 0;
50651    i++;
50652  }
50653
50654  /*
50655  ** Put the new pages in accending order.  This helps to
50656  ** keep entries in the disk file in order so that a scan
50657  ** of the table is a linear scan through the file.  That
50658  ** in turn helps the operating system to deliver pages
50659  ** from the disk more rapidly.
50660  **
50661  ** An O(n^2) insertion sort algorithm is used, but since
50662  ** n is never more than NB (a small constant), that should
50663  ** not be a problem.
50664  **
50665  ** When NB==3, this one optimization makes the database
50666  ** about 25% faster for large insertions and deletions.
50667  */
50668  for(i=0; i<k-1; i++){
50669    int minV = apNew[i]->pgno;
50670    int minI = i;
50671    for(j=i+1; j<k; j++){
50672      if( apNew[j]->pgno<(unsigned)minV ){
50673        minI = j;
50674        minV = apNew[j]->pgno;
50675      }
50676    }
50677    if( minI>i ){
50678      int t;
50679      MemPage *pT;
50680      t = apNew[i]->pgno;
50681      pT = apNew[i];
50682      apNew[i] = apNew[minI];
50683      apNew[minI] = pT;
50684    }
50685  }
50686  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
50687    apNew[0]->pgno, szNew[0],
50688    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
50689    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
50690    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
50691    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
50692
50693  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50694  put4byte(pRight, apNew[nNew-1]->pgno);
50695
50696  /*
50697  ** Evenly distribute the data in apCell[] across the new pages.
50698  ** Insert divider cells into pParent as necessary.
50699  */
50700  j = 0;
50701  for(i=0; i<nNew; i++){
50702    /* Assemble the new sibling page. */
50703    MemPage *pNew = apNew[i];
50704    assert( j<nMaxCells );
50705    zeroPage(pNew, pageFlags);
50706    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
50707    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
50708    assert( pNew->nOverflow==0 );
50709
50710    j = cntNew[i];
50711
50712    /* If the sibling page assembled above was not the right-most sibling,
50713    ** insert a divider cell into the parent page.
50714    */
50715    assert( i<nNew-1 || j==nCell );
50716    if( j<nCell ){
50717      u8 *pCell;
50718      u8 *pTemp;
50719      int sz;
50720
50721      assert( j<nMaxCells );
50722      pCell = apCell[j];
50723      sz = szCell[j] + leafCorrection;
50724      pTemp = &aOvflSpace[iOvflSpace];
50725      if( !pNew->leaf ){
50726        memcpy(&pNew->aData[8], pCell, 4);
50727      }else if( leafData ){
50728        /* If the tree is a leaf-data tree, and the siblings are leaves,
50729        ** then there is no divider cell in apCell[]. Instead, the divider
50730        ** cell consists of the integer key for the right-most cell of
50731        ** the sibling-page assembled above only.
50732        */
50733        CellInfo info;
50734        j--;
50735        btreeParseCellPtr(pNew, apCell[j], &info);
50736        pCell = pTemp;
50737        sz = 4 + putVarint(&pCell[4], info.nKey);
50738        pTemp = 0;
50739      }else{
50740        pCell -= 4;
50741        /* Obscure case for non-leaf-data trees: If the cell at pCell was
50742        ** previously stored on a leaf node, and its reported size was 4
50743        ** bytes, then it may actually be smaller than this
50744        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
50745        ** any cell). But it is important to pass the correct size to
50746        ** insertCell(), so reparse the cell now.
50747        **
50748        ** Note that this can never happen in an SQLite data file, as all
50749        ** cells are at least 4 bytes. It only happens in b-trees used
50750        ** to evaluate "IN (SELECT ...)" and similar clauses.
50751        */
50752        if( szCell[j]==4 ){
50753          assert(leafCorrection==4);
50754          sz = cellSizePtr(pParent, pCell);
50755        }
50756      }
50757      iOvflSpace += sz;
50758      assert( sz<=pBt->maxLocal+23 );
50759      assert( iOvflSpace<=pBt->pageSize );
50760      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
50761      if( rc!=SQLITE_OK ) goto balance_cleanup;
50762      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50763
50764      j++;
50765      nxDiv++;
50766    }
50767  }
50768  assert( j==nCell );
50769  assert( nOld>0 );
50770  assert( nNew>0 );
50771  if( (pageFlags & PTF_LEAF)==0 ){
50772    u8 *zChild = &apCopy[nOld-1]->aData[8];
50773    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
50774  }
50775
50776  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
50777    /* The root page of the b-tree now contains no cells. The only sibling
50778    ** page is the right-child of the parent. Copy the contents of the
50779    ** child page into the parent, decreasing the overall height of the
50780    ** b-tree structure by one. This is described as the "balance-shallower"
50781    ** sub-algorithm in some documentation.
50782    **
50783    ** If this is an auto-vacuum database, the call to copyNodeContent()
50784    ** sets all pointer-map entries corresponding to database image pages
50785    ** for which the pointer is stored within the content being copied.
50786    **
50787    ** The second assert below verifies that the child page is defragmented
50788    ** (it must be, as it was just reconstructed using assemblePage()). This
50789    ** is important if the parent page happens to be page 1 of the database
50790    ** image.  */
50791    assert( nNew==1 );
50792    assert( apNew[0]->nFree ==
50793        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
50794    );
50795    copyNodeContent(apNew[0], pParent, &rc);
50796    freePage(apNew[0], &rc);
50797  }else if( ISAUTOVACUUM ){
50798    /* Fix the pointer-map entries for all the cells that were shifted around.
50799    ** There are several different types of pointer-map entries that need to
50800    ** be dealt with by this routine. Some of these have been set already, but
50801    ** many have not. The following is a summary:
50802    **
50803    **   1) The entries associated with new sibling pages that were not
50804    **      siblings when this function was called. These have already
50805    **      been set. We don't need to worry about old siblings that were
50806    **      moved to the free-list - the freePage() code has taken care
50807    **      of those.
50808    **
50809    **   2) The pointer-map entries associated with the first overflow
50810    **      page in any overflow chains used by new divider cells. These
50811    **      have also already been taken care of by the insertCell() code.
50812    **
50813    **   3) If the sibling pages are not leaves, then the child pages of
50814    **      cells stored on the sibling pages may need to be updated.
50815    **
50816    **   4) If the sibling pages are not internal intkey nodes, then any
50817    **      overflow pages used by these cells may need to be updated
50818    **      (internal intkey nodes never contain pointers to overflow pages).
50819    **
50820    **   5) If the sibling pages are not leaves, then the pointer-map
50821    **      entries for the right-child pages of each sibling may need
50822    **      to be updated.
50823    **
50824    ** Cases 1 and 2 are dealt with above by other code. The next
50825    ** block deals with cases 3 and 4 and the one after that, case 5. Since
50826    ** setting a pointer map entry is a relatively expensive operation, this
50827    ** code only sets pointer map entries for child or overflow pages that have
50828    ** actually moved between pages.  */
50829    MemPage *pNew = apNew[0];
50830    MemPage *pOld = apCopy[0];
50831    int nOverflow = pOld->nOverflow;
50832    int iNextOld = pOld->nCell + nOverflow;
50833    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
50834    j = 0;                             /* Current 'old' sibling page */
50835    k = 0;                             /* Current 'new' sibling page */
50836    for(i=0; i<nCell; i++){
50837      int isDivider = 0;
50838      while( i==iNextOld ){
50839        /* Cell i is the cell immediately following the last cell on old
50840        ** sibling page j. If the siblings are not leaf pages of an
50841        ** intkey b-tree, then cell i was a divider cell. */
50842        pOld = apCopy[++j];
50843        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
50844        if( pOld->nOverflow ){
50845          nOverflow = pOld->nOverflow;
50846          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
50847        }
50848        isDivider = !leafData;
50849      }
50850
50851      assert(nOverflow>0 || iOverflow<i );
50852      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
50853      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
50854      if( i==iOverflow ){
50855        isDivider = 1;
50856        if( (--nOverflow)>0 ){
50857          iOverflow++;
50858        }
50859      }
50860
50861      if( i==cntNew[k] ){
50862        /* Cell i is the cell immediately following the last cell on new
50863        ** sibling page k. If the siblings are not leaf pages of an
50864        ** intkey b-tree, then cell i is a divider cell.  */
50865        pNew = apNew[++k];
50866        if( !leafData ) continue;
50867      }
50868      assert( j<nOld );
50869      assert( k<nNew );
50870
50871      /* If the cell was originally divider cell (and is not now) or
50872      ** an overflow cell, or if the cell was located on a different sibling
50873      ** page before the balancing, then the pointer map entries associated
50874      ** with any child or overflow pages need to be updated.  */
50875      if( isDivider || pOld->pgno!=pNew->pgno ){
50876        if( !leafCorrection ){
50877          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
50878        }
50879        if( szCell[i]>pNew->minLocal ){
50880          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
50881        }
50882      }
50883    }
50884
50885    if( !leafCorrection ){
50886      for(i=0; i<nNew; i++){
50887        u32 key = get4byte(&apNew[i]->aData[8]);
50888        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
50889      }
50890    }
50891
50892#if 0
50893    /* The ptrmapCheckPages() contains assert() statements that verify that
50894    ** all pointer map pages are set correctly. This is helpful while
50895    ** debugging. This is usually disabled because a corrupt database may
50896    ** cause an assert() statement to fail.  */
50897    ptrmapCheckPages(apNew, nNew);
50898    ptrmapCheckPages(&pParent, 1);
50899#endif
50900  }
50901
50902  assert( pParent->isInit );
50903  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
50904          nOld, nNew, nCell));
50905
50906  /*
50907  ** Cleanup before returning.
50908  */
50909balance_cleanup:
50910  sqlite3ScratchFree(apCell);
50911  for(i=0; i<nOld; i++){
50912    releasePage(apOld[i]);
50913  }
50914  for(i=0; i<nNew; i++){
50915    releasePage(apNew[i]);
50916  }
50917
50918  return rc;
50919}
50920
50921
50922/*
50923** This function is called when the root page of a b-tree structure is
50924** overfull (has one or more overflow pages).
50925**
50926** A new child page is allocated and the contents of the current root
50927** page, including overflow cells, are copied into the child. The root
50928** page is then overwritten to make it an empty page with the right-child
50929** pointer pointing to the new page.
50930**
50931** Before returning, all pointer-map entries corresponding to pages
50932** that the new child-page now contains pointers to are updated. The
50933** entry corresponding to the new right-child pointer of the root
50934** page is also updated.
50935**
50936** If successful, *ppChild is set to contain a reference to the child
50937** page and SQLITE_OK is returned. In this case the caller is required
50938** to call releasePage() on *ppChild exactly once. If an error occurs,
50939** an error code is returned and *ppChild is set to 0.
50940*/
50941static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
50942  int rc;                        /* Return value from subprocedures */
50943  MemPage *pChild = 0;           /* Pointer to a new child page */
50944  Pgno pgnoChild = 0;            /* Page number of the new child page */
50945  BtShared *pBt = pRoot->pBt;    /* The BTree */
50946
50947  assert( pRoot->nOverflow>0 );
50948  assert( sqlite3_mutex_held(pBt->mutex) );
50949
50950  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
50951  ** page that will become the new right-child of pPage. Copy the contents
50952  ** of the node stored on pRoot into the new child page.
50953  */
50954  rc = sqlite3PagerWrite(pRoot->pDbPage);
50955  if( rc==SQLITE_OK ){
50956    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
50957    copyNodeContent(pRoot, pChild, &rc);
50958    if( ISAUTOVACUUM ){
50959      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
50960    }
50961  }
50962  if( rc ){
50963    *ppChild = 0;
50964    releasePage(pChild);
50965    return rc;
50966  }
50967  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
50968  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
50969  assert( pChild->nCell==pRoot->nCell );
50970
50971  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
50972
50973  /* Copy the overflow cells from pRoot to pChild */
50974  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
50975  pChild->nOverflow = pRoot->nOverflow;
50976
50977  /* Zero the contents of pRoot. Then install pChild as the right-child. */
50978  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
50979  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
50980
50981  *ppChild = pChild;
50982  return SQLITE_OK;
50983}
50984
50985/*
50986** The page that pCur currently points to has just been modified in
50987** some way. This function figures out if this modification means the
50988** tree needs to be balanced, and if so calls the appropriate balancing
50989** routine. Balancing routines are:
50990**
50991**   balance_quick()
50992**   balance_deeper()
50993**   balance_nonroot()
50994*/
50995static int balance(BtCursor *pCur){
50996  int rc = SQLITE_OK;
50997  const int nMin = pCur->pBt->usableSize * 2 / 3;
50998  u8 aBalanceQuickSpace[13];
50999  u8 *pFree = 0;
51000
51001  TESTONLY( int balance_quick_called = 0 );
51002  TESTONLY( int balance_deeper_called = 0 );
51003
51004  do {
51005    int iPage = pCur->iPage;
51006    MemPage *pPage = pCur->apPage[iPage];
51007
51008    if( iPage==0 ){
51009      if( pPage->nOverflow ){
51010        /* The root page of the b-tree is overfull. In this case call the
51011        ** balance_deeper() function to create a new child for the root-page
51012        ** and copy the current contents of the root-page to it. The
51013        ** next iteration of the do-loop will balance the child page.
51014        */
51015        assert( (balance_deeper_called++)==0 );
51016        rc = balance_deeper(pPage, &pCur->apPage[1]);
51017        if( rc==SQLITE_OK ){
51018          pCur->iPage = 1;
51019          pCur->aiIdx[0] = 0;
51020          pCur->aiIdx[1] = 0;
51021          assert( pCur->apPage[1]->nOverflow );
51022        }
51023      }else{
51024        break;
51025      }
51026    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
51027      break;
51028    }else{
51029      MemPage * const pParent = pCur->apPage[iPage-1];
51030      int const iIdx = pCur->aiIdx[iPage-1];
51031
51032      rc = sqlite3PagerWrite(pParent->pDbPage);
51033      if( rc==SQLITE_OK ){
51034#ifndef SQLITE_OMIT_QUICKBALANCE
51035        if( pPage->hasData
51036         && pPage->nOverflow==1
51037         && pPage->aOvfl[0].idx==pPage->nCell
51038         && pParent->pgno!=1
51039         && pParent->nCell==iIdx
51040        ){
51041          /* Call balance_quick() to create a new sibling of pPage on which
51042          ** to store the overflow cell. balance_quick() inserts a new cell
51043          ** into pParent, which may cause pParent overflow. If this
51044          ** happens, the next interation of the do-loop will balance pParent
51045          ** use either balance_nonroot() or balance_deeper(). Until this
51046          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
51047          ** buffer.
51048          **
51049          ** The purpose of the following assert() is to check that only a
51050          ** single call to balance_quick() is made for each call to this
51051          ** function. If this were not verified, a subtle bug involving reuse
51052          ** of the aBalanceQuickSpace[] might sneak in.
51053          */
51054          assert( (balance_quick_called++)==0 );
51055          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
51056        }else
51057#endif
51058        {
51059          /* In this case, call balance_nonroot() to redistribute cells
51060          ** between pPage and up to 2 of its sibling pages. This involves
51061          ** modifying the contents of pParent, which may cause pParent to
51062          ** become overfull or underfull. The next iteration of the do-loop
51063          ** will balance the parent page to correct this.
51064          **
51065          ** If the parent page becomes overfull, the overflow cell or cells
51066          ** are stored in the pSpace buffer allocated immediately below.
51067          ** A subsequent iteration of the do-loop will deal with this by
51068          ** calling balance_nonroot() (balance_deeper() may be called first,
51069          ** but it doesn't deal with overflow cells - just moves them to a
51070          ** different page). Once this subsequent call to balance_nonroot()
51071          ** has completed, it is safe to release the pSpace buffer used by
51072          ** the previous call, as the overflow cell data will have been
51073          ** copied either into the body of a database page or into the new
51074          ** pSpace buffer passed to the latter call to balance_nonroot().
51075          */
51076          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
51077          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
51078          if( pFree ){
51079            /* If pFree is not NULL, it points to the pSpace buffer used
51080            ** by a previous call to balance_nonroot(). Its contents are
51081            ** now stored either on real database pages or within the
51082            ** new pSpace buffer, so it may be safely freed here. */
51083            sqlite3PageFree(pFree);
51084          }
51085
51086          /* The pSpace buffer will be freed after the next call to
51087          ** balance_nonroot(), or just before this function returns, whichever
51088          ** comes first. */
51089          pFree = pSpace;
51090        }
51091      }
51092
51093      pPage->nOverflow = 0;
51094
51095      /* The next iteration of the do-loop balances the parent page. */
51096      releasePage(pPage);
51097      pCur->iPage--;
51098    }
51099  }while( rc==SQLITE_OK );
51100
51101  if( pFree ){
51102    sqlite3PageFree(pFree);
51103  }
51104  return rc;
51105}
51106
51107
51108/*
51109** Insert a new record into the BTree.  The key is given by (pKey,nKey)
51110** and the data is given by (pData,nData).  The cursor is used only to
51111** define what table the record should be inserted into.  The cursor
51112** is left pointing at a random location.
51113**
51114** For an INTKEY table, only the nKey value of the key is used.  pKey is
51115** ignored.  For a ZERODATA table, the pData and nData are both ignored.
51116**
51117** If the seekResult parameter is non-zero, then a successful call to
51118** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
51119** been performed. seekResult is the search result returned (a negative
51120** number if pCur points at an entry that is smaller than (pKey, nKey), or
51121** a positive value if pCur points at an etry that is larger than
51122** (pKey, nKey)).
51123**
51124** If the seekResult parameter is non-zero, then the caller guarantees that
51125** cursor pCur is pointing at the existing copy of a row that is to be
51126** overwritten.  If the seekResult parameter is 0, then cursor pCur may
51127** point to any entry or to no entry at all and so this function has to seek
51128** the cursor before the new key can be inserted.
51129*/
51130SQLITE_PRIVATE int sqlite3BtreeInsert(
51131  BtCursor *pCur,                /* Insert data into the table of this cursor */
51132  const void *pKey, i64 nKey,    /* The key of the new record */
51133  const void *pData, int nData,  /* The data of the new record */
51134  int nZero,                     /* Number of extra 0 bytes to append to data */
51135  int appendBias,                /* True if this is likely an append */
51136  int seekResult                 /* Result of prior MovetoUnpacked() call */
51137){
51138  int rc;
51139  int loc = seekResult;          /* -1: before desired location  +1: after */
51140  int szNew = 0;
51141  int idx;
51142  MemPage *pPage;
51143  Btree *p = pCur->pBtree;
51144  BtShared *pBt = p->pBt;
51145  unsigned char *oldCell;
51146  unsigned char *newCell = 0;
51147
51148  if( pCur->eState==CURSOR_FAULT ){
51149    assert( pCur->skipNext!=SQLITE_OK );
51150    return pCur->skipNext;
51151  }
51152
51153  assert( cursorHoldsMutex(pCur) );
51154  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
51155  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
51156
51157  /* Assert that the caller has been consistent. If this cursor was opened
51158  ** expecting an index b-tree, then the caller should be inserting blob
51159  ** keys with no associated data. If the cursor was opened expecting an
51160  ** intkey table, the caller should be inserting integer keys with a
51161  ** blob of associated data.  */
51162  assert( (pKey==0)==(pCur->pKeyInfo==0) );
51163
51164  /* If this is an insert into a table b-tree, invalidate any incrblob
51165  ** cursors open on the row being replaced (assuming this is a replace
51166  ** operation - if it is not, the following is a no-op).  */
51167  if( pCur->pKeyInfo==0 ){
51168    invalidateIncrblobCursors(p, nKey, 0);
51169  }
51170
51171  /* Save the positions of any other cursors open on this table.
51172  **
51173  ** In some cases, the call to btreeMoveto() below is a no-op. For
51174  ** example, when inserting data into a table with auto-generated integer
51175  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
51176  ** integer key to use. It then calls this function to actually insert the
51177  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
51178  ** that the cursor is already where it needs to be and returns without
51179  ** doing any work. To avoid thwarting these optimizations, it is important
51180  ** not to clear the cursor here.
51181  */
51182  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
51183  if( rc ) return rc;
51184  if( !loc ){
51185    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
51186    if( rc ) return rc;
51187  }
51188  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
51189
51190  pPage = pCur->apPage[pCur->iPage];
51191  assert( pPage->intKey || nKey>=0 );
51192  assert( pPage->leaf || !pPage->intKey );
51193
51194  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
51195          pCur->pgnoRoot, nKey, nData, pPage->pgno,
51196          loc==0 ? "overwrite" : "new entry"));
51197  assert( pPage->isInit );
51198  allocateTempSpace(pBt);
51199  newCell = pBt->pTmpSpace;
51200  if( newCell==0 ) return SQLITE_NOMEM;
51201  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
51202  if( rc ) goto end_insert;
51203  assert( szNew==cellSizePtr(pPage, newCell) );
51204  assert( szNew<=MX_CELL_SIZE(pBt) );
51205  idx = pCur->aiIdx[pCur->iPage];
51206  if( loc==0 ){
51207    u16 szOld;
51208    assert( idx<pPage->nCell );
51209    rc = sqlite3PagerWrite(pPage->pDbPage);
51210    if( rc ){
51211      goto end_insert;
51212    }
51213    oldCell = findCell(pPage, idx);
51214    if( !pPage->leaf ){
51215      memcpy(newCell, oldCell, 4);
51216    }
51217    szOld = cellSizePtr(pPage, oldCell);
51218    rc = clearCell(pPage, oldCell);
51219    dropCell(pPage, idx, szOld, &rc);
51220    if( rc ) goto end_insert;
51221  }else if( loc<0 && pPage->nCell>0 ){
51222    assert( pPage->leaf );
51223    idx = ++pCur->aiIdx[pCur->iPage];
51224  }else{
51225    assert( pPage->leaf );
51226  }
51227  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
51228  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
51229
51230  /* If no error has occured and pPage has an overflow cell, call balance()
51231  ** to redistribute the cells within the tree. Since balance() may move
51232  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
51233  ** variables.
51234  **
51235  ** Previous versions of SQLite called moveToRoot() to move the cursor
51236  ** back to the root page as balance() used to invalidate the contents
51237  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
51238  ** set the cursor state to "invalid". This makes common insert operations
51239  ** slightly faster.
51240  **
51241  ** There is a subtle but important optimization here too. When inserting
51242  ** multiple records into an intkey b-tree using a single cursor (as can
51243  ** happen while processing an "INSERT INTO ... SELECT" statement), it
51244  ** is advantageous to leave the cursor pointing to the last entry in
51245  ** the b-tree if possible. If the cursor is left pointing to the last
51246  ** entry in the table, and the next row inserted has an integer key
51247  ** larger than the largest existing key, it is possible to insert the
51248  ** row without seeking the cursor. This can be a big performance boost.
51249  */
51250  pCur->info.nSize = 0;
51251  pCur->validNKey = 0;
51252  if( rc==SQLITE_OK && pPage->nOverflow ){
51253    rc = balance(pCur);
51254
51255    /* Must make sure nOverflow is reset to zero even if the balance()
51256    ** fails. Internal data structure corruption will result otherwise.
51257    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
51258    ** from trying to save the current position of the cursor.  */
51259    pCur->apPage[pCur->iPage]->nOverflow = 0;
51260    pCur->eState = CURSOR_INVALID;
51261  }
51262  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
51263
51264end_insert:
51265  return rc;
51266}
51267
51268/*
51269** Delete the entry that the cursor is pointing to.  The cursor
51270** is left pointing at a arbitrary location.
51271*/
51272SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
51273  Btree *p = pCur->pBtree;
51274  BtShared *pBt = p->pBt;
51275  int rc;                              /* Return code */
51276  MemPage *pPage;                      /* Page to delete cell from */
51277  unsigned char *pCell;                /* Pointer to cell to delete */
51278  int iCellIdx;                        /* Index of cell to delete */
51279  int iCellDepth;                      /* Depth of node containing pCell */
51280
51281  assert( cursorHoldsMutex(pCur) );
51282  assert( pBt->inTransaction==TRANS_WRITE );
51283  assert( !pBt->readOnly );
51284  assert( pCur->wrFlag );
51285  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
51286  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
51287
51288  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
51289   || NEVER(pCur->eState!=CURSOR_VALID)
51290  ){
51291    return SQLITE_ERROR;  /* Something has gone awry. */
51292  }
51293
51294  /* If this is a delete operation to remove a row from a table b-tree,
51295  ** invalidate any incrblob cursors open on the row being deleted.  */
51296  if( pCur->pKeyInfo==0 ){
51297    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
51298  }
51299
51300  iCellDepth = pCur->iPage;
51301  iCellIdx = pCur->aiIdx[iCellDepth];
51302  pPage = pCur->apPage[iCellDepth];
51303  pCell = findCell(pPage, iCellIdx);
51304
51305  /* If the page containing the entry to delete is not a leaf page, move
51306  ** the cursor to the largest entry in the tree that is smaller than
51307  ** the entry being deleted. This cell will replace the cell being deleted
51308  ** from the internal node. The 'previous' entry is used for this instead
51309  ** of the 'next' entry, as the previous entry is always a part of the
51310  ** sub-tree headed by the child page of the cell being deleted. This makes
51311  ** balancing the tree following the delete operation easier.  */
51312  if( !pPage->leaf ){
51313    int notUsed;
51314    rc = sqlite3BtreePrevious(pCur, &notUsed);
51315    if( rc ) return rc;
51316  }
51317
51318  /* Save the positions of any other cursors open on this table before
51319  ** making any modifications. Make the page containing the entry to be
51320  ** deleted writable. Then free any overflow pages associated with the
51321  ** entry and finally remove the cell itself from within the page.
51322  */
51323  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
51324  if( rc ) return rc;
51325  rc = sqlite3PagerWrite(pPage->pDbPage);
51326  if( rc ) return rc;
51327  rc = clearCell(pPage, pCell);
51328  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
51329  if( rc ) return rc;
51330
51331  /* If the cell deleted was not located on a leaf page, then the cursor
51332  ** is currently pointing to the largest entry in the sub-tree headed
51333  ** by the child-page of the cell that was just deleted from an internal
51334  ** node. The cell from the leaf node needs to be moved to the internal
51335  ** node to replace the deleted cell.  */
51336  if( !pPage->leaf ){
51337    MemPage *pLeaf = pCur->apPage[pCur->iPage];
51338    int nCell;
51339    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
51340    unsigned char *pTmp;
51341
51342    pCell = findCell(pLeaf, pLeaf->nCell-1);
51343    nCell = cellSizePtr(pLeaf, pCell);
51344    assert( MX_CELL_SIZE(pBt)>=nCell );
51345
51346    allocateTempSpace(pBt);
51347    pTmp = pBt->pTmpSpace;
51348
51349    rc = sqlite3PagerWrite(pLeaf->pDbPage);
51350    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
51351    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
51352    if( rc ) return rc;
51353  }
51354
51355  /* Balance the tree. If the entry deleted was located on a leaf page,
51356  ** then the cursor still points to that page. In this case the first
51357  ** call to balance() repairs the tree, and the if(...) condition is
51358  ** never true.
51359  **
51360  ** Otherwise, if the entry deleted was on an internal node page, then
51361  ** pCur is pointing to the leaf page from which a cell was removed to
51362  ** replace the cell deleted from the internal node. This is slightly
51363  ** tricky as the leaf node may be underfull, and the internal node may
51364  ** be either under or overfull. In this case run the balancing algorithm
51365  ** on the leaf node first. If the balance proceeds far enough up the
51366  ** tree that we can be sure that any problem in the internal node has
51367  ** been corrected, so be it. Otherwise, after balancing the leaf node,
51368  ** walk the cursor up the tree to the internal node and balance it as
51369  ** well.  */
51370  rc = balance(pCur);
51371  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
51372    while( pCur->iPage>iCellDepth ){
51373      releasePage(pCur->apPage[pCur->iPage--]);
51374    }
51375    rc = balance(pCur);
51376  }
51377
51378  if( rc==SQLITE_OK ){
51379    moveToRoot(pCur);
51380  }
51381  return rc;
51382}
51383
51384/*
51385** Create a new BTree table.  Write into *piTable the page
51386** number for the root page of the new table.
51387**
51388** The type of type is determined by the flags parameter.  Only the
51389** following values of flags are currently in use.  Other values for
51390** flags might not work:
51391**
51392**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
51393**     BTREE_ZERODATA                  Used for SQL indices
51394*/
51395static int btreeCreateTable(Btree *p, int *piTable, int flags){
51396  BtShared *pBt = p->pBt;
51397  MemPage *pRoot;
51398  Pgno pgnoRoot;
51399  int rc;
51400
51401  assert( sqlite3BtreeHoldsMutex(p) );
51402  assert( pBt->inTransaction==TRANS_WRITE );
51403  assert( !pBt->readOnly );
51404
51405#ifdef SQLITE_OMIT_AUTOVACUUM
51406  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
51407  if( rc ){
51408    return rc;
51409  }
51410#else
51411  if( pBt->autoVacuum ){
51412    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
51413    MemPage *pPageMove; /* The page to move to. */
51414
51415    /* Creating a new table may probably require moving an existing database
51416    ** to make room for the new tables root page. In case this page turns
51417    ** out to be an overflow page, delete all overflow page-map caches
51418    ** held by open cursors.
51419    */
51420    invalidateAllOverflowCache(pBt);
51421
51422    /* Read the value of meta[3] from the database to determine where the
51423    ** root page of the new table should go. meta[3] is the largest root-page
51424    ** created so far, so the new root-page is (meta[3]+1).
51425    */
51426    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
51427    pgnoRoot++;
51428
51429    /* The new root-page may not be allocated on a pointer-map page, or the
51430    ** PENDING_BYTE page.
51431    */
51432    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
51433        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
51434      pgnoRoot++;
51435    }
51436    assert( pgnoRoot>=3 );
51437
51438    /* Allocate a page. The page that currently resides at pgnoRoot will
51439    ** be moved to the allocated page (unless the allocated page happens
51440    ** to reside at pgnoRoot).
51441    */
51442    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
51443    if( rc!=SQLITE_OK ){
51444      return rc;
51445    }
51446
51447    if( pgnoMove!=pgnoRoot ){
51448      /* pgnoRoot is the page that will be used for the root-page of
51449      ** the new table (assuming an error did not occur). But we were
51450      ** allocated pgnoMove. If required (i.e. if it was not allocated
51451      ** by extending the file), the current page at position pgnoMove
51452      ** is already journaled.
51453      */
51454      u8 eType = 0;
51455      Pgno iPtrPage = 0;
51456
51457      releasePage(pPageMove);
51458
51459      /* Move the page currently at pgnoRoot to pgnoMove. */
51460      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
51461      if( rc!=SQLITE_OK ){
51462        return rc;
51463      }
51464      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
51465      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
51466        rc = SQLITE_CORRUPT_BKPT;
51467      }
51468      if( rc!=SQLITE_OK ){
51469        releasePage(pRoot);
51470        return rc;
51471      }
51472      assert( eType!=PTRMAP_ROOTPAGE );
51473      assert( eType!=PTRMAP_FREEPAGE );
51474      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
51475      releasePage(pRoot);
51476
51477      /* Obtain the page at pgnoRoot */
51478      if( rc!=SQLITE_OK ){
51479        return rc;
51480      }
51481      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
51482      if( rc!=SQLITE_OK ){
51483        return rc;
51484      }
51485      rc = sqlite3PagerWrite(pRoot->pDbPage);
51486      if( rc!=SQLITE_OK ){
51487        releasePage(pRoot);
51488        return rc;
51489      }
51490    }else{
51491      pRoot = pPageMove;
51492    }
51493
51494    /* Update the pointer-map and meta-data with the new root-page number. */
51495    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
51496    if( rc ){
51497      releasePage(pRoot);
51498      return rc;
51499    }
51500
51501    /* When the new root page was allocated, page 1 was made writable in
51502    ** order either to increase the database filesize, or to decrement the
51503    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
51504    */
51505    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
51506    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
51507    if( NEVER(rc) ){
51508      releasePage(pRoot);
51509      return rc;
51510    }
51511
51512  }else{
51513    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
51514    if( rc ) return rc;
51515  }
51516#endif
51517  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51518  zeroPage(pRoot, flags | PTF_LEAF);
51519  sqlite3PagerUnref(pRoot->pDbPage);
51520  *piTable = (int)pgnoRoot;
51521  return SQLITE_OK;
51522}
51523SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
51524  int rc;
51525  sqlite3BtreeEnter(p);
51526  rc = btreeCreateTable(p, piTable, flags);
51527  sqlite3BtreeLeave(p);
51528  return rc;
51529}
51530
51531/*
51532** Erase the given database page and all its children.  Return
51533** the page to the freelist.
51534*/
51535static int clearDatabasePage(
51536  BtShared *pBt,           /* The BTree that contains the table */
51537  Pgno pgno,               /* Page number to clear */
51538  int freePageFlag,        /* Deallocate page if true */
51539  int *pnChange            /* Add number of Cells freed to this counter */
51540){
51541  MemPage *pPage;
51542  int rc;
51543  unsigned char *pCell;
51544  int i;
51545
51546  assert( sqlite3_mutex_held(pBt->mutex) );
51547  if( pgno>btreePagecount(pBt) ){
51548    return SQLITE_CORRUPT_BKPT;
51549  }
51550
51551  rc = getAndInitPage(pBt, pgno, &pPage);
51552  if( rc ) return rc;
51553  for(i=0; i<pPage->nCell; i++){
51554    pCell = findCell(pPage, i);
51555    if( !pPage->leaf ){
51556      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
51557      if( rc ) goto cleardatabasepage_out;
51558    }
51559    rc = clearCell(pPage, pCell);
51560    if( rc ) goto cleardatabasepage_out;
51561  }
51562  if( !pPage->leaf ){
51563    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
51564    if( rc ) goto cleardatabasepage_out;
51565  }else if( pnChange ){
51566    assert( pPage->intKey );
51567    *pnChange += pPage->nCell;
51568  }
51569  if( freePageFlag ){
51570    freePage(pPage, &rc);
51571  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
51572    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
51573  }
51574
51575cleardatabasepage_out:
51576  releasePage(pPage);
51577  return rc;
51578}
51579
51580/*
51581** Delete all information from a single table in the database.  iTable is
51582** the page number of the root of the table.  After this routine returns,
51583** the root page is empty, but still exists.
51584**
51585** This routine will fail with SQLITE_LOCKED if there are any open
51586** read cursors on the table.  Open write cursors are moved to the
51587** root of the table.
51588**
51589** If pnChange is not NULL, then table iTable must be an intkey table. The
51590** integer value pointed to by pnChange is incremented by the number of
51591** entries in the table.
51592*/
51593SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
51594  int rc;
51595  BtShared *pBt = p->pBt;
51596  sqlite3BtreeEnter(p);
51597  assert( p->inTrans==TRANS_WRITE );
51598
51599  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
51600  ** is the root of a table b-tree - if it is not, the following call is
51601  ** a no-op).  */
51602  invalidateIncrblobCursors(p, 0, 1);
51603
51604  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
51605  if( SQLITE_OK==rc ){
51606    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
51607  }
51608  sqlite3BtreeLeave(p);
51609  return rc;
51610}
51611
51612/*
51613** Erase all information in a table and add the root of the table to
51614** the freelist.  Except, the root of the principle table (the one on
51615** page 1) is never added to the freelist.
51616**
51617** This routine will fail with SQLITE_LOCKED if there are any open
51618** cursors on the table.
51619**
51620** If AUTOVACUUM is enabled and the page at iTable is not the last
51621** root page in the database file, then the last root page
51622** in the database file is moved into the slot formerly occupied by
51623** iTable and that last slot formerly occupied by the last root page
51624** is added to the freelist instead of iTable.  In this say, all
51625** root pages are kept at the beginning of the database file, which
51626** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
51627** page number that used to be the last root page in the file before
51628** the move.  If no page gets moved, *piMoved is set to 0.
51629** The last root page is recorded in meta[3] and the value of
51630** meta[3] is updated by this procedure.
51631*/
51632static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
51633  int rc;
51634  MemPage *pPage = 0;
51635  BtShared *pBt = p->pBt;
51636
51637  assert( sqlite3BtreeHoldsMutex(p) );
51638  assert( p->inTrans==TRANS_WRITE );
51639
51640  /* It is illegal to drop a table if any cursors are open on the
51641  ** database. This is because in auto-vacuum mode the backend may
51642  ** need to move another root-page to fill a gap left by the deleted
51643  ** root page. If an open cursor was using this page a problem would
51644  ** occur.
51645  **
51646  ** This error is caught long before control reaches this point.
51647  */
51648  if( NEVER(pBt->pCursor) ){
51649    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
51650    return SQLITE_LOCKED_SHAREDCACHE;
51651  }
51652
51653  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
51654  if( rc ) return rc;
51655  rc = sqlite3BtreeClearTable(p, iTable, 0);
51656  if( rc ){
51657    releasePage(pPage);
51658    return rc;
51659  }
51660
51661  *piMoved = 0;
51662
51663  if( iTable>1 ){
51664#ifdef SQLITE_OMIT_AUTOVACUUM
51665    freePage(pPage, &rc);
51666    releasePage(pPage);
51667#else
51668    if( pBt->autoVacuum ){
51669      Pgno maxRootPgno;
51670      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
51671
51672      if( iTable==maxRootPgno ){
51673        /* If the table being dropped is the table with the largest root-page
51674        ** number in the database, put the root page on the free list.
51675        */
51676        freePage(pPage, &rc);
51677        releasePage(pPage);
51678        if( rc!=SQLITE_OK ){
51679          return rc;
51680        }
51681      }else{
51682        /* The table being dropped does not have the largest root-page
51683        ** number in the database. So move the page that does into the
51684        ** gap left by the deleted root-page.
51685        */
51686        MemPage *pMove;
51687        releasePage(pPage);
51688        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
51689        if( rc!=SQLITE_OK ){
51690          return rc;
51691        }
51692        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
51693        releasePage(pMove);
51694        if( rc!=SQLITE_OK ){
51695          return rc;
51696        }
51697        pMove = 0;
51698        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
51699        freePage(pMove, &rc);
51700        releasePage(pMove);
51701        if( rc!=SQLITE_OK ){
51702          return rc;
51703        }
51704        *piMoved = maxRootPgno;
51705      }
51706
51707      /* Set the new 'max-root-page' value in the database header. This
51708      ** is the old value less one, less one more if that happens to
51709      ** be a root-page number, less one again if that is the
51710      ** PENDING_BYTE_PAGE.
51711      */
51712      maxRootPgno--;
51713      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
51714             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
51715        maxRootPgno--;
51716      }
51717      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
51718
51719      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
51720    }else{
51721      freePage(pPage, &rc);
51722      releasePage(pPage);
51723    }
51724#endif
51725  }else{
51726    /* If sqlite3BtreeDropTable was called on page 1.
51727    ** This really never should happen except in a corrupt
51728    ** database.
51729    */
51730    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
51731    releasePage(pPage);
51732  }
51733  return rc;
51734}
51735SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
51736  int rc;
51737  sqlite3BtreeEnter(p);
51738  rc = btreeDropTable(p, iTable, piMoved);
51739  sqlite3BtreeLeave(p);
51740  return rc;
51741}
51742
51743
51744/*
51745** This function may only be called if the b-tree connection already
51746** has a read or write transaction open on the database.
51747**
51748** Read the meta-information out of a database file.  Meta[0]
51749** is the number of free pages currently in the database.  Meta[1]
51750** through meta[15] are available for use by higher layers.  Meta[0]
51751** is read-only, the others are read/write.
51752**
51753** The schema layer numbers meta values differently.  At the schema
51754** layer (and the SetCookie and ReadCookie opcodes) the number of
51755** free pages is not visible.  So Cookie[0] is the same as Meta[1].
51756*/
51757SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
51758  BtShared *pBt = p->pBt;
51759
51760  sqlite3BtreeEnter(p);
51761  assert( p->inTrans>TRANS_NONE );
51762  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
51763  assert( pBt->pPage1 );
51764  assert( idx>=0 && idx<=15 );
51765
51766  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
51767
51768  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
51769  ** database, mark the database as read-only.  */
51770#ifdef SQLITE_OMIT_AUTOVACUUM
51771  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
51772#endif
51773
51774  sqlite3BtreeLeave(p);
51775}
51776
51777/*
51778** Write meta-information back into the database.  Meta[0] is
51779** read-only and may not be written.
51780*/
51781SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
51782  BtShared *pBt = p->pBt;
51783  unsigned char *pP1;
51784  int rc;
51785  assert( idx>=1 && idx<=15 );
51786  sqlite3BtreeEnter(p);
51787  assert( p->inTrans==TRANS_WRITE );
51788  assert( pBt->pPage1!=0 );
51789  pP1 = pBt->pPage1->aData;
51790  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51791  if( rc==SQLITE_OK ){
51792    put4byte(&pP1[36 + idx*4], iMeta);
51793#ifndef SQLITE_OMIT_AUTOVACUUM
51794    if( idx==BTREE_INCR_VACUUM ){
51795      assert( pBt->autoVacuum || iMeta==0 );
51796      assert( iMeta==0 || iMeta==1 );
51797      pBt->incrVacuum = (u8)iMeta;
51798    }
51799#endif
51800  }
51801  sqlite3BtreeLeave(p);
51802  return rc;
51803}
51804
51805#ifndef SQLITE_OMIT_BTREECOUNT
51806/*
51807** The first argument, pCur, is a cursor opened on some b-tree. Count the
51808** number of entries in the b-tree and write the result to *pnEntry.
51809**
51810** SQLITE_OK is returned if the operation is successfully executed.
51811** Otherwise, if an error is encountered (i.e. an IO error or database
51812** corruption) an SQLite error code is returned.
51813*/
51814SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
51815  i64 nEntry = 0;                      /* Value to return in *pnEntry */
51816  int rc;                              /* Return code */
51817  rc = moveToRoot(pCur);
51818
51819  /* Unless an error occurs, the following loop runs one iteration for each
51820  ** page in the B-Tree structure (not including overflow pages).
51821  */
51822  while( rc==SQLITE_OK ){
51823    int iIdx;                          /* Index of child node in parent */
51824    MemPage *pPage;                    /* Current page of the b-tree */
51825
51826    /* If this is a leaf page or the tree is not an int-key tree, then
51827    ** this page contains countable entries. Increment the entry counter
51828    ** accordingly.
51829    */
51830    pPage = pCur->apPage[pCur->iPage];
51831    if( pPage->leaf || !pPage->intKey ){
51832      nEntry += pPage->nCell;
51833    }
51834
51835    /* pPage is a leaf node. This loop navigates the cursor so that it
51836    ** points to the first interior cell that it points to the parent of
51837    ** the next page in the tree that has not yet been visited. The
51838    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
51839    ** of the page, or to the number of cells in the page if the next page
51840    ** to visit is the right-child of its parent.
51841    **
51842    ** If all pages in the tree have been visited, return SQLITE_OK to the
51843    ** caller.
51844    */
51845    if( pPage->leaf ){
51846      do {
51847        if( pCur->iPage==0 ){
51848          /* All pages of the b-tree have been visited. Return successfully. */
51849          *pnEntry = nEntry;
51850          return SQLITE_OK;
51851        }
51852        moveToParent(pCur);
51853      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
51854
51855      pCur->aiIdx[pCur->iPage]++;
51856      pPage = pCur->apPage[pCur->iPage];
51857    }
51858
51859    /* Descend to the child node of the cell that the cursor currently
51860    ** points at. This is the right-child if (iIdx==pPage->nCell).
51861    */
51862    iIdx = pCur->aiIdx[pCur->iPage];
51863    if( iIdx==pPage->nCell ){
51864      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
51865    }else{
51866      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
51867    }
51868  }
51869
51870  /* An error has occurred. Return an error code. */
51871  return rc;
51872}
51873#endif
51874
51875/*
51876** Return the pager associated with a BTree.  This routine is used for
51877** testing and debugging only.
51878*/
51879SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
51880  return p->pBt->pPager;
51881}
51882
51883#ifndef SQLITE_OMIT_INTEGRITY_CHECK
51884/*
51885** Append a message to the error message string.
51886*/
51887static void checkAppendMsg(
51888  IntegrityCk *pCheck,
51889  char *zMsg1,
51890  const char *zFormat,
51891  ...
51892){
51893  va_list ap;
51894  if( !pCheck->mxErr ) return;
51895  pCheck->mxErr--;
51896  pCheck->nErr++;
51897  va_start(ap, zFormat);
51898  if( pCheck->errMsg.nChar ){
51899    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
51900  }
51901  if( zMsg1 ){
51902    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
51903  }
51904  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
51905  va_end(ap);
51906  if( pCheck->errMsg.mallocFailed ){
51907    pCheck->mallocFailed = 1;
51908  }
51909}
51910#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
51911
51912#ifndef SQLITE_OMIT_INTEGRITY_CHECK
51913/*
51914** Add 1 to the reference count for page iPage.  If this is the second
51915** reference to the page, add an error message to pCheck->zErrMsg.
51916** Return 1 if there are 2 ore more references to the page and 0 if
51917** if this is the first reference to the page.
51918**
51919** Also check that the page number is in bounds.
51920*/
51921static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
51922  if( iPage==0 ) return 1;
51923  if( iPage>pCheck->nPage ){
51924    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
51925    return 1;
51926  }
51927  if( pCheck->anRef[iPage]==1 ){
51928    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
51929    return 1;
51930  }
51931  return  (pCheck->anRef[iPage]++)>1;
51932}
51933
51934#ifndef SQLITE_OMIT_AUTOVACUUM
51935/*
51936** Check that the entry in the pointer-map for page iChild maps to
51937** page iParent, pointer type ptrType. If not, append an error message
51938** to pCheck.
51939*/
51940static void checkPtrmap(
51941  IntegrityCk *pCheck,   /* Integrity check context */
51942  Pgno iChild,           /* Child page number */
51943  u8 eType,              /* Expected pointer map type */
51944  Pgno iParent,          /* Expected pointer map parent page number */
51945  char *zContext         /* Context description (used for error msg) */
51946){
51947  int rc;
51948  u8 ePtrmapType;
51949  Pgno iPtrmapParent;
51950
51951  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
51952  if( rc!=SQLITE_OK ){
51953    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
51954    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
51955    return;
51956  }
51957
51958  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
51959    checkAppendMsg(pCheck, zContext,
51960      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
51961      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
51962  }
51963}
51964#endif
51965
51966/*
51967** Check the integrity of the freelist or of an overflow page list.
51968** Verify that the number of pages on the list is N.
51969*/
51970static void checkList(
51971  IntegrityCk *pCheck,  /* Integrity checking context */
51972  int isFreeList,       /* True for a freelist.  False for overflow page list */
51973  int iPage,            /* Page number for first page in the list */
51974  int N,                /* Expected number of pages in the list */
51975  char *zContext        /* Context for error messages */
51976){
51977  int i;
51978  int expected = N;
51979  int iFirst = iPage;
51980  while( N-- > 0 && pCheck->mxErr ){
51981    DbPage *pOvflPage;
51982    unsigned char *pOvflData;
51983    if( iPage<1 ){
51984      checkAppendMsg(pCheck, zContext,
51985         "%d of %d pages missing from overflow list starting at %d",
51986          N+1, expected, iFirst);
51987      break;
51988    }
51989    if( checkRef(pCheck, iPage, zContext) ) break;
51990    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
51991      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
51992      break;
51993    }
51994    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
51995    if( isFreeList ){
51996      int n = get4byte(&pOvflData[4]);
51997#ifndef SQLITE_OMIT_AUTOVACUUM
51998      if( pCheck->pBt->autoVacuum ){
51999        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
52000      }
52001#endif
52002      if( n>(int)pCheck->pBt->usableSize/4-2 ){
52003        checkAppendMsg(pCheck, zContext,
52004           "freelist leaf count too big on page %d", iPage);
52005        N--;
52006      }else{
52007        for(i=0; i<n; i++){
52008          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
52009#ifndef SQLITE_OMIT_AUTOVACUUM
52010          if( pCheck->pBt->autoVacuum ){
52011            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
52012          }
52013#endif
52014          checkRef(pCheck, iFreePage, zContext);
52015        }
52016        N -= n;
52017      }
52018    }
52019#ifndef SQLITE_OMIT_AUTOVACUUM
52020    else{
52021      /* If this database supports auto-vacuum and iPage is not the last
52022      ** page in this overflow list, check that the pointer-map entry for
52023      ** the following page matches iPage.
52024      */
52025      if( pCheck->pBt->autoVacuum && N>0 ){
52026        i = get4byte(pOvflData);
52027        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
52028      }
52029    }
52030#endif
52031    iPage = get4byte(pOvflData);
52032    sqlite3PagerUnref(pOvflPage);
52033  }
52034}
52035#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52036
52037#ifndef SQLITE_OMIT_INTEGRITY_CHECK
52038/*
52039** Do various sanity checks on a single page of a tree.  Return
52040** the tree depth.  Root pages return 0.  Parents of root pages
52041** return 1, and so forth.
52042**
52043** These checks are done:
52044**
52045**      1.  Make sure that cells and freeblocks do not overlap
52046**          but combine to completely cover the page.
52047**  NO  2.  Make sure cell keys are in order.
52048**  NO  3.  Make sure no key is less than or equal to zLowerBound.
52049**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
52050**      5.  Check the integrity of overflow pages.
52051**      6.  Recursively call checkTreePage on all children.
52052**      7.  Verify that the depth of all children is the same.
52053**      8.  Make sure this page is at least 33% full or else it is
52054**          the root of the tree.
52055*/
52056static int checkTreePage(
52057  IntegrityCk *pCheck,  /* Context for the sanity check */
52058  int iPage,            /* Page number of the page to check */
52059  char *zParentContext, /* Parent context */
52060  i64 *pnParentMinKey,
52061  i64 *pnParentMaxKey
52062){
52063  MemPage *pPage;
52064  int i, rc, depth, d2, pgno, cnt;
52065  int hdr, cellStart;
52066  int nCell;
52067  u8 *data;
52068  BtShared *pBt;
52069  int usableSize;
52070  char zContext[100];
52071  char *hit = 0;
52072  i64 nMinKey = 0;
52073  i64 nMaxKey = 0;
52074
52075  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
52076
52077  /* Check that the page exists
52078  */
52079  pBt = pCheck->pBt;
52080  usableSize = pBt->usableSize;
52081  if( iPage==0 ) return 0;
52082  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
52083  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
52084    checkAppendMsg(pCheck, zContext,
52085       "unable to get the page. error code=%d", rc);
52086    return 0;
52087  }
52088
52089  /* Clear MemPage.isInit to make sure the corruption detection code in
52090  ** btreeInitPage() is executed.  */
52091  pPage->isInit = 0;
52092  if( (rc = btreeInitPage(pPage))!=0 ){
52093    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
52094    checkAppendMsg(pCheck, zContext,
52095                   "btreeInitPage() returns error code %d", rc);
52096    releasePage(pPage);
52097    return 0;
52098  }
52099
52100  /* Check out all the cells.
52101  */
52102  depth = 0;
52103  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
52104    u8 *pCell;
52105    u32 sz;
52106    CellInfo info;
52107
52108    /* Check payload overflow pages
52109    */
52110    sqlite3_snprintf(sizeof(zContext), zContext,
52111             "On tree page %d cell %d: ", iPage, i);
52112    pCell = findCell(pPage,i);
52113    btreeParseCellPtr(pPage, pCell, &info);
52114    sz = info.nData;
52115    if( !pPage->intKey ) sz += (int)info.nKey;
52116    /* For intKey pages, check that the keys are in order.
52117    */
52118    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
52119    else{
52120      if( info.nKey <= nMaxKey ){
52121        checkAppendMsg(pCheck, zContext,
52122            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
52123      }
52124      nMaxKey = info.nKey;
52125    }
52126    assert( sz==info.nPayload );
52127    if( (sz>info.nLocal)
52128     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
52129    ){
52130      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
52131      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
52132#ifndef SQLITE_OMIT_AUTOVACUUM
52133      if( pBt->autoVacuum ){
52134        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
52135      }
52136#endif
52137      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
52138    }
52139
52140    /* Check sanity of left child page.
52141    */
52142    if( !pPage->leaf ){
52143      pgno = get4byte(pCell);
52144#ifndef SQLITE_OMIT_AUTOVACUUM
52145      if( pBt->autoVacuum ){
52146        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
52147      }
52148#endif
52149      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
52150      if( i>0 && d2!=depth ){
52151        checkAppendMsg(pCheck, zContext, "Child page depth differs");
52152      }
52153      depth = d2;
52154    }
52155  }
52156
52157  if( !pPage->leaf ){
52158    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52159    sqlite3_snprintf(sizeof(zContext), zContext,
52160                     "On page %d at right child: ", iPage);
52161#ifndef SQLITE_OMIT_AUTOVACUUM
52162    if( pBt->autoVacuum ){
52163      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
52164    }
52165#endif
52166    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
52167  }
52168
52169  /* For intKey leaf pages, check that the min/max keys are in order
52170  ** with any left/parent/right pages.
52171  */
52172  if( pPage->leaf && pPage->intKey ){
52173    /* if we are a left child page */
52174    if( pnParentMinKey ){
52175      /* if we are the left most child page */
52176      if( !pnParentMaxKey ){
52177        if( nMaxKey > *pnParentMinKey ){
52178          checkAppendMsg(pCheck, zContext,
52179              "Rowid %lld out of order (max larger than parent min of %lld)",
52180              nMaxKey, *pnParentMinKey);
52181        }
52182      }else{
52183        if( nMinKey <= *pnParentMinKey ){
52184          checkAppendMsg(pCheck, zContext,
52185              "Rowid %lld out of order (min less than parent min of %lld)",
52186              nMinKey, *pnParentMinKey);
52187        }
52188        if( nMaxKey > *pnParentMaxKey ){
52189          checkAppendMsg(pCheck, zContext,
52190              "Rowid %lld out of order (max larger than parent max of %lld)",
52191              nMaxKey, *pnParentMaxKey);
52192        }
52193        *pnParentMinKey = nMaxKey;
52194      }
52195    /* else if we're a right child page */
52196    } else if( pnParentMaxKey ){
52197      if( nMinKey <= *pnParentMaxKey ){
52198        checkAppendMsg(pCheck, zContext,
52199            "Rowid %lld out of order (min less than parent max of %lld)",
52200            nMinKey, *pnParentMaxKey);
52201      }
52202    }
52203  }
52204
52205  /* Check for complete coverage of the page
52206  */
52207  data = pPage->aData;
52208  hdr = pPage->hdrOffset;
52209  hit = sqlite3PageMalloc( pBt->pageSize );
52210  if( hit==0 ){
52211    pCheck->mallocFailed = 1;
52212  }else{
52213    int contentOffset = get2byteNotZero(&data[hdr+5]);
52214    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
52215    memset(hit+contentOffset, 0, usableSize-contentOffset);
52216    memset(hit, 1, contentOffset);
52217    nCell = get2byte(&data[hdr+3]);
52218    cellStart = hdr + 12 - 4*pPage->leaf;
52219    for(i=0; i<nCell; i++){
52220      int pc = get2byte(&data[cellStart+i*2]);
52221      u32 size = 65536;
52222      int j;
52223      if( pc<=usableSize-4 ){
52224        size = cellSizePtr(pPage, &data[pc]);
52225      }
52226      if( (int)(pc+size-1)>=usableSize ){
52227        checkAppendMsg(pCheck, 0,
52228            "Corruption detected in cell %d on page %d",i,iPage);
52229      }else{
52230        for(j=pc+size-1; j>=pc; j--) hit[j]++;
52231      }
52232    }
52233    i = get2byte(&data[hdr+1]);
52234    while( i>0 ){
52235      int size, j;
52236      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
52237      size = get2byte(&data[i+2]);
52238      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
52239      for(j=i+size-1; j>=i; j--) hit[j]++;
52240      j = get2byte(&data[i]);
52241      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
52242      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
52243      i = j;
52244    }
52245    for(i=cnt=0; i<usableSize; i++){
52246      if( hit[i]==0 ){
52247        cnt++;
52248      }else if( hit[i]>1 ){
52249        checkAppendMsg(pCheck, 0,
52250          "Multiple uses for byte %d of page %d", i, iPage);
52251        break;
52252      }
52253    }
52254    if( cnt!=data[hdr+7] ){
52255      checkAppendMsg(pCheck, 0,
52256          "Fragmentation of %d bytes reported as %d on page %d",
52257          cnt, data[hdr+7], iPage);
52258    }
52259  }
52260  sqlite3PageFree(hit);
52261  releasePage(pPage);
52262  return depth+1;
52263}
52264#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52265
52266#ifndef SQLITE_OMIT_INTEGRITY_CHECK
52267/*
52268** This routine does a complete check of the given BTree file.  aRoot[] is
52269** an array of pages numbers were each page number is the root page of
52270** a table.  nRoot is the number of entries in aRoot.
52271**
52272** A read-only or read-write transaction must be opened before calling
52273** this function.
52274**
52275** Write the number of error seen in *pnErr.  Except for some memory
52276** allocation errors,  an error message held in memory obtained from
52277** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
52278** returned.  If a memory allocation error occurs, NULL is returned.
52279*/
52280SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
52281  Btree *p,     /* The btree to be checked */
52282  int *aRoot,   /* An array of root pages numbers for individual trees */
52283  int nRoot,    /* Number of entries in aRoot[] */
52284  int mxErr,    /* Stop reporting errors after this many */
52285  int *pnErr    /* Write number of errors seen to this variable */
52286){
52287  Pgno i;
52288  int nRef;
52289  IntegrityCk sCheck;
52290  BtShared *pBt = p->pBt;
52291  char zErr[100];
52292
52293  sqlite3BtreeEnter(p);
52294  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
52295  nRef = sqlite3PagerRefcount(pBt->pPager);
52296  sCheck.pBt = pBt;
52297  sCheck.pPager = pBt->pPager;
52298  sCheck.nPage = btreePagecount(sCheck.pBt);
52299  sCheck.mxErr = mxErr;
52300  sCheck.nErr = 0;
52301  sCheck.mallocFailed = 0;
52302  *pnErr = 0;
52303  if( sCheck.nPage==0 ){
52304    sqlite3BtreeLeave(p);
52305    return 0;
52306  }
52307  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
52308  if( !sCheck.anRef ){
52309    *pnErr = 1;
52310    sqlite3BtreeLeave(p);
52311    return 0;
52312  }
52313  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
52314  i = PENDING_BYTE_PAGE(pBt);
52315  if( i<=sCheck.nPage ){
52316    sCheck.anRef[i] = 1;
52317  }
52318  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
52319  sCheck.errMsg.useMalloc = 2;
52320
52321  /* Check the integrity of the freelist
52322  */
52323  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
52324            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
52325
52326  /* Check all the tables.
52327  */
52328  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
52329    if( aRoot[i]==0 ) continue;
52330#ifndef SQLITE_OMIT_AUTOVACUUM
52331    if( pBt->autoVacuum && aRoot[i]>1 ){
52332      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
52333    }
52334#endif
52335    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
52336  }
52337
52338  /* Make sure every page in the file is referenced
52339  */
52340  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
52341#ifdef SQLITE_OMIT_AUTOVACUUM
52342    if( sCheck.anRef[i]==0 ){
52343      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
52344    }
52345#else
52346    /* If the database supports auto-vacuum, make sure no tables contain
52347    ** references to pointer-map pages.
52348    */
52349    if( sCheck.anRef[i]==0 &&
52350       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
52351      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
52352    }
52353    if( sCheck.anRef[i]!=0 &&
52354       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
52355      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
52356    }
52357#endif
52358  }
52359
52360  /* Make sure this analysis did not leave any unref() pages.
52361  ** This is an internal consistency check; an integrity check
52362  ** of the integrity check.
52363  */
52364  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
52365    checkAppendMsg(&sCheck, 0,
52366      "Outstanding page count goes from %d to %d during this analysis",
52367      nRef, sqlite3PagerRefcount(pBt->pPager)
52368    );
52369  }
52370
52371  /* Clean  up and report errors.
52372  */
52373  sqlite3BtreeLeave(p);
52374  sqlite3_free(sCheck.anRef);
52375  if( sCheck.mallocFailed ){
52376    sqlite3StrAccumReset(&sCheck.errMsg);
52377    *pnErr = sCheck.nErr+1;
52378    return 0;
52379  }
52380  *pnErr = sCheck.nErr;
52381  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
52382  return sqlite3StrAccumFinish(&sCheck.errMsg);
52383}
52384#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52385
52386/*
52387** Return the full pathname of the underlying database file.
52388**
52389** The pager filename is invariant as long as the pager is
52390** open so it is safe to access without the BtShared mutex.
52391*/
52392SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
52393  assert( p->pBt->pPager!=0 );
52394  return sqlite3PagerFilename(p->pBt->pPager);
52395}
52396
52397/*
52398** Return the pathname of the journal file for this database. The return
52399** value of this routine is the same regardless of whether the journal file
52400** has been created or not.
52401**
52402** The pager journal filename is invariant as long as the pager is
52403** open so it is safe to access without the BtShared mutex.
52404*/
52405SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
52406  assert( p->pBt->pPager!=0 );
52407  return sqlite3PagerJournalname(p->pBt->pPager);
52408}
52409
52410/*
52411** Return non-zero if a transaction is active.
52412*/
52413SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
52414  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
52415  return (p && (p->inTrans==TRANS_WRITE));
52416}
52417
52418#ifndef SQLITE_OMIT_WAL
52419/*
52420** Run a checkpoint on the Btree passed as the first argument.
52421**
52422** Return SQLITE_LOCKED if this or any other connection has an open
52423** transaction on the shared-cache the argument Btree is connected to.
52424*/
52425SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p){
52426  int rc = SQLITE_OK;
52427  if( p ){
52428    BtShared *pBt = p->pBt;
52429    sqlite3BtreeEnter(p);
52430    if( pBt->inTransaction!=TRANS_NONE ){
52431      rc = SQLITE_LOCKED;
52432    }else{
52433      rc = sqlite3PagerCheckpoint(pBt->pPager);
52434    }
52435    sqlite3BtreeLeave(p);
52436  }
52437  return rc;
52438}
52439#endif
52440
52441/*
52442** Return non-zero if a read (or write) transaction is active.
52443*/
52444SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
52445  assert( p );
52446  assert( sqlite3_mutex_held(p->db->mutex) );
52447  return p->inTrans!=TRANS_NONE;
52448}
52449
52450SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
52451  assert( p );
52452  assert( sqlite3_mutex_held(p->db->mutex) );
52453  return p->nBackup!=0;
52454}
52455
52456/*
52457** This function returns a pointer to a blob of memory associated with
52458** a single shared-btree. The memory is used by client code for its own
52459** purposes (for example, to store a high-level schema associated with
52460** the shared-btree). The btree layer manages reference counting issues.
52461**
52462** The first time this is called on a shared-btree, nBytes bytes of memory
52463** are allocated, zeroed, and returned to the caller. For each subsequent
52464** call the nBytes parameter is ignored and a pointer to the same blob
52465** of memory returned.
52466**
52467** If the nBytes parameter is 0 and the blob of memory has not yet been
52468** allocated, a null pointer is returned. If the blob has already been
52469** allocated, it is returned as normal.
52470**
52471** Just before the shared-btree is closed, the function passed as the
52472** xFree argument when the memory allocation was made is invoked on the
52473** blob of allocated memory. This function should not call sqlite3_free()
52474** on the memory, the btree layer does that.
52475*/
52476SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
52477  BtShared *pBt = p->pBt;
52478  sqlite3BtreeEnter(p);
52479  if( !pBt->pSchema && nBytes ){
52480    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
52481    pBt->xFreeSchema = xFree;
52482  }
52483  sqlite3BtreeLeave(p);
52484  return pBt->pSchema;
52485}
52486
52487/*
52488** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
52489** btree as the argument handle holds an exclusive lock on the
52490** sqlite_master table. Otherwise SQLITE_OK.
52491*/
52492SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
52493  int rc;
52494  assert( sqlite3_mutex_held(p->db->mutex) );
52495  sqlite3BtreeEnter(p);
52496  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52497  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
52498  sqlite3BtreeLeave(p);
52499  return rc;
52500}
52501
52502
52503#ifndef SQLITE_OMIT_SHARED_CACHE
52504/*
52505** Obtain a lock on the table whose root page is iTab.  The
52506** lock is a write lock if isWritelock is true or a read lock
52507** if it is false.
52508*/
52509SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
52510  int rc = SQLITE_OK;
52511  assert( p->inTrans!=TRANS_NONE );
52512  if( p->sharable ){
52513    u8 lockType = READ_LOCK + isWriteLock;
52514    assert( READ_LOCK+1==WRITE_LOCK );
52515    assert( isWriteLock==0 || isWriteLock==1 );
52516
52517    sqlite3BtreeEnter(p);
52518    rc = querySharedCacheTableLock(p, iTab, lockType);
52519    if( rc==SQLITE_OK ){
52520      rc = setSharedCacheTableLock(p, iTab, lockType);
52521    }
52522    sqlite3BtreeLeave(p);
52523  }
52524  return rc;
52525}
52526#endif
52527
52528#ifndef SQLITE_OMIT_INCRBLOB
52529/*
52530** Argument pCsr must be a cursor opened for writing on an
52531** INTKEY table currently pointing at a valid table entry.
52532** This function modifies the data stored as part of that entry.
52533**
52534** Only the data content may only be modified, it is not possible to
52535** change the length of the data stored. If this function is called with
52536** parameters that attempt to write past the end of the existing data,
52537** no modifications are made and SQLITE_CORRUPT is returned.
52538*/
52539SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
52540  int rc;
52541  assert( cursorHoldsMutex(pCsr) );
52542  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
52543  assert( pCsr->isIncrblobHandle );
52544
52545  rc = restoreCursorPosition(pCsr);
52546  if( rc!=SQLITE_OK ){
52547    return rc;
52548  }
52549  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
52550  if( pCsr->eState!=CURSOR_VALID ){
52551    return SQLITE_ABORT;
52552  }
52553
52554  /* Check some assumptions:
52555  **   (a) the cursor is open for writing,
52556  **   (b) there is a read/write transaction open,
52557  **   (c) the connection holds a write-lock on the table (if required),
52558  **   (d) there are no conflicting read-locks, and
52559  **   (e) the cursor points at a valid row of an intKey table.
52560  */
52561  if( !pCsr->wrFlag ){
52562    return SQLITE_READONLY;
52563  }
52564  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
52565  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
52566  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
52567  assert( pCsr->apPage[pCsr->iPage]->intKey );
52568
52569  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
52570}
52571
52572/*
52573** Set a flag on this cursor to cache the locations of pages from the
52574** overflow list for the current row. This is used by cursors opened
52575** for incremental blob IO only.
52576**
52577** This function sets a flag only. The actual page location cache
52578** (stored in BtCursor.aOverflow[]) is allocated and used by function
52579** accessPayload() (the worker function for sqlite3BtreeData() and
52580** sqlite3BtreePutData()).
52581*/
52582SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
52583  assert( cursorHoldsMutex(pCur) );
52584  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52585  assert(!pCur->isIncrblobHandle);
52586  assert(!pCur->aOverflow);
52587  pCur->isIncrblobHandle = 1;
52588}
52589#endif
52590
52591/*
52592** Set both the "read version" (single byte at byte offset 18) and
52593** "write version" (single byte at byte offset 19) fields in the database
52594** header to iVersion.
52595*/
52596SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
52597  BtShared *pBt = pBtree->pBt;
52598  int rc;                         /* Return code */
52599
52600  assert( pBtree->inTrans==TRANS_NONE );
52601  assert( iVersion==1 || iVersion==2 );
52602
52603  /* If setting the version fields to 1, do not automatically open the
52604  ** WAL connection, even if the version fields are currently set to 2.
52605  */
52606  pBt->doNotUseWAL = (u8)(iVersion==1);
52607
52608  rc = sqlite3BtreeBeginTrans(pBtree, 0);
52609  if( rc==SQLITE_OK ){
52610    u8 *aData = pBt->pPage1->aData;
52611    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
52612      rc = sqlite3BtreeBeginTrans(pBtree, 2);
52613      if( rc==SQLITE_OK ){
52614        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52615        if( rc==SQLITE_OK ){
52616          aData[18] = (u8)iVersion;
52617          aData[19] = (u8)iVersion;
52618        }
52619      }
52620    }
52621  }
52622
52623  pBt->doNotUseWAL = 0;
52624  return rc;
52625}
52626
52627/************** End of btree.c ***********************************************/
52628/************** Begin file backup.c ******************************************/
52629/*
52630** 2009 January 28
52631**
52632** The author disclaims copyright to this source code.  In place of
52633** a legal notice, here is a blessing:
52634**
52635**    May you do good and not evil.
52636**    May you find forgiveness for yourself and forgive others.
52637**    May you share freely, never taking more than you give.
52638**
52639*************************************************************************
52640** This file contains the implementation of the sqlite3_backup_XXX()
52641** API functions and the related features.
52642*/
52643
52644/* Macro to find the minimum of two numeric values.
52645*/
52646#ifndef MIN
52647# define MIN(x,y) ((x)<(y)?(x):(y))
52648#endif
52649
52650/*
52651** Structure allocated for each backup operation.
52652*/
52653struct sqlite3_backup {
52654  sqlite3* pDestDb;        /* Destination database handle */
52655  Btree *pDest;            /* Destination b-tree file */
52656  u32 iDestSchema;         /* Original schema cookie in destination */
52657  int bDestLocked;         /* True once a write-transaction is open on pDest */
52658
52659  Pgno iNext;              /* Page number of the next source page to copy */
52660  sqlite3* pSrcDb;         /* Source database handle */
52661  Btree *pSrc;             /* Source b-tree file */
52662
52663  int rc;                  /* Backup process error code */
52664
52665  /* These two variables are set by every call to backup_step(). They are
52666  ** read by calls to backup_remaining() and backup_pagecount().
52667  */
52668  Pgno nRemaining;         /* Number of pages left to copy */
52669  Pgno nPagecount;         /* Total number of pages to copy */
52670
52671  int isAttached;          /* True once backup has been registered with pager */
52672  sqlite3_backup *pNext;   /* Next backup associated with source pager */
52673};
52674
52675/*
52676** THREAD SAFETY NOTES:
52677**
52678**   Once it has been created using backup_init(), a single sqlite3_backup
52679**   structure may be accessed via two groups of thread-safe entry points:
52680**
52681**     * Via the sqlite3_backup_XXX() API function backup_step() and
52682**       backup_finish(). Both these functions obtain the source database
52683**       handle mutex and the mutex associated with the source BtShared
52684**       structure, in that order.
52685**
52686**     * Via the BackupUpdate() and BackupRestart() functions, which are
52687**       invoked by the pager layer to report various state changes in
52688**       the page cache associated with the source database. The mutex
52689**       associated with the source database BtShared structure will always
52690**       be held when either of these functions are invoked.
52691**
52692**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
52693**   backup_pagecount() are not thread-safe functions. If they are called
52694**   while some other thread is calling backup_step() or backup_finish(),
52695**   the values returned may be invalid. There is no way for a call to
52696**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
52697**   or backup_pagecount().
52698**
52699**   Depending on the SQLite configuration, the database handles and/or
52700**   the Btree objects may have their own mutexes that require locking.
52701**   Non-sharable Btrees (in-memory databases for example), do not have
52702**   associated mutexes.
52703*/
52704
52705/*
52706** Return a pointer corresponding to database zDb (i.e. "main", "temp")
52707** in connection handle pDb. If such a database cannot be found, return
52708** a NULL pointer and write an error message to pErrorDb.
52709**
52710** If the "temp" database is requested, it may need to be opened by this
52711** function. If an error occurs while doing so, return 0 and write an
52712** error message to pErrorDb.
52713*/
52714static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
52715  int i = sqlite3FindDbName(pDb, zDb);
52716
52717  if( i==1 ){
52718    Parse *pParse;
52719    int rc = 0;
52720    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
52721    if( pParse==0 ){
52722      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
52723      rc = SQLITE_NOMEM;
52724    }else{
52725      pParse->db = pDb;
52726      if( sqlite3OpenTempDatabase(pParse) ){
52727        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
52728        rc = SQLITE_ERROR;
52729      }
52730      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
52731      sqlite3StackFree(pErrorDb, pParse);
52732    }
52733    if( rc ){
52734      return 0;
52735    }
52736  }
52737
52738  if( i<0 ){
52739    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
52740    return 0;
52741  }
52742
52743  return pDb->aDb[i].pBt;
52744}
52745
52746/*
52747** Create an sqlite3_backup process to copy the contents of zSrcDb from
52748** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
52749** a pointer to the new sqlite3_backup object.
52750**
52751** If an error occurs, NULL is returned and an error code and error message
52752** stored in database handle pDestDb.
52753*/
52754SQLITE_API sqlite3_backup *sqlite3_backup_init(
52755  sqlite3* pDestDb,                     /* Database to write to */
52756  const char *zDestDb,                  /* Name of database within pDestDb */
52757  sqlite3* pSrcDb,                      /* Database connection to read from */
52758  const char *zSrcDb                    /* Name of database within pSrcDb */
52759){
52760  sqlite3_backup *p;                    /* Value to return */
52761
52762  /* Lock the source database handle. The destination database
52763  ** handle is not locked in this routine, but it is locked in
52764  ** sqlite3_backup_step(). The user is required to ensure that no
52765  ** other thread accesses the destination handle for the duration
52766  ** of the backup operation.  Any attempt to use the destination
52767  ** database connection while a backup is in progress may cause
52768  ** a malfunction or a deadlock.
52769  */
52770  sqlite3_mutex_enter(pSrcDb->mutex);
52771  sqlite3_mutex_enter(pDestDb->mutex);
52772
52773  if( pSrcDb==pDestDb ){
52774    sqlite3Error(
52775        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
52776    );
52777    p = 0;
52778  }else {
52779    /* Allocate space for a new sqlite3_backup object */
52780    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
52781    if( !p ){
52782      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
52783    }
52784  }
52785
52786  /* If the allocation succeeded, populate the new object. */
52787  if( p ){
52788    memset(p, 0, sizeof(sqlite3_backup));
52789    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
52790    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
52791    p->pDestDb = pDestDb;
52792    p->pSrcDb = pSrcDb;
52793    p->iNext = 1;
52794    p->isAttached = 0;
52795
52796    if( 0==p->pSrc || 0==p->pDest ){
52797      /* One (or both) of the named databases did not exist. An error has
52798      ** already been written into the pDestDb handle. All that is left
52799      ** to do here is free the sqlite3_backup structure.
52800      */
52801      sqlite3_free(p);
52802      p = 0;
52803    }
52804  }
52805  if( p ){
52806    p->pSrc->nBackup++;
52807  }
52808
52809  sqlite3_mutex_leave(pDestDb->mutex);
52810  sqlite3_mutex_leave(pSrcDb->mutex);
52811  return p;
52812}
52813
52814/*
52815** Argument rc is an SQLite error code. Return true if this error is
52816** considered fatal if encountered during a backup operation. All errors
52817** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
52818*/
52819static int isFatalError(int rc){
52820  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
52821}
52822
52823/*
52824** Parameter zSrcData points to a buffer containing the data for
52825** page iSrcPg from the source database. Copy this data into the
52826** destination database.
52827*/
52828static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
52829  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
52830  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
52831  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
52832  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
52833  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
52834
52835  int rc = SQLITE_OK;
52836  i64 iOff;
52837
52838  assert( p->bDestLocked );
52839  assert( !isFatalError(p->rc) );
52840  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
52841  assert( zSrcData );
52842
52843  /* Catch the case where the destination is an in-memory database and the
52844  ** page sizes of the source and destination differ.
52845  */
52846  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
52847    rc = SQLITE_READONLY;
52848  }
52849
52850#ifdef SQLITE_HAS_CODEC
52851  /* Backup is not possible if the page size of the destination is changing
52852  ** a a codec is in use.
52853  */
52854  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
52855    rc = SQLITE_READONLY;
52856  }
52857#endif
52858
52859  /* This loop runs once for each destination page spanned by the source
52860  ** page. For each iteration, variable iOff is set to the byte offset
52861  ** of the destination page.
52862  */
52863  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
52864    DbPage *pDestPg = 0;
52865    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
52866    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
52867    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
52868     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
52869    ){
52870      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
52871      u8 *zDestData = sqlite3PagerGetData(pDestPg);
52872      u8 *zOut = &zDestData[iOff%nDestPgsz];
52873
52874      /* Copy the data from the source page into the destination page.
52875      ** Then clear the Btree layer MemPage.isInit flag. Both this module
52876      ** and the pager code use this trick (clearing the first byte
52877      ** of the page 'extra' space to invalidate the Btree layers
52878      ** cached parse of the page). MemPage.isInit is marked
52879      ** "MUST BE FIRST" for this purpose.
52880      */
52881      memcpy(zOut, zIn, nCopy);
52882      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
52883    }
52884    sqlite3PagerUnref(pDestPg);
52885  }
52886
52887  return rc;
52888}
52889
52890/*
52891** If pFile is currently larger than iSize bytes, then truncate it to
52892** exactly iSize bytes. If pFile is not larger than iSize bytes, then
52893** this function is a no-op.
52894**
52895** Return SQLITE_OK if everything is successful, or an SQLite error
52896** code if an error occurs.
52897*/
52898static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
52899  i64 iCurrent;
52900  int rc = sqlite3OsFileSize(pFile, &iCurrent);
52901  if( rc==SQLITE_OK && iCurrent>iSize ){
52902    rc = sqlite3OsTruncate(pFile, iSize);
52903  }
52904  return rc;
52905}
52906
52907/*
52908** Register this backup object with the associated source pager for
52909** callbacks when pages are changed or the cache invalidated.
52910*/
52911static void attachBackupObject(sqlite3_backup *p){
52912  sqlite3_backup **pp;
52913  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
52914  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
52915  p->pNext = *pp;
52916  *pp = p;
52917  p->isAttached = 1;
52918}
52919
52920/*
52921** Copy nPage pages from the source b-tree to the destination.
52922*/
52923SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
52924  int rc;
52925  int destMode;       /* Destination journal mode */
52926  int pgszSrc = 0;    /* Source page size */
52927  int pgszDest = 0;   /* Destination page size */
52928
52929  sqlite3_mutex_enter(p->pSrcDb->mutex);
52930  sqlite3BtreeEnter(p->pSrc);
52931  if( p->pDestDb ){
52932    sqlite3_mutex_enter(p->pDestDb->mutex);
52933  }
52934
52935  rc = p->rc;
52936  if( !isFatalError(rc) ){
52937    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
52938    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
52939    int ii;                            /* Iterator variable */
52940    int nSrcPage = -1;                 /* Size of source db in pages */
52941    int bCloseTrans = 0;               /* True if src db requires unlocking */
52942
52943    /* If the source pager is currently in a write-transaction, return
52944    ** SQLITE_BUSY immediately.
52945    */
52946    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
52947      rc = SQLITE_BUSY;
52948    }else{
52949      rc = SQLITE_OK;
52950    }
52951
52952    /* Lock the destination database, if it is not locked already. */
52953    if( SQLITE_OK==rc && p->bDestLocked==0
52954     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
52955    ){
52956      p->bDestLocked = 1;
52957      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
52958    }
52959
52960    /* If there is no open read-transaction on the source database, open
52961    ** one now. If a transaction is opened here, then it will be closed
52962    ** before this function exits.
52963    */
52964    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
52965      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
52966      bCloseTrans = 1;
52967    }
52968
52969    /* Do not allow backup if the destination database is in WAL mode
52970    ** and the page sizes are different between source and destination */
52971    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
52972    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
52973    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
52974    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
52975      rc = SQLITE_READONLY;
52976    }
52977
52978    /* Now that there is a read-lock on the source database, query the
52979    ** source pager for the number of pages in the database.
52980    */
52981    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
52982    assert( nSrcPage>=0 );
52983    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
52984      const Pgno iSrcPg = p->iNext;                 /* Source page number */
52985      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
52986        DbPage *pSrcPg;                             /* Source page object */
52987        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
52988        if( rc==SQLITE_OK ){
52989          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
52990          sqlite3PagerUnref(pSrcPg);
52991        }
52992      }
52993      p->iNext++;
52994    }
52995    if( rc==SQLITE_OK ){
52996      p->nPagecount = nSrcPage;
52997      p->nRemaining = nSrcPage+1-p->iNext;
52998      if( p->iNext>(Pgno)nSrcPage ){
52999        rc = SQLITE_DONE;
53000      }else if( !p->isAttached ){
53001        attachBackupObject(p);
53002      }
53003    }
53004
53005    /* Update the schema version field in the destination database. This
53006    ** is to make sure that the schema-version really does change in
53007    ** the case where the source and destination databases have the
53008    ** same schema version.
53009    */
53010    if( rc==SQLITE_DONE
53011     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
53012    ){
53013      int nDestTruncate;
53014
53015      if( p->pDestDb ){
53016        sqlite3ResetInternalSchema(p->pDestDb, 0);
53017      }
53018
53019      /* Set nDestTruncate to the final number of pages in the destination
53020      ** database. The complication here is that the destination page
53021      ** size may be different to the source page size.
53022      **
53023      ** If the source page size is smaller than the destination page size,
53024      ** round up. In this case the call to sqlite3OsTruncate() below will
53025      ** fix the size of the file. However it is important to call
53026      ** sqlite3PagerTruncateImage() here so that any pages in the
53027      ** destination file that lie beyond the nDestTruncate page mark are
53028      ** journalled by PagerCommitPhaseOne() before they are destroyed
53029      ** by the file truncation.
53030      */
53031      assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
53032      assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
53033      if( pgszSrc<pgszDest ){
53034        int ratio = pgszDest/pgszSrc;
53035        nDestTruncate = (nSrcPage+ratio-1)/ratio;
53036        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
53037          nDestTruncate--;
53038        }
53039      }else{
53040        nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
53041      }
53042      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
53043
53044      if( pgszSrc<pgszDest ){
53045        /* If the source page-size is smaller than the destination page-size,
53046        ** two extra things may need to happen:
53047        **
53048        **   * The destination may need to be truncated, and
53049        **
53050        **   * Data stored on the pages immediately following the
53051        **     pending-byte page in the source database may need to be
53052        **     copied into the destination database.
53053        */
53054        const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
53055        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
53056
53057        assert( pFile );
53058        assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
53059              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
53060           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
53061        ));
53062        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
53063         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
53064         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
53065        ){
53066          i64 iOff;
53067          i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
53068          for(
53069            iOff=PENDING_BYTE+pgszSrc;
53070            rc==SQLITE_OK && iOff<iEnd;
53071            iOff+=pgszSrc
53072          ){
53073            PgHdr *pSrcPg = 0;
53074            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
53075            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
53076            if( rc==SQLITE_OK ){
53077              u8 *zData = sqlite3PagerGetData(pSrcPg);
53078              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
53079            }
53080            sqlite3PagerUnref(pSrcPg);
53081          }
53082        }
53083      }else{
53084        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
53085      }
53086
53087      /* Finish committing the transaction to the destination database. */
53088      if( SQLITE_OK==rc
53089       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
53090      ){
53091        rc = SQLITE_DONE;
53092      }
53093    }
53094
53095    /* If bCloseTrans is true, then this function opened a read transaction
53096    ** on the source database. Close the read transaction here. There is
53097    ** no need to check the return values of the btree methods here, as
53098    ** "committing" a read-only transaction cannot fail.
53099    */
53100    if( bCloseTrans ){
53101      TESTONLY( int rc2 );
53102      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
53103      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
53104      assert( rc2==SQLITE_OK );
53105    }
53106
53107    if( rc==SQLITE_IOERR_NOMEM ){
53108      rc = SQLITE_NOMEM;
53109    }
53110    p->rc = rc;
53111  }
53112  if( p->pDestDb ){
53113    sqlite3_mutex_leave(p->pDestDb->mutex);
53114  }
53115  sqlite3BtreeLeave(p->pSrc);
53116  sqlite3_mutex_leave(p->pSrcDb->mutex);
53117  return rc;
53118}
53119
53120/*
53121** Release all resources associated with an sqlite3_backup* handle.
53122*/
53123SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
53124  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
53125  sqlite3_mutex *mutex;                /* Mutex to protect source database */
53126  int rc;                              /* Value to return */
53127
53128  /* Enter the mutexes */
53129  if( p==0 ) return SQLITE_OK;
53130  sqlite3_mutex_enter(p->pSrcDb->mutex);
53131  sqlite3BtreeEnter(p->pSrc);
53132  mutex = p->pSrcDb->mutex;
53133  if( p->pDestDb ){
53134    sqlite3_mutex_enter(p->pDestDb->mutex);
53135  }
53136
53137  /* Detach this backup from the source pager. */
53138  if( p->pDestDb ){
53139    p->pSrc->nBackup--;
53140  }
53141  if( p->isAttached ){
53142    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
53143    while( *pp!=p ){
53144      pp = &(*pp)->pNext;
53145    }
53146    *pp = p->pNext;
53147  }
53148
53149  /* If a transaction is still open on the Btree, roll it back. */
53150  sqlite3BtreeRollback(p->pDest);
53151
53152  /* Set the error code of the destination database handle. */
53153  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
53154  sqlite3Error(p->pDestDb, rc, 0);
53155
53156  /* Exit the mutexes and free the backup context structure. */
53157  if( p->pDestDb ){
53158    sqlite3_mutex_leave(p->pDestDb->mutex);
53159  }
53160  sqlite3BtreeLeave(p->pSrc);
53161  if( p->pDestDb ){
53162    sqlite3_free(p);
53163  }
53164  sqlite3_mutex_leave(mutex);
53165  return rc;
53166}
53167
53168/*
53169** Return the number of pages still to be backed up as of the most recent
53170** call to sqlite3_backup_step().
53171*/
53172SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
53173  return p->nRemaining;
53174}
53175
53176/*
53177** Return the total number of pages in the source database as of the most
53178** recent call to sqlite3_backup_step().
53179*/
53180SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
53181  return p->nPagecount;
53182}
53183
53184/*
53185** This function is called after the contents of page iPage of the
53186** source database have been modified. If page iPage has already been
53187** copied into the destination database, then the data written to the
53188** destination is now invalidated. The destination copy of iPage needs
53189** to be updated with the new data before the backup operation is
53190** complete.
53191**
53192** It is assumed that the mutex associated with the BtShared object
53193** corresponding to the source database is held when this function is
53194** called.
53195*/
53196SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
53197  sqlite3_backup *p;                   /* Iterator variable */
53198  for(p=pBackup; p; p=p->pNext){
53199    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
53200    if( !isFatalError(p->rc) && iPage<p->iNext ){
53201      /* The backup process p has already copied page iPage. But now it
53202      ** has been modified by a transaction on the source pager. Copy
53203      ** the new data into the backup.
53204      */
53205      int rc = backupOnePage(p, iPage, aData);
53206      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
53207      if( rc!=SQLITE_OK ){
53208        p->rc = rc;
53209      }
53210    }
53211  }
53212}
53213
53214/*
53215** Restart the backup process. This is called when the pager layer
53216** detects that the database has been modified by an external database
53217** connection. In this case there is no way of knowing which of the
53218** pages that have been copied into the destination database are still
53219** valid and which are not, so the entire process needs to be restarted.
53220**
53221** It is assumed that the mutex associated with the BtShared object
53222** corresponding to the source database is held when this function is
53223** called.
53224*/
53225SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
53226  sqlite3_backup *p;                   /* Iterator variable */
53227  for(p=pBackup; p; p=p->pNext){
53228    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
53229    p->iNext = 1;
53230  }
53231}
53232
53233#ifndef SQLITE_OMIT_VACUUM
53234/*
53235** Copy the complete content of pBtFrom into pBtTo.  A transaction
53236** must be active for both files.
53237**
53238** The size of file pTo may be reduced by this operation. If anything
53239** goes wrong, the transaction on pTo is rolled back. If successful, the
53240** transaction is committed before returning.
53241*/
53242SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
53243  int rc;
53244  sqlite3_backup b;
53245  sqlite3BtreeEnter(pTo);
53246  sqlite3BtreeEnter(pFrom);
53247
53248  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
53249  ** to 0. This is used by the implementations of sqlite3_backup_step()
53250  ** and sqlite3_backup_finish() to detect that they are being called
53251  ** from this function, not directly by the user.
53252  */
53253  memset(&b, 0, sizeof(b));
53254  b.pSrcDb = pFrom->db;
53255  b.pSrc = pFrom;
53256  b.pDest = pTo;
53257  b.iNext = 1;
53258
53259  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
53260  ** file. By passing this as the number of pages to copy to
53261  ** sqlite3_backup_step(), we can guarantee that the copy finishes
53262  ** within a single call (unless an error occurs). The assert() statement
53263  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
53264  ** or an error code.
53265  */
53266  sqlite3_backup_step(&b, 0x7FFFFFFF);
53267  assert( b.rc!=SQLITE_OK );
53268  rc = sqlite3_backup_finish(&b);
53269  if( rc==SQLITE_OK ){
53270    pTo->pBt->pageSizeFixed = 0;
53271  }
53272
53273  sqlite3BtreeLeave(pFrom);
53274  sqlite3BtreeLeave(pTo);
53275  return rc;
53276}
53277#endif /* SQLITE_OMIT_VACUUM */
53278
53279/************** End of backup.c **********************************************/
53280/************** Begin file vdbemem.c *****************************************/
53281/*
53282** 2004 May 26
53283**
53284** The author disclaims copyright to this source code.  In place of
53285** a legal notice, here is a blessing:
53286**
53287**    May you do good and not evil.
53288**    May you find forgiveness for yourself and forgive others.
53289**    May you share freely, never taking more than you give.
53290**
53291*************************************************************************
53292**
53293** This file contains code use to manipulate "Mem" structure.  A "Mem"
53294** stores a single value in the VDBE.  Mem is an opaque structure visible
53295** only within the VDBE.  Interface routines refer to a Mem using the
53296** name sqlite_value
53297*/
53298
53299/*
53300** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
53301** P if required.
53302*/
53303#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
53304
53305/*
53306** If pMem is an object with a valid string representation, this routine
53307** ensures the internal encoding for the string representation is
53308** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
53309**
53310** If pMem is not a string object, or the encoding of the string
53311** representation is already stored using the requested encoding, then this
53312** routine is a no-op.
53313**
53314** SQLITE_OK is returned if the conversion is successful (or not required).
53315** SQLITE_NOMEM may be returned if a malloc() fails during conversion
53316** between formats.
53317*/
53318SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
53319  int rc;
53320  assert( (pMem->flags&MEM_RowSet)==0 );
53321  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
53322           || desiredEnc==SQLITE_UTF16BE );
53323  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
53324    return SQLITE_OK;
53325  }
53326  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53327#ifdef SQLITE_OMIT_UTF16
53328  return SQLITE_ERROR;
53329#else
53330
53331  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
53332  ** then the encoding of the value may not have changed.
53333  */
53334  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
53335  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
53336  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
53337  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
53338  return rc;
53339#endif
53340}
53341
53342/*
53343** Make sure pMem->z points to a writable allocation of at least
53344** n bytes.
53345**
53346** If the memory cell currently contains string or blob data
53347** and the third argument passed to this function is true, the
53348** current content of the cell is preserved. Otherwise, it may
53349** be discarded.
53350**
53351** This function sets the MEM_Dyn flag and clears any xDel callback.
53352** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
53353** not set, Mem.n is zeroed.
53354*/
53355SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
53356  assert( 1 >=
53357    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
53358    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
53359    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
53360    ((pMem->flags&MEM_Static) ? 1 : 0)
53361  );
53362  assert( (pMem->flags&MEM_RowSet)==0 );
53363
53364  if( n<32 ) n = 32;
53365  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
53366    if( preserve && pMem->z==pMem->zMalloc ){
53367      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
53368      preserve = 0;
53369    }else{
53370      sqlite3DbFree(pMem->db, pMem->zMalloc);
53371      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
53372    }
53373  }
53374
53375  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
53376    memcpy(pMem->zMalloc, pMem->z, pMem->n);
53377  }
53378  if( pMem->flags&MEM_Dyn && pMem->xDel ){
53379    pMem->xDel((void *)(pMem->z));
53380  }
53381
53382  pMem->z = pMem->zMalloc;
53383  if( pMem->z==0 ){
53384    pMem->flags = MEM_Null;
53385  }else{
53386    pMem->flags &= ~(MEM_Ephem|MEM_Static);
53387  }
53388  pMem->xDel = 0;
53389  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
53390}
53391
53392/*
53393** Make the given Mem object MEM_Dyn.  In other words, make it so
53394** that any TEXT or BLOB content is stored in memory obtained from
53395** malloc().  In this way, we know that the memory is safe to be
53396** overwritten or altered.
53397**
53398** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
53399*/
53400SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
53401  int f;
53402  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53403  assert( (pMem->flags&MEM_RowSet)==0 );
53404  expandBlob(pMem);
53405  f = pMem->flags;
53406  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
53407    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
53408      return SQLITE_NOMEM;
53409    }
53410    pMem->z[pMem->n] = 0;
53411    pMem->z[pMem->n+1] = 0;
53412    pMem->flags |= MEM_Term;
53413  }
53414
53415  return SQLITE_OK;
53416}
53417
53418/*
53419** If the given Mem* has a zero-filled tail, turn it into an ordinary
53420** blob stored in dynamically allocated space.
53421*/
53422#ifndef SQLITE_OMIT_INCRBLOB
53423SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
53424  if( pMem->flags & MEM_Zero ){
53425    int nByte;
53426    assert( pMem->flags&MEM_Blob );
53427    assert( (pMem->flags&MEM_RowSet)==0 );
53428    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53429
53430    /* Set nByte to the number of bytes required to store the expanded blob. */
53431    nByte = pMem->n + pMem->u.nZero;
53432    if( nByte<=0 ){
53433      nByte = 1;
53434    }
53435    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
53436      return SQLITE_NOMEM;
53437    }
53438
53439    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
53440    pMem->n += pMem->u.nZero;
53441    pMem->flags &= ~(MEM_Zero|MEM_Term);
53442  }
53443  return SQLITE_OK;
53444}
53445#endif
53446
53447
53448/*
53449** Make sure the given Mem is \u0000 terminated.
53450*/
53451SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
53452  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53453  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
53454    return SQLITE_OK;   /* Nothing to do */
53455  }
53456  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
53457    return SQLITE_NOMEM;
53458  }
53459  pMem->z[pMem->n] = 0;
53460  pMem->z[pMem->n+1] = 0;
53461  pMem->flags |= MEM_Term;
53462  return SQLITE_OK;
53463}
53464
53465/*
53466** Add MEM_Str to the set of representations for the given Mem.  Numbers
53467** are converted using sqlite3_snprintf().  Converting a BLOB to a string
53468** is a no-op.
53469**
53470** Existing representations MEM_Int and MEM_Real are *not* invalidated.
53471**
53472** A MEM_Null value will never be passed to this function. This function is
53473** used for converting values to text for returning to the user (i.e. via
53474** sqlite3_value_text()), or for ensuring that values to be used as btree
53475** keys are strings. In the former case a NULL pointer is returned the
53476** user and the later is an internal programming error.
53477*/
53478SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
53479  int rc = SQLITE_OK;
53480  int fg = pMem->flags;
53481  const int nByte = 32;
53482
53483  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53484  assert( !(fg&MEM_Zero) );
53485  assert( !(fg&(MEM_Str|MEM_Blob)) );
53486  assert( fg&(MEM_Int|MEM_Real) );
53487  assert( (pMem->flags&MEM_RowSet)==0 );
53488  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53489
53490
53491  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
53492    return SQLITE_NOMEM;
53493  }
53494
53495  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
53496  ** string representation of the value. Then, if the required encoding
53497  ** is UTF-16le or UTF-16be do a translation.
53498  **
53499  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
53500  */
53501  if( fg & MEM_Int ){
53502    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
53503  }else{
53504    assert( fg & MEM_Real );
53505    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
53506  }
53507  pMem->n = sqlite3Strlen30(pMem->z);
53508  pMem->enc = SQLITE_UTF8;
53509  pMem->flags |= MEM_Str|MEM_Term;
53510  sqlite3VdbeChangeEncoding(pMem, enc);
53511  return rc;
53512}
53513
53514/*
53515** Memory cell pMem contains the context of an aggregate function.
53516** This routine calls the finalize method for that function.  The
53517** result of the aggregate is stored back into pMem.
53518**
53519** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
53520** otherwise.
53521*/
53522SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
53523  int rc = SQLITE_OK;
53524  if( ALWAYS(pFunc && pFunc->xFinalize) ){
53525    sqlite3_context ctx;
53526    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
53527    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53528    memset(&ctx, 0, sizeof(ctx));
53529    ctx.s.flags = MEM_Null;
53530    ctx.s.db = pMem->db;
53531    ctx.pMem = pMem;
53532    ctx.pFunc = pFunc;
53533    pFunc->xFinalize(&ctx);
53534    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
53535    sqlite3DbFree(pMem->db, pMem->zMalloc);
53536    memcpy(pMem, &ctx.s, sizeof(ctx.s));
53537    rc = ctx.isError;
53538  }
53539  return rc;
53540}
53541
53542/*
53543** If the memory cell contains a string value that must be freed by
53544** invoking an external callback, free it now. Calling this function
53545** does not free any Mem.zMalloc buffer.
53546*/
53547SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
53548  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
53549  testcase( p->flags & MEM_Agg );
53550  testcase( p->flags & MEM_Dyn );
53551  testcase( p->flags & MEM_RowSet );
53552  testcase( p->flags & MEM_Frame );
53553  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
53554    if( p->flags&MEM_Agg ){
53555      sqlite3VdbeMemFinalize(p, p->u.pDef);
53556      assert( (p->flags & MEM_Agg)==0 );
53557      sqlite3VdbeMemRelease(p);
53558    }else if( p->flags&MEM_Dyn && p->xDel ){
53559      assert( (p->flags&MEM_RowSet)==0 );
53560      p->xDel((void *)p->z);
53561      p->xDel = 0;
53562    }else if( p->flags&MEM_RowSet ){
53563      sqlite3RowSetClear(p->u.pRowSet);
53564    }else if( p->flags&MEM_Frame ){
53565      sqlite3VdbeMemSetNull(p);
53566    }
53567  }
53568}
53569
53570/*
53571** Release any memory held by the Mem. This may leave the Mem in an
53572** inconsistent state, for example with (Mem.z==0) and
53573** (Mem.type==SQLITE_TEXT).
53574*/
53575SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
53576  sqlite3VdbeMemReleaseExternal(p);
53577  sqlite3DbFree(p->db, p->zMalloc);
53578  p->z = 0;
53579  p->zMalloc = 0;
53580  p->xDel = 0;
53581}
53582
53583/*
53584** Convert a 64-bit IEEE double into a 64-bit signed integer.
53585** If the double is too large, return 0x8000000000000000.
53586**
53587** Most systems appear to do this simply by assigning
53588** variables and without the extra range tests.  But
53589** there are reports that windows throws an expection
53590** if the floating point value is out of range. (See ticket #2880.)
53591** Because we do not completely understand the problem, we will
53592** take the conservative approach and always do range tests
53593** before attempting the conversion.
53594*/
53595static i64 doubleToInt64(double r){
53596#ifdef SQLITE_OMIT_FLOATING_POINT
53597  /* When floating-point is omitted, double and int64 are the same thing */
53598  return r;
53599#else
53600  /*
53601  ** Many compilers we encounter do not define constants for the
53602  ** minimum and maximum 64-bit integers, or they define them
53603  ** inconsistently.  And many do not understand the "LL" notation.
53604  ** So we define our own static constants here using nothing
53605  ** larger than a 32-bit integer constant.
53606  */
53607  static const i64 maxInt = LARGEST_INT64;
53608  static const i64 minInt = SMALLEST_INT64;
53609
53610  if( r<(double)minInt ){
53611    return minInt;
53612  }else if( r>(double)maxInt ){
53613    /* minInt is correct here - not maxInt.  It turns out that assigning
53614    ** a very large positive number to an integer results in a very large
53615    ** negative integer.  This makes no sense, but it is what x86 hardware
53616    ** does so for compatibility we will do the same in software. */
53617    return minInt;
53618  }else{
53619    return (i64)r;
53620  }
53621#endif
53622}
53623
53624/*
53625** Return some kind of integer value which is the best we can do
53626** at representing the value that *pMem describes as an integer.
53627** If pMem is an integer, then the value is exact.  If pMem is
53628** a floating-point then the value returned is the integer part.
53629** If pMem is a string or blob, then we make an attempt to convert
53630** it into a integer and return that.  If pMem represents an
53631** an SQL-NULL value, return 0.
53632**
53633** If pMem represents a string value, its encoding might be changed.
53634*/
53635SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
53636  int flags;
53637  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53638  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53639  flags = pMem->flags;
53640  if( flags & MEM_Int ){
53641    return pMem->u.i;
53642  }else if( flags & MEM_Real ){
53643    return doubleToInt64(pMem->r);
53644  }else if( flags & (MEM_Str|MEM_Blob) ){
53645    i64 value;
53646    pMem->flags |= MEM_Str;
53647    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
53648       || sqlite3VdbeMemNulTerminate(pMem) ){
53649      return 0;
53650    }
53651    assert( pMem->z );
53652    sqlite3Atoi64(pMem->z, &value);
53653    return value;
53654  }else{
53655    return 0;
53656  }
53657}
53658
53659/*
53660** Return the best representation of pMem that we can get into a
53661** double.  If pMem is already a double or an integer, return its
53662** value.  If it is a string or blob, try to convert it to a double.
53663** If it is a NULL, return 0.0.
53664*/
53665SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
53666  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53667  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53668  if( pMem->flags & MEM_Real ){
53669    return pMem->r;
53670  }else if( pMem->flags & MEM_Int ){
53671    return (double)pMem->u.i;
53672  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
53673    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53674    double val = (double)0;
53675    pMem->flags |= MEM_Str;
53676    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
53677       || sqlite3VdbeMemNulTerminate(pMem) ){
53678      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53679      return (double)0;
53680    }
53681    assert( pMem->z );
53682    sqlite3AtoF(pMem->z, &val);
53683    return val;
53684  }else{
53685    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53686    return (double)0;
53687  }
53688}
53689
53690/*
53691** The MEM structure is already a MEM_Real.  Try to also make it a
53692** MEM_Int if we can.
53693*/
53694SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
53695  assert( pMem->flags & MEM_Real );
53696  assert( (pMem->flags & MEM_RowSet)==0 );
53697  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53698  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53699
53700  pMem->u.i = doubleToInt64(pMem->r);
53701
53702  /* Only mark the value as an integer if
53703  **
53704  **    (1) the round-trip conversion real->int->real is a no-op, and
53705  **    (2) The integer is neither the largest nor the smallest
53706  **        possible integer (ticket #3922)
53707  **
53708  ** The second and third terms in the following conditional enforces
53709  ** the second condition under the assumption that addition overflow causes
53710  ** values to wrap around.  On x86 hardware, the third term is always
53711  ** true and could be omitted.  But we leave it in because other
53712  ** architectures might behave differently.
53713  */
53714  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
53715      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
53716    pMem->flags |= MEM_Int;
53717  }
53718}
53719
53720/*
53721** Convert pMem to type integer.  Invalidate any prior representations.
53722*/
53723SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
53724  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53725  assert( (pMem->flags & MEM_RowSet)==0 );
53726  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53727
53728  pMem->u.i = sqlite3VdbeIntValue(pMem);
53729  MemSetTypeFlag(pMem, MEM_Int);
53730  return SQLITE_OK;
53731}
53732
53733/*
53734** Convert pMem so that it is of type MEM_Real.
53735** Invalidate any prior representations.
53736*/
53737SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
53738  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53739  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
53740
53741  pMem->r = sqlite3VdbeRealValue(pMem);
53742  MemSetTypeFlag(pMem, MEM_Real);
53743  return SQLITE_OK;
53744}
53745
53746/*
53747** Convert pMem so that it has types MEM_Real or MEM_Int or both.
53748** Invalidate any prior representations.
53749**
53750** Every effort is made to force the conversion, even if the input
53751** is a string that does not look completely like a number.  Convert
53752** as much of the string as we can and ignore the rest.
53753*/
53754SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
53755  int rc;
53756  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
53757  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
53758  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53759  rc = sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8);
53760  if( rc ) return rc;
53761  rc = sqlite3VdbeMemNulTerminate(pMem);
53762  if( rc ) return rc;
53763  if( sqlite3Atoi64(pMem->z, &pMem->u.i) ){
53764    MemSetTypeFlag(pMem, MEM_Int);
53765  }else{
53766    pMem->r = sqlite3VdbeRealValue(pMem);
53767    MemSetTypeFlag(pMem, MEM_Real);
53768    sqlite3VdbeIntegerAffinity(pMem);
53769  }
53770  return SQLITE_OK;
53771}
53772
53773/*
53774** Delete any previous value and set the value stored in *pMem to NULL.
53775*/
53776SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
53777  if( pMem->flags & MEM_Frame ){
53778    sqlite3VdbeFrameDelete(pMem->u.pFrame);
53779  }
53780  if( pMem->flags & MEM_RowSet ){
53781    sqlite3RowSetClear(pMem->u.pRowSet);
53782  }
53783  MemSetTypeFlag(pMem, MEM_Null);
53784  pMem->type = SQLITE_NULL;
53785}
53786
53787/*
53788** Delete any previous value and set the value to be a BLOB of length
53789** n containing all zeros.
53790*/
53791SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
53792  sqlite3VdbeMemRelease(pMem);
53793  pMem->flags = MEM_Blob|MEM_Zero;
53794  pMem->type = SQLITE_BLOB;
53795  pMem->n = 0;
53796  if( n<0 ) n = 0;
53797  pMem->u.nZero = n;
53798  pMem->enc = SQLITE_UTF8;
53799
53800#ifdef SQLITE_OMIT_INCRBLOB
53801  sqlite3VdbeMemGrow(pMem, n, 0);
53802  if( pMem->z ){
53803    pMem->n = n;
53804    memset(pMem->z, 0, n);
53805  }
53806#endif
53807}
53808
53809/*
53810** Delete any previous value and set the value stored in *pMem to val,
53811** manifest type INTEGER.
53812*/
53813SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
53814  sqlite3VdbeMemRelease(pMem);
53815  pMem->u.i = val;
53816  pMem->flags = MEM_Int;
53817  pMem->type = SQLITE_INTEGER;
53818}
53819
53820#ifndef SQLITE_OMIT_FLOATING_POINT
53821/*
53822** Delete any previous value and set the value stored in *pMem to val,
53823** manifest type REAL.
53824*/
53825SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
53826  if( sqlite3IsNaN(val) ){
53827    sqlite3VdbeMemSetNull(pMem);
53828  }else{
53829    sqlite3VdbeMemRelease(pMem);
53830    pMem->r = val;
53831    pMem->flags = MEM_Real;
53832    pMem->type = SQLITE_FLOAT;
53833  }
53834}
53835#endif
53836
53837/*
53838** Delete any previous value and set the value of pMem to be an
53839** empty boolean index.
53840*/
53841SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
53842  sqlite3 *db = pMem->db;
53843  assert( db!=0 );
53844  assert( (pMem->flags & MEM_RowSet)==0 );
53845  sqlite3VdbeMemRelease(pMem);
53846  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
53847  if( db->mallocFailed ){
53848    pMem->flags = MEM_Null;
53849  }else{
53850    assert( pMem->zMalloc );
53851    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
53852                                       sqlite3DbMallocSize(db, pMem->zMalloc));
53853    assert( pMem->u.pRowSet!=0 );
53854    pMem->flags = MEM_RowSet;
53855  }
53856}
53857
53858/*
53859** Return true if the Mem object contains a TEXT or BLOB that is
53860** too large - whose size exceeds SQLITE_MAX_LENGTH.
53861*/
53862SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
53863  assert( p->db!=0 );
53864  if( p->flags & (MEM_Str|MEM_Blob) ){
53865    int n = p->n;
53866    if( p->flags & MEM_Zero ){
53867      n += p->u.nZero;
53868    }
53869    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
53870  }
53871  return 0;
53872}
53873
53874/*
53875** Size of struct Mem not including the Mem.zMalloc member.
53876*/
53877#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
53878
53879/*
53880** Make an shallow copy of pFrom into pTo.  Prior contents of
53881** pTo are freed.  The pFrom->z field is not duplicated.  If
53882** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
53883** and flags gets srcType (either MEM_Ephem or MEM_Static).
53884*/
53885SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
53886  assert( (pFrom->flags & MEM_RowSet)==0 );
53887  sqlite3VdbeMemReleaseExternal(pTo);
53888  memcpy(pTo, pFrom, MEMCELLSIZE);
53889  pTo->xDel = 0;
53890  if( (pFrom->flags&MEM_Static)==0 ){
53891    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
53892    assert( srcType==MEM_Ephem || srcType==MEM_Static );
53893    pTo->flags |= srcType;
53894  }
53895}
53896
53897/*
53898** Make a full copy of pFrom into pTo.  Prior contents of pTo are
53899** freed before the copy is made.
53900*/
53901SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
53902  int rc = SQLITE_OK;
53903
53904  assert( (pFrom->flags & MEM_RowSet)==0 );
53905  sqlite3VdbeMemReleaseExternal(pTo);
53906  memcpy(pTo, pFrom, MEMCELLSIZE);
53907  pTo->flags &= ~MEM_Dyn;
53908
53909  if( pTo->flags&(MEM_Str|MEM_Blob) ){
53910    if( 0==(pFrom->flags&MEM_Static) ){
53911      pTo->flags |= MEM_Ephem;
53912      rc = sqlite3VdbeMemMakeWriteable(pTo);
53913    }
53914  }
53915
53916  return rc;
53917}
53918
53919/*
53920** Transfer the contents of pFrom to pTo. Any existing value in pTo is
53921** freed. If pFrom contains ephemeral data, a copy is made.
53922**
53923** pFrom contains an SQL NULL when this routine returns.
53924*/
53925SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
53926  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
53927  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
53928  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
53929
53930  sqlite3VdbeMemRelease(pTo);
53931  memcpy(pTo, pFrom, sizeof(Mem));
53932  pFrom->flags = MEM_Null;
53933  pFrom->xDel = 0;
53934  pFrom->zMalloc = 0;
53935}
53936
53937/*
53938** Change the value of a Mem to be a string or a BLOB.
53939**
53940** The memory management strategy depends on the value of the xDel
53941** parameter. If the value passed is SQLITE_TRANSIENT, then the
53942** string is copied into a (possibly existing) buffer managed by the
53943** Mem structure. Otherwise, any existing buffer is freed and the
53944** pointer copied.
53945**
53946** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
53947** size limit) then no memory allocation occurs.  If the string can be
53948** stored without allocating memory, then it is.  If a memory allocation
53949** is required to store the string, then value of pMem is unchanged.  In
53950** either case, SQLITE_TOOBIG is returned.
53951*/
53952SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
53953  Mem *pMem,          /* Memory cell to set to string value */
53954  const char *z,      /* String pointer */
53955  int n,              /* Bytes in string, or negative */
53956  u8 enc,             /* Encoding of z.  0 for BLOBs */
53957  void (*xDel)(void*) /* Destructor function */
53958){
53959  int nByte = n;      /* New value for pMem->n */
53960  int iLimit;         /* Maximum allowed string or blob size */
53961  u16 flags = 0;      /* New value for pMem->flags */
53962
53963  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
53964  assert( (pMem->flags & MEM_RowSet)==0 );
53965
53966  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
53967  if( !z ){
53968    sqlite3VdbeMemSetNull(pMem);
53969    return SQLITE_OK;
53970  }
53971
53972  if( pMem->db ){
53973    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
53974  }else{
53975    iLimit = SQLITE_MAX_LENGTH;
53976  }
53977  flags = (enc==0?MEM_Blob:MEM_Str);
53978  if( nByte<0 ){
53979    assert( enc!=0 );
53980    if( enc==SQLITE_UTF8 ){
53981      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
53982    }else{
53983      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
53984    }
53985    flags |= MEM_Term;
53986  }
53987
53988  /* The following block sets the new values of Mem.z and Mem.xDel. It
53989  ** also sets a flag in local variable "flags" to indicate the memory
53990  ** management (one of MEM_Dyn or MEM_Static).
53991  */
53992  if( xDel==SQLITE_TRANSIENT ){
53993    int nAlloc = nByte;
53994    if( flags&MEM_Term ){
53995      nAlloc += (enc==SQLITE_UTF8?1:2);
53996    }
53997    if( nByte>iLimit ){
53998      return SQLITE_TOOBIG;
53999    }
54000    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
54001      return SQLITE_NOMEM;
54002    }
54003    memcpy(pMem->z, z, nAlloc);
54004  }else if( xDel==SQLITE_DYNAMIC ){
54005    sqlite3VdbeMemRelease(pMem);
54006    pMem->zMalloc = pMem->z = (char *)z;
54007    pMem->xDel = 0;
54008  }else{
54009    sqlite3VdbeMemRelease(pMem);
54010    pMem->z = (char *)z;
54011    pMem->xDel = xDel;
54012    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
54013  }
54014
54015  pMem->n = nByte;
54016  pMem->flags = flags;
54017  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
54018  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
54019
54020#ifndef SQLITE_OMIT_UTF16
54021  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
54022    return SQLITE_NOMEM;
54023  }
54024#endif
54025
54026  if( nByte>iLimit ){
54027    return SQLITE_TOOBIG;
54028  }
54029
54030  return SQLITE_OK;
54031}
54032
54033/*
54034** Compare the values contained by the two memory cells, returning
54035** negative, zero or positive if pMem1 is less than, equal to, or greater
54036** than pMem2. Sorting order is NULL's first, followed by numbers (integers
54037** and reals) sorted numerically, followed by text ordered by the collating
54038** sequence pColl and finally blob's ordered by memcmp().
54039**
54040** Two NULL values are considered equal by this function.
54041*/
54042SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
54043  int rc;
54044  int f1, f2;
54045  int combined_flags;
54046
54047  f1 = pMem1->flags;
54048  f2 = pMem2->flags;
54049  combined_flags = f1|f2;
54050  assert( (combined_flags & MEM_RowSet)==0 );
54051
54052  /* If one value is NULL, it is less than the other. If both values
54053  ** are NULL, return 0.
54054  */
54055  if( combined_flags&MEM_Null ){
54056    return (f2&MEM_Null) - (f1&MEM_Null);
54057  }
54058
54059  /* If one value is a number and the other is not, the number is less.
54060  ** If both are numbers, compare as reals if one is a real, or as integers
54061  ** if both values are integers.
54062  */
54063  if( combined_flags&(MEM_Int|MEM_Real) ){
54064    if( !(f1&(MEM_Int|MEM_Real)) ){
54065      return 1;
54066    }
54067    if( !(f2&(MEM_Int|MEM_Real)) ){
54068      return -1;
54069    }
54070    if( (f1 & f2 & MEM_Int)==0 ){
54071      double r1, r2;
54072      if( (f1&MEM_Real)==0 ){
54073        r1 = (double)pMem1->u.i;
54074      }else{
54075        r1 = pMem1->r;
54076      }
54077      if( (f2&MEM_Real)==0 ){
54078        r2 = (double)pMem2->u.i;
54079      }else{
54080        r2 = pMem2->r;
54081      }
54082      if( r1<r2 ) return -1;
54083      if( r1>r2 ) return 1;
54084      return 0;
54085    }else{
54086      assert( f1&MEM_Int );
54087      assert( f2&MEM_Int );
54088      if( pMem1->u.i < pMem2->u.i ) return -1;
54089      if( pMem1->u.i > pMem2->u.i ) return 1;
54090      return 0;
54091    }
54092  }
54093
54094  /* If one value is a string and the other is a blob, the string is less.
54095  ** If both are strings, compare using the collating functions.
54096  */
54097  if( combined_flags&MEM_Str ){
54098    if( (f1 & MEM_Str)==0 ){
54099      return 1;
54100    }
54101    if( (f2 & MEM_Str)==0 ){
54102      return -1;
54103    }
54104
54105    assert( pMem1->enc==pMem2->enc );
54106    assert( pMem1->enc==SQLITE_UTF8 ||
54107            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
54108
54109    /* The collation sequence must be defined at this point, even if
54110    ** the user deletes the collation sequence after the vdbe program is
54111    ** compiled (this was not always the case).
54112    */
54113    assert( !pColl || pColl->xCmp );
54114
54115    if( pColl ){
54116      if( pMem1->enc==pColl->enc ){
54117        /* The strings are already in the correct encoding.  Call the
54118        ** comparison function directly */
54119        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
54120      }else{
54121        const void *v1, *v2;
54122        int n1, n2;
54123        Mem c1;
54124        Mem c2;
54125        memset(&c1, 0, sizeof(c1));
54126        memset(&c2, 0, sizeof(c2));
54127        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
54128        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
54129        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
54130        n1 = v1==0 ? 0 : c1.n;
54131        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
54132        n2 = v2==0 ? 0 : c2.n;
54133        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
54134        sqlite3VdbeMemRelease(&c1);
54135        sqlite3VdbeMemRelease(&c2);
54136        return rc;
54137      }
54138    }
54139    /* If a NULL pointer was passed as the collate function, fall through
54140    ** to the blob case and use memcmp().  */
54141  }
54142
54143  /* Both values must be blobs.  Compare using memcmp().  */
54144  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
54145  if( rc==0 ){
54146    rc = pMem1->n - pMem2->n;
54147  }
54148  return rc;
54149}
54150
54151/*
54152** Move data out of a btree key or data field and into a Mem structure.
54153** The data or key is taken from the entry that pCur is currently pointing
54154** to.  offset and amt determine what portion of the data or key to retrieve.
54155** key is true to get the key or false to get data.  The result is written
54156** into the pMem element.
54157**
54158** The pMem structure is assumed to be uninitialized.  Any prior content
54159** is overwritten without being freed.
54160**
54161** If this routine fails for any reason (malloc returns NULL or unable
54162** to read from the disk) then the pMem is left in an inconsistent state.
54163*/
54164SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
54165  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
54166  int offset,       /* Offset from the start of data to return bytes from. */
54167  int amt,          /* Number of bytes to return. */
54168  int key,          /* If true, retrieve from the btree key, not data. */
54169  Mem *pMem         /* OUT: Return data in this Mem structure. */
54170){
54171  char *zData;        /* Data from the btree layer */
54172  int available = 0;  /* Number of bytes available on the local btree page */
54173  int rc = SQLITE_OK; /* Return code */
54174
54175  assert( sqlite3BtreeCursorIsValid(pCur) );
54176
54177  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
54178  ** that both the BtShared and database handle mutexes are held. */
54179  assert( (pMem->flags & MEM_RowSet)==0 );
54180  if( key ){
54181    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
54182  }else{
54183    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
54184  }
54185  assert( zData!=0 );
54186
54187  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
54188    sqlite3VdbeMemRelease(pMem);
54189    pMem->z = &zData[offset];
54190    pMem->flags = MEM_Blob|MEM_Ephem;
54191  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
54192    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
54193    pMem->enc = 0;
54194    pMem->type = SQLITE_BLOB;
54195    if( key ){
54196      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
54197    }else{
54198      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
54199    }
54200    pMem->z[amt] = 0;
54201    pMem->z[amt+1] = 0;
54202    if( rc!=SQLITE_OK ){
54203      sqlite3VdbeMemRelease(pMem);
54204    }
54205  }
54206  pMem->n = amt;
54207
54208  return rc;
54209}
54210
54211/* This function is only available internally, it is not part of the
54212** external API. It works in a similar way to sqlite3_value_text(),
54213** except the data returned is in the encoding specified by the second
54214** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
54215** SQLITE_UTF8.
54216**
54217** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
54218** If that is the case, then the result must be aligned on an even byte
54219** boundary.
54220*/
54221SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
54222  if( !pVal ) return 0;
54223
54224  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
54225  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
54226  assert( (pVal->flags & MEM_RowSet)==0 );
54227
54228  if( pVal->flags&MEM_Null ){
54229    return 0;
54230  }
54231  assert( (MEM_Blob>>3) == MEM_Str );
54232  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
54233  expandBlob(pVal);
54234  if( pVal->flags&MEM_Str ){
54235    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
54236    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
54237      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
54238      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
54239        return 0;
54240      }
54241    }
54242    sqlite3VdbeMemNulTerminate(pVal);
54243  }else{
54244    assert( (pVal->flags&MEM_Blob)==0 );
54245    sqlite3VdbeMemStringify(pVal, enc);
54246    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
54247  }
54248  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
54249              || pVal->db->mallocFailed );
54250  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
54251    return pVal->z;
54252  }else{
54253    return 0;
54254  }
54255}
54256
54257/*
54258** Create a new sqlite3_value object.
54259*/
54260SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
54261  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
54262  if( p ){
54263    p->flags = MEM_Null;
54264    p->type = SQLITE_NULL;
54265    p->db = db;
54266  }
54267  return p;
54268}
54269
54270/*
54271** Create a new sqlite3_value object, containing the value of pExpr.
54272**
54273** This only works for very simple expressions that consist of one constant
54274** token (i.e. "5", "5.1", "'a string'"). If the expression can
54275** be converted directly into a value, then the value is allocated and
54276** a pointer written to *ppVal. The caller is responsible for deallocating
54277** the value by passing it to sqlite3ValueFree() later on. If the expression
54278** cannot be converted to a value, then *ppVal is set to NULL.
54279*/
54280SQLITE_PRIVATE int sqlite3ValueFromExpr(
54281  sqlite3 *db,              /* The database connection */
54282  Expr *pExpr,              /* The expression to evaluate */
54283  u8 enc,                   /* Encoding to use */
54284  u8 affinity,              /* Affinity to use */
54285  sqlite3_value **ppVal     /* Write the new value here */
54286){
54287  int op;
54288  char *zVal = 0;
54289  sqlite3_value *pVal = 0;
54290
54291  if( !pExpr ){
54292    *ppVal = 0;
54293    return SQLITE_OK;
54294  }
54295  op = pExpr->op;
54296
54297  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
54298  ** The ifdef here is to enable us to achieve 100% branch test coverage even
54299  ** when SQLITE_ENABLE_STAT2 is omitted.
54300  */
54301#ifdef SQLITE_ENABLE_STAT2
54302  if( op==TK_REGISTER ) op = pExpr->op2;
54303#else
54304  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
54305#endif
54306
54307  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
54308    pVal = sqlite3ValueNew(db);
54309    if( pVal==0 ) goto no_mem;
54310    if( ExprHasProperty(pExpr, EP_IntValue) ){
54311      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
54312    }else{
54313      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
54314      if( zVal==0 ) goto no_mem;
54315      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
54316      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
54317    }
54318    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
54319      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
54320    }else{
54321      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
54322    }
54323    if( enc!=SQLITE_UTF8 ){
54324      sqlite3VdbeChangeEncoding(pVal, enc);
54325    }
54326  }else if( op==TK_UMINUS ) {
54327    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
54328      pVal->u.i = -1 * pVal->u.i;
54329      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
54330      pVal->r = (double)-1 * pVal->r;
54331    }
54332  }
54333#ifndef SQLITE_OMIT_BLOB_LITERAL
54334  else if( op==TK_BLOB ){
54335    int nVal;
54336    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
54337    assert( pExpr->u.zToken[1]=='\'' );
54338    pVal = sqlite3ValueNew(db);
54339    if( !pVal ) goto no_mem;
54340    zVal = &pExpr->u.zToken[2];
54341    nVal = sqlite3Strlen30(zVal)-1;
54342    assert( zVal[nVal]=='\'' );
54343    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
54344                         0, SQLITE_DYNAMIC);
54345  }
54346#endif
54347
54348  if( pVal ){
54349    sqlite3VdbeMemStoreType(pVal);
54350  }
54351  *ppVal = pVal;
54352  return SQLITE_OK;
54353
54354no_mem:
54355  db->mallocFailed = 1;
54356  sqlite3DbFree(db, zVal);
54357  sqlite3ValueFree(pVal);
54358  *ppVal = 0;
54359  return SQLITE_NOMEM;
54360}
54361
54362/*
54363** Change the string value of an sqlite3_value object
54364*/
54365SQLITE_PRIVATE void sqlite3ValueSetStr(
54366  sqlite3_value *v,     /* Value to be set */
54367  int n,                /* Length of string z */
54368  const void *z,        /* Text of the new string */
54369  u8 enc,               /* Encoding to use */
54370  void (*xDel)(void*)   /* Destructor for the string */
54371){
54372  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
54373}
54374
54375/*
54376** Free an sqlite3_value object
54377*/
54378SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
54379  if( !v ) return;
54380  sqlite3VdbeMemRelease((Mem *)v);
54381  sqlite3DbFree(((Mem*)v)->db, v);
54382}
54383
54384/*
54385** Return the number of bytes in the sqlite3_value object assuming
54386** that it uses the encoding "enc"
54387*/
54388SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
54389  Mem *p = (Mem*)pVal;
54390  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
54391    if( p->flags & MEM_Zero ){
54392      return p->n + p->u.nZero;
54393    }else{
54394      return p->n;
54395    }
54396  }
54397  return 0;
54398}
54399
54400/************** End of vdbemem.c *********************************************/
54401/************** Begin file vdbeaux.c *****************************************/
54402/*
54403** 2003 September 6
54404**
54405** The author disclaims copyright to this source code.  In place of
54406** a legal notice, here is a blessing:
54407**
54408**    May you do good and not evil.
54409**    May you find forgiveness for yourself and forgive others.
54410**    May you share freely, never taking more than you give.
54411**
54412*************************************************************************
54413** This file contains code used for creating, destroying, and populating
54414** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
54415** to version 2.8.7, all this code was combined into the vdbe.c source file.
54416** But that file was getting too big so this subroutines were split out.
54417*/
54418
54419
54420
54421/*
54422** When debugging the code generator in a symbolic debugger, one can
54423** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
54424** as they are added to the instruction stream.
54425*/
54426#ifdef SQLITE_DEBUG
54427SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
54428#endif
54429
54430
54431/*
54432** Create a new virtual database engine.
54433*/
54434SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
54435  Vdbe *p;
54436  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
54437  if( p==0 ) return 0;
54438  p->db = db;
54439  if( db->pVdbe ){
54440    db->pVdbe->pPrev = p;
54441  }
54442  p->pNext = db->pVdbe;
54443  p->pPrev = 0;
54444  db->pVdbe = p;
54445  p->magic = VDBE_MAGIC_INIT;
54446  return p;
54447}
54448
54449/*
54450** Remember the SQL string for a prepared statement.
54451*/
54452SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
54453  assert( isPrepareV2==1 || isPrepareV2==0 );
54454  if( p==0 ) return;
54455#ifdef SQLITE_OMIT_TRACE
54456  if( !isPrepareV2 ) return;
54457#endif
54458  assert( p->zSql==0 );
54459  p->zSql = sqlite3DbStrNDup(p->db, z, n);
54460  p->isPrepareV2 = (u8)isPrepareV2;
54461}
54462
54463/*
54464** Return the SQL associated with a prepared statement
54465*/
54466SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
54467  Vdbe *p = (Vdbe *)pStmt;
54468  return (p && p->isPrepareV2) ? p->zSql : 0;
54469}
54470
54471/*
54472** Swap all content between two VDBE structures.
54473*/
54474SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
54475  Vdbe tmp, *pTmp;
54476  char *zTmp;
54477  tmp = *pA;
54478  *pA = *pB;
54479  *pB = tmp;
54480  pTmp = pA->pNext;
54481  pA->pNext = pB->pNext;
54482  pB->pNext = pTmp;
54483  pTmp = pA->pPrev;
54484  pA->pPrev = pB->pPrev;
54485  pB->pPrev = pTmp;
54486  zTmp = pA->zSql;
54487  pA->zSql = pB->zSql;
54488  pB->zSql = zTmp;
54489  pB->isPrepareV2 = pA->isPrepareV2;
54490}
54491
54492#ifdef SQLITE_DEBUG
54493/*
54494** Turn tracing on or off
54495*/
54496SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
54497  p->trace = trace;
54498}
54499#endif
54500
54501/*
54502** Resize the Vdbe.aOp array so that it is at least one op larger than
54503** it was.
54504**
54505** If an out-of-memory error occurs while resizing the array, return
54506** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
54507** unchanged (this is so that any opcodes already allocated can be
54508** correctly deallocated along with the rest of the Vdbe).
54509*/
54510static int growOpArray(Vdbe *p){
54511  VdbeOp *pNew;
54512  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
54513  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
54514  if( pNew ){
54515    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
54516    p->aOp = pNew;
54517  }
54518  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
54519}
54520
54521/*
54522** Add a new instruction to the list of instructions current in the
54523** VDBE.  Return the address of the new instruction.
54524**
54525** Parameters:
54526**
54527**    p               Pointer to the VDBE
54528**
54529**    op              The opcode for this instruction
54530**
54531**    p1, p2, p3      Operands
54532**
54533** Use the sqlite3VdbeResolveLabel() function to fix an address and
54534** the sqlite3VdbeChangeP4() function to change the value of the P4
54535** operand.
54536*/
54537SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
54538  int i;
54539  VdbeOp *pOp;
54540
54541  i = p->nOp;
54542  assert( p->magic==VDBE_MAGIC_INIT );
54543  assert( op>0 && op<0xff );
54544  if( p->nOpAlloc<=i ){
54545    if( growOpArray(p) ){
54546      return 1;
54547    }
54548  }
54549  p->nOp++;
54550  pOp = &p->aOp[i];
54551  pOp->opcode = (u8)op;
54552  pOp->p5 = 0;
54553  pOp->p1 = p1;
54554  pOp->p2 = p2;
54555  pOp->p3 = p3;
54556  pOp->p4.p = 0;
54557  pOp->p4type = P4_NOTUSED;
54558  p->expired = 0;
54559#ifdef SQLITE_DEBUG
54560  pOp->zComment = 0;
54561  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
54562#endif
54563#ifdef VDBE_PROFILE
54564  pOp->cycles = 0;
54565  pOp->cnt = 0;
54566#endif
54567  return i;
54568}
54569SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
54570  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
54571}
54572SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
54573  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
54574}
54575SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
54576  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
54577}
54578
54579
54580/*
54581** Add an opcode that includes the p4 value as a pointer.
54582*/
54583SQLITE_PRIVATE int sqlite3VdbeAddOp4(
54584  Vdbe *p,            /* Add the opcode to this VM */
54585  int op,             /* The new opcode */
54586  int p1,             /* The P1 operand */
54587  int p2,             /* The P2 operand */
54588  int p3,             /* The P3 operand */
54589  const char *zP4,    /* The P4 operand */
54590  int p4type          /* P4 operand type */
54591){
54592  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
54593  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
54594  return addr;
54595}
54596
54597/*
54598** Add an opcode that includes the p4 value as an integer.
54599*/
54600SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
54601  Vdbe *p,            /* Add the opcode to this VM */
54602  int op,             /* The new opcode */
54603  int p1,             /* The P1 operand */
54604  int p2,             /* The P2 operand */
54605  int p3,             /* The P3 operand */
54606  int p4              /* The P4 operand as an integer */
54607){
54608  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
54609  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
54610  return addr;
54611}
54612
54613/*
54614** Create a new symbolic label for an instruction that has yet to be
54615** coded.  The symbolic label is really just a negative number.  The
54616** label can be used as the P2 value of an operation.  Later, when
54617** the label is resolved to a specific address, the VDBE will scan
54618** through its operation list and change all values of P2 which match
54619** the label into the resolved address.
54620**
54621** The VDBE knows that a P2 value is a label because labels are
54622** always negative and P2 values are suppose to be non-negative.
54623** Hence, a negative P2 value is a label that has yet to be resolved.
54624**
54625** Zero is returned if a malloc() fails.
54626*/
54627SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
54628  int i;
54629  i = p->nLabel++;
54630  assert( p->magic==VDBE_MAGIC_INIT );
54631  if( i>=p->nLabelAlloc ){
54632    int n = p->nLabelAlloc*2 + 5;
54633    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
54634                                       n*sizeof(p->aLabel[0]));
54635    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
54636  }
54637  if( p->aLabel ){
54638    p->aLabel[i] = -1;
54639  }
54640  return -1-i;
54641}
54642
54643/*
54644** Resolve label "x" to be the address of the next instruction to
54645** be inserted.  The parameter "x" must have been obtained from
54646** a prior call to sqlite3VdbeMakeLabel().
54647*/
54648SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
54649  int j = -1-x;
54650  assert( p->magic==VDBE_MAGIC_INIT );
54651  assert( j>=0 && j<p->nLabel );
54652  if( p->aLabel ){
54653    p->aLabel[j] = p->nOp;
54654  }
54655}
54656
54657/*
54658** Mark the VDBE as one that can only be run one time.
54659*/
54660SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
54661  p->runOnlyOnce = 1;
54662}
54663
54664#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
54665
54666/*
54667** The following type and function are used to iterate through all opcodes
54668** in a Vdbe main program and each of the sub-programs (triggers) it may
54669** invoke directly or indirectly. It should be used as follows:
54670**
54671**   Op *pOp;
54672**   VdbeOpIter sIter;
54673**
54674**   memset(&sIter, 0, sizeof(sIter));
54675**   sIter.v = v;                            // v is of type Vdbe*
54676**   while( (pOp = opIterNext(&sIter)) ){
54677**     // Do something with pOp
54678**   }
54679**   sqlite3DbFree(v->db, sIter.apSub);
54680**
54681*/
54682typedef struct VdbeOpIter VdbeOpIter;
54683struct VdbeOpIter {
54684  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
54685  SubProgram **apSub;        /* Array of subprograms */
54686  int nSub;                  /* Number of entries in apSub */
54687  int iAddr;                 /* Address of next instruction to return */
54688  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
54689};
54690static Op *opIterNext(VdbeOpIter *p){
54691  Vdbe *v = p->v;
54692  Op *pRet = 0;
54693  Op *aOp;
54694  int nOp;
54695
54696  if( p->iSub<=p->nSub ){
54697
54698    if( p->iSub==0 ){
54699      aOp = v->aOp;
54700      nOp = v->nOp;
54701    }else{
54702      aOp = p->apSub[p->iSub-1]->aOp;
54703      nOp = p->apSub[p->iSub-1]->nOp;
54704    }
54705    assert( p->iAddr<nOp );
54706
54707    pRet = &aOp[p->iAddr];
54708    p->iAddr++;
54709    if( p->iAddr==nOp ){
54710      p->iSub++;
54711      p->iAddr = 0;
54712    }
54713
54714    if( pRet->p4type==P4_SUBPROGRAM ){
54715      int nByte = (p->nSub+1)*sizeof(SubProgram*);
54716      int j;
54717      for(j=0; j<p->nSub; j++){
54718        if( p->apSub[j]==pRet->p4.pProgram ) break;
54719      }
54720      if( j==p->nSub ){
54721        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
54722        if( !p->apSub ){
54723          pRet = 0;
54724        }else{
54725          p->apSub[p->nSub++] = pRet->p4.pProgram;
54726        }
54727      }
54728    }
54729  }
54730
54731  return pRet;
54732}
54733
54734/*
54735** Check if the program stored in the VM associated with pParse may
54736** throw an ABORT exception (causing the statement, but not entire transaction
54737** to be rolled back). This condition is true if the main program or any
54738** sub-programs contains any of the following:
54739**
54740**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
54741**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
54742**   *  OP_Destroy
54743**   *  OP_VUpdate
54744**   *  OP_VRename
54745**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
54746**
54747** Then check that the value of Parse.mayAbort is true if an
54748** ABORT may be thrown, or false otherwise. Return true if it does
54749** match, or false otherwise. This function is intended to be used as
54750** part of an assert statement in the compiler. Similar to:
54751**
54752**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
54753*/
54754SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
54755  int hasAbort = 0;
54756  Op *pOp;
54757  VdbeOpIter sIter;
54758  memset(&sIter, 0, sizeof(sIter));
54759  sIter.v = v;
54760
54761  while( (pOp = opIterNext(&sIter))!=0 ){
54762    int opcode = pOp->opcode;
54763    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
54764#ifndef SQLITE_OMIT_FOREIGN_KEY
54765     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
54766#endif
54767     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
54768      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
54769    ){
54770      hasAbort = 1;
54771      break;
54772    }
54773  }
54774  sqlite3DbFree(v->db, sIter.apSub);
54775
54776  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
54777  ** If malloc failed, then the while() loop above may not have iterated
54778  ** through all opcodes and hasAbort may be set incorrectly. Return
54779  ** true for this case to prevent the assert() in the callers frame
54780  ** from failing.  */
54781  return ( v->db->mallocFailed || hasAbort==mayAbort );
54782}
54783#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
54784
54785/*
54786** Loop through the program looking for P2 values that are negative
54787** on jump instructions.  Each such value is a label.  Resolve the
54788** label by setting the P2 value to its correct non-zero value.
54789**
54790** This routine is called once after all opcodes have been inserted.
54791**
54792** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
54793** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
54794** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
54795**
54796** The Op.opflags field is set on all opcodes.
54797*/
54798static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
54799  int i;
54800  int nMaxArgs = *pMaxFuncArgs;
54801  Op *pOp;
54802  int *aLabel = p->aLabel;
54803  p->readOnly = 1;
54804  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
54805    u8 opcode = pOp->opcode;
54806
54807    pOp->opflags = sqlite3OpcodeProperty[opcode];
54808    if( opcode==OP_Function || opcode==OP_AggStep ){
54809      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
54810    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
54811      p->readOnly = 0;
54812#ifndef SQLITE_OMIT_VIRTUALTABLE
54813    }else if( opcode==OP_VUpdate ){
54814      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
54815    }else if( opcode==OP_VFilter ){
54816      int n;
54817      assert( p->nOp - i >= 3 );
54818      assert( pOp[-1].opcode==OP_Integer );
54819      n = pOp[-1].p1;
54820      if( n>nMaxArgs ) nMaxArgs = n;
54821#endif
54822    }
54823
54824    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
54825      assert( -1-pOp->p2<p->nLabel );
54826      pOp->p2 = aLabel[-1-pOp->p2];
54827    }
54828  }
54829  sqlite3DbFree(p->db, p->aLabel);
54830  p->aLabel = 0;
54831
54832  *pMaxFuncArgs = nMaxArgs;
54833}
54834
54835/*
54836** Return the address of the next instruction to be inserted.
54837*/
54838SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
54839  assert( p->magic==VDBE_MAGIC_INIT );
54840  return p->nOp;
54841}
54842
54843/*
54844** This function returns a pointer to the array of opcodes associated with
54845** the Vdbe passed as the first argument. It is the callers responsibility
54846** to arrange for the returned array to be eventually freed using the
54847** vdbeFreeOpArray() function.
54848**
54849** Before returning, *pnOp is set to the number of entries in the returned
54850** array. Also, *pnMaxArg is set to the larger of its current value and
54851** the number of entries in the Vdbe.apArg[] array required to execute the
54852** returned program.
54853*/
54854SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
54855  VdbeOp *aOp = p->aOp;
54856  assert( aOp && !p->db->mallocFailed );
54857
54858  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
54859  assert( p->aMutex.nMutex==0 );
54860
54861  resolveP2Values(p, pnMaxArg);
54862  *pnOp = p->nOp;
54863  p->aOp = 0;
54864  return aOp;
54865}
54866
54867/*
54868** Add a whole list of operations to the operation stack.  Return the
54869** address of the first operation added.
54870*/
54871SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
54872  int addr;
54873  assert( p->magic==VDBE_MAGIC_INIT );
54874  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
54875    return 0;
54876  }
54877  addr = p->nOp;
54878  if( ALWAYS(nOp>0) ){
54879    int i;
54880    VdbeOpList const *pIn = aOp;
54881    for(i=0; i<nOp; i++, pIn++){
54882      int p2 = pIn->p2;
54883      VdbeOp *pOut = &p->aOp[i+addr];
54884      pOut->opcode = pIn->opcode;
54885      pOut->p1 = pIn->p1;
54886      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
54887        pOut->p2 = addr + ADDR(p2);
54888      }else{
54889        pOut->p2 = p2;
54890      }
54891      pOut->p3 = pIn->p3;
54892      pOut->p4type = P4_NOTUSED;
54893      pOut->p4.p = 0;
54894      pOut->p5 = 0;
54895#ifdef SQLITE_DEBUG
54896      pOut->zComment = 0;
54897      if( sqlite3VdbeAddopTrace ){
54898        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
54899      }
54900#endif
54901    }
54902    p->nOp += nOp;
54903  }
54904  return addr;
54905}
54906
54907/*
54908** Change the value of the P1 operand for a specific instruction.
54909** This routine is useful when a large program is loaded from a
54910** static array using sqlite3VdbeAddOpList but we want to make a
54911** few minor changes to the program.
54912*/
54913SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
54914  assert( p!=0 );
54915  assert( addr>=0 );
54916  if( p->nOp>addr ){
54917    p->aOp[addr].p1 = val;
54918  }
54919}
54920
54921/*
54922** Change the value of the P2 operand for a specific instruction.
54923** This routine is useful for setting a jump destination.
54924*/
54925SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
54926  assert( p!=0 );
54927  assert( addr>=0 );
54928  if( p->nOp>addr ){
54929    p->aOp[addr].p2 = val;
54930  }
54931}
54932
54933/*
54934** Change the value of the P3 operand for a specific instruction.
54935*/
54936SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
54937  assert( p!=0 );
54938  assert( addr>=0 );
54939  if( p->nOp>addr ){
54940    p->aOp[addr].p3 = val;
54941  }
54942}
54943
54944/*
54945** Change the value of the P5 operand for the most recently
54946** added operation.
54947*/
54948SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
54949  assert( p!=0 );
54950  if( p->aOp ){
54951    assert( p->nOp>0 );
54952    p->aOp[p->nOp-1].p5 = val;
54953  }
54954}
54955
54956/*
54957** Change the P2 operand of instruction addr so that it points to
54958** the address of the next instruction to be coded.
54959*/
54960SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
54961  sqlite3VdbeChangeP2(p, addr, p->nOp);
54962}
54963
54964
54965/*
54966** If the input FuncDef structure is ephemeral, then free it.  If
54967** the FuncDef is not ephermal, then do nothing.
54968*/
54969static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
54970  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
54971    sqlite3DbFree(db, pDef);
54972  }
54973}
54974
54975static void vdbeFreeOpArray(sqlite3 *, Op *, int);
54976
54977/*
54978** Delete a P4 value if necessary.
54979*/
54980static void freeP4(sqlite3 *db, int p4type, void *p4){
54981  if( p4 ){
54982    assert( db );
54983    switch( p4type ){
54984      case P4_REAL:
54985      case P4_INT64:
54986      case P4_DYNAMIC:
54987      case P4_KEYINFO:
54988      case P4_INTARRAY:
54989      case P4_KEYINFO_HANDOFF: {
54990        sqlite3DbFree(db, p4);
54991        break;
54992      }
54993      case P4_MPRINTF: {
54994        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
54995        break;
54996      }
54997      case P4_VDBEFUNC: {
54998        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
54999        freeEphemeralFunction(db, pVdbeFunc->pFunc);
55000        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
55001        sqlite3DbFree(db, pVdbeFunc);
55002        break;
55003      }
55004      case P4_FUNCDEF: {
55005        freeEphemeralFunction(db, (FuncDef*)p4);
55006        break;
55007      }
55008      case P4_MEM: {
55009        if( db->pnBytesFreed==0 ){
55010          sqlite3ValueFree((sqlite3_value*)p4);
55011        }else{
55012          Mem *p = (Mem*)p4;
55013          sqlite3DbFree(db, p->zMalloc);
55014          sqlite3DbFree(db, p);
55015        }
55016        break;
55017      }
55018      case P4_VTAB : {
55019        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
55020        break;
55021      }
55022    }
55023  }
55024}
55025
55026/*
55027** Free the space allocated for aOp and any p4 values allocated for the
55028** opcodes contained within. If aOp is not NULL it is assumed to contain
55029** nOp entries.
55030*/
55031static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
55032  if( aOp ){
55033    Op *pOp;
55034    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
55035      freeP4(db, pOp->p4type, pOp->p4.p);
55036#ifdef SQLITE_DEBUG
55037      sqlite3DbFree(db, pOp->zComment);
55038#endif
55039    }
55040  }
55041  sqlite3DbFree(db, aOp);
55042}
55043
55044/*
55045** Link the SubProgram object passed as the second argument into the linked
55046** list at Vdbe.pSubProgram. This list is used to delete all sub-program
55047** objects when the VM is no longer required.
55048*/
55049SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
55050  p->pNext = pVdbe->pProgram;
55051  pVdbe->pProgram = p;
55052}
55053
55054/*
55055** Change N opcodes starting at addr to No-ops.
55056*/
55057SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
55058  if( p->aOp ){
55059    VdbeOp *pOp = &p->aOp[addr];
55060    sqlite3 *db = p->db;
55061    while( N-- ){
55062      freeP4(db, pOp->p4type, pOp->p4.p);
55063      memset(pOp, 0, sizeof(pOp[0]));
55064      pOp->opcode = OP_Noop;
55065      pOp++;
55066    }
55067  }
55068}
55069
55070/*
55071** Change the value of the P4 operand for a specific instruction.
55072** This routine is useful when a large program is loaded from a
55073** static array using sqlite3VdbeAddOpList but we want to make a
55074** few minor changes to the program.
55075**
55076** If n>=0 then the P4 operand is dynamic, meaning that a copy of
55077** the string is made into memory obtained from sqlite3_malloc().
55078** A value of n==0 means copy bytes of zP4 up to and including the
55079** first null byte.  If n>0 then copy n+1 bytes of zP4.
55080**
55081** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
55082** A copy is made of the KeyInfo structure into memory obtained from
55083** sqlite3_malloc, to be freed when the Vdbe is finalized.
55084** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
55085** stored in memory that the caller has obtained from sqlite3_malloc. The
55086** caller should not free the allocation, it will be freed when the Vdbe is
55087** finalized.
55088**
55089** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
55090** to a string or structure that is guaranteed to exist for the lifetime of
55091** the Vdbe. In these cases we can just copy the pointer.
55092**
55093** If addr<0 then change P4 on the most recently inserted instruction.
55094*/
55095SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
55096  Op *pOp;
55097  sqlite3 *db;
55098  assert( p!=0 );
55099  db = p->db;
55100  assert( p->magic==VDBE_MAGIC_INIT );
55101  if( p->aOp==0 || db->mallocFailed ){
55102    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
55103      freeP4(db, n, (void*)*(char**)&zP4);
55104    }
55105    return;
55106  }
55107  assert( p->nOp>0 );
55108  assert( addr<p->nOp );
55109  if( addr<0 ){
55110    addr = p->nOp - 1;
55111  }
55112  pOp = &p->aOp[addr];
55113  freeP4(db, pOp->p4type, pOp->p4.p);
55114  pOp->p4.p = 0;
55115  if( n==P4_INT32 ){
55116    /* Note: this cast is safe, because the origin data point was an int
55117    ** that was cast to a (const char *). */
55118    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
55119    pOp->p4type = P4_INT32;
55120  }else if( zP4==0 ){
55121    pOp->p4.p = 0;
55122    pOp->p4type = P4_NOTUSED;
55123  }else if( n==P4_KEYINFO ){
55124    KeyInfo *pKeyInfo;
55125    int nField, nByte;
55126
55127    nField = ((KeyInfo*)zP4)->nField;
55128    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
55129    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
55130    pOp->p4.pKeyInfo = pKeyInfo;
55131    if( pKeyInfo ){
55132      u8 *aSortOrder;
55133      memcpy((char*)pKeyInfo, zP4, nByte - nField);
55134      aSortOrder = pKeyInfo->aSortOrder;
55135      if( aSortOrder ){
55136        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
55137        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
55138      }
55139      pOp->p4type = P4_KEYINFO;
55140    }else{
55141      p->db->mallocFailed = 1;
55142      pOp->p4type = P4_NOTUSED;
55143    }
55144  }else if( n==P4_KEYINFO_HANDOFF ){
55145    pOp->p4.p = (void*)zP4;
55146    pOp->p4type = P4_KEYINFO;
55147  }else if( n==P4_VTAB ){
55148    pOp->p4.p = (void*)zP4;
55149    pOp->p4type = P4_VTAB;
55150    sqlite3VtabLock((VTable *)zP4);
55151    assert( ((VTable *)zP4)->db==p->db );
55152  }else if( n<0 ){
55153    pOp->p4.p = (void*)zP4;
55154    pOp->p4type = (signed char)n;
55155  }else{
55156    if( n==0 ) n = sqlite3Strlen30(zP4);
55157    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
55158    pOp->p4type = P4_DYNAMIC;
55159  }
55160}
55161
55162#ifndef NDEBUG
55163/*
55164** Change the comment on the the most recently coded instruction.  Or
55165** insert a No-op and add the comment to that new instruction.  This
55166** makes the code easier to read during debugging.  None of this happens
55167** in a production build.
55168*/
55169SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
55170  va_list ap;
55171  if( !p ) return;
55172  assert( p->nOp>0 || p->aOp==0 );
55173  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
55174  if( p->nOp ){
55175    char **pz = &p->aOp[p->nOp-1].zComment;
55176    va_start(ap, zFormat);
55177    sqlite3DbFree(p->db, *pz);
55178    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
55179    va_end(ap);
55180  }
55181}
55182SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
55183  va_list ap;
55184  if( !p ) return;
55185  sqlite3VdbeAddOp0(p, OP_Noop);
55186  assert( p->nOp>0 || p->aOp==0 );
55187  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
55188  if( p->nOp ){
55189    char **pz = &p->aOp[p->nOp-1].zComment;
55190    va_start(ap, zFormat);
55191    sqlite3DbFree(p->db, *pz);
55192    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
55193    va_end(ap);
55194  }
55195}
55196#endif  /* NDEBUG */
55197
55198/*
55199** Return the opcode for a given address.  If the address is -1, then
55200** return the most recently inserted opcode.
55201**
55202** If a memory allocation error has occurred prior to the calling of this
55203** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
55204** is readable but not writable, though it is cast to a writable value.
55205** The return of a dummy opcode allows the call to continue functioning
55206** after a OOM fault without having to check to see if the return from
55207** this routine is a valid pointer.  But because the dummy.opcode is 0,
55208** dummy will never be written to.  This is verified by code inspection and
55209** by running with Valgrind.
55210**
55211** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
55212** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
55213** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
55214** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
55215** having to double-check to make sure that the result is non-negative. But
55216** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
55217** check the value of p->nOp-1 before continuing.
55218*/
55219SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
55220  /* C89 specifies that the constant "dummy" will be initialized to all
55221  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
55222  static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
55223  assert( p->magic==VDBE_MAGIC_INIT );
55224  if( addr<0 ){
55225#ifdef SQLITE_OMIT_TRACE
55226    if( p->nOp==0 ) return (VdbeOp*)&dummy;
55227#endif
55228    addr = p->nOp - 1;
55229  }
55230  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
55231  if( p->db->mallocFailed ){
55232    return (VdbeOp*)&dummy;
55233  }else{
55234    return &p->aOp[addr];
55235  }
55236}
55237
55238#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
55239     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
55240/*
55241** Compute a string that describes the P4 parameter for an opcode.
55242** Use zTemp for any required temporary buffer space.
55243*/
55244static char *displayP4(Op *pOp, char *zTemp, int nTemp){
55245  char *zP4 = zTemp;
55246  assert( nTemp>=20 );
55247  switch( pOp->p4type ){
55248    case P4_KEYINFO_STATIC:
55249    case P4_KEYINFO: {
55250      int i, j;
55251      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
55252      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
55253      i = sqlite3Strlen30(zTemp);
55254      for(j=0; j<pKeyInfo->nField; j++){
55255        CollSeq *pColl = pKeyInfo->aColl[j];
55256        if( pColl ){
55257          int n = sqlite3Strlen30(pColl->zName);
55258          if( i+n>nTemp-6 ){
55259            memcpy(&zTemp[i],",...",4);
55260            break;
55261          }
55262          zTemp[i++] = ',';
55263          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
55264            zTemp[i++] = '-';
55265          }
55266          memcpy(&zTemp[i], pColl->zName,n+1);
55267          i += n;
55268        }else if( i+4<nTemp-6 ){
55269          memcpy(&zTemp[i],",nil",4);
55270          i += 4;
55271        }
55272      }
55273      zTemp[i++] = ')';
55274      zTemp[i] = 0;
55275      assert( i<nTemp );
55276      break;
55277    }
55278    case P4_COLLSEQ: {
55279      CollSeq *pColl = pOp->p4.pColl;
55280      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
55281      break;
55282    }
55283    case P4_FUNCDEF: {
55284      FuncDef *pDef = pOp->p4.pFunc;
55285      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
55286      break;
55287    }
55288    case P4_INT64: {
55289      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
55290      break;
55291    }
55292    case P4_INT32: {
55293      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
55294      break;
55295    }
55296    case P4_REAL: {
55297      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
55298      break;
55299    }
55300    case P4_MEM: {
55301      Mem *pMem = pOp->p4.pMem;
55302      assert( (pMem->flags & MEM_Null)==0 );
55303      if( pMem->flags & MEM_Str ){
55304        zP4 = pMem->z;
55305      }else if( pMem->flags & MEM_Int ){
55306        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
55307      }else if( pMem->flags & MEM_Real ){
55308        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
55309      }else{
55310        assert( pMem->flags & MEM_Blob );
55311        zP4 = "(blob)";
55312      }
55313      break;
55314    }
55315#ifndef SQLITE_OMIT_VIRTUALTABLE
55316    case P4_VTAB: {
55317      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
55318      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
55319      break;
55320    }
55321#endif
55322    case P4_INTARRAY: {
55323      sqlite3_snprintf(nTemp, zTemp, "intarray");
55324      break;
55325    }
55326    case P4_SUBPROGRAM: {
55327      sqlite3_snprintf(nTemp, zTemp, "program");
55328      break;
55329    }
55330    default: {
55331      zP4 = pOp->p4.z;
55332      if( zP4==0 ){
55333        zP4 = zTemp;
55334        zTemp[0] = 0;
55335      }
55336    }
55337  }
55338  assert( zP4!=0 );
55339  return zP4;
55340}
55341#endif
55342
55343/*
55344** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
55345**
55346** The prepared statement has to know in advance which Btree objects
55347** will be used so that it can acquire mutexes on them all in sorted
55348** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
55349** in order (and released in reverse order) to avoid deadlocks.
55350*/
55351SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
55352  int mask;
55353  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
55354  assert( i<(int)sizeof(p->btreeMask)*8 );
55355  mask = ((u32)1)<<i;
55356  if( (p->btreeMask & mask)==0 ){
55357    p->btreeMask |= mask;
55358    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
55359  }
55360}
55361
55362
55363#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
55364/*
55365** Print a single opcode.  This routine is used for debugging only.
55366*/
55367SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
55368  char *zP4;
55369  char zPtr[50];
55370  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
55371  if( pOut==0 ) pOut = stdout;
55372  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
55373  fprintf(pOut, zFormat1, pc,
55374      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
55375#ifdef SQLITE_DEBUG
55376      pOp->zComment ? pOp->zComment : ""
55377#else
55378      ""
55379#endif
55380  );
55381  fflush(pOut);
55382}
55383#endif
55384
55385/*
55386** Release an array of N Mem elements
55387*/
55388static void releaseMemArray(Mem *p, int N){
55389  if( p && N ){
55390    Mem *pEnd;
55391    sqlite3 *db = p->db;
55392    u8 malloc_failed = db->mallocFailed;
55393    if( db->pnBytesFreed ){
55394      for(pEnd=&p[N]; p<pEnd; p++){
55395        sqlite3DbFree(db, p->zMalloc);
55396      }
55397      return;
55398    }
55399    for(pEnd=&p[N]; p<pEnd; p++){
55400      assert( (&p[1])==pEnd || p[0].db==p[1].db );
55401
55402      /* This block is really an inlined version of sqlite3VdbeMemRelease()
55403      ** that takes advantage of the fact that the memory cell value is
55404      ** being set to NULL after releasing any dynamic resources.
55405      **
55406      ** The justification for duplicating code is that according to
55407      ** callgrind, this causes a certain test case to hit the CPU 4.7
55408      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
55409      ** sqlite3MemRelease() were called from here. With -O2, this jumps
55410      ** to 6.6 percent. The test case is inserting 1000 rows into a table
55411      ** with no indexes using a single prepared INSERT statement, bind()
55412      ** and reset(). Inserts are grouped into a transaction.
55413      */
55414      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
55415        sqlite3VdbeMemRelease(p);
55416      }else if( p->zMalloc ){
55417        sqlite3DbFree(db, p->zMalloc);
55418        p->zMalloc = 0;
55419      }
55420
55421      p->flags = MEM_Null;
55422    }
55423    db->mallocFailed = malloc_failed;
55424  }
55425}
55426
55427/*
55428** Delete a VdbeFrame object and its contents. VdbeFrame objects are
55429** allocated by the OP_Program opcode in sqlite3VdbeExec().
55430*/
55431SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
55432  int i;
55433  Mem *aMem = VdbeFrameMem(p);
55434  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
55435  for(i=0; i<p->nChildCsr; i++){
55436    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
55437  }
55438  releaseMemArray(aMem, p->nChildMem);
55439  sqlite3DbFree(p->v->db, p);
55440}
55441
55442#ifndef SQLITE_OMIT_EXPLAIN
55443/*
55444** Give a listing of the program in the virtual machine.
55445**
55446** The interface is the same as sqlite3VdbeExec().  But instead of
55447** running the code, it invokes the callback once for each instruction.
55448** This feature is used to implement "EXPLAIN".
55449**
55450** When p->explain==1, each instruction is listed.  When
55451** p->explain==2, only OP_Explain instructions are listed and these
55452** are shown in a different format.  p->explain==2 is used to implement
55453** EXPLAIN QUERY PLAN.
55454**
55455** When p->explain==1, first the main program is listed, then each of
55456** the trigger subprograms are listed one by one.
55457*/
55458SQLITE_PRIVATE int sqlite3VdbeList(
55459  Vdbe *p                   /* The VDBE */
55460){
55461  int nRow;                            /* Stop when row count reaches this */
55462  int nSub = 0;                        /* Number of sub-vdbes seen so far */
55463  SubProgram **apSub = 0;              /* Array of sub-vdbes */
55464  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
55465  sqlite3 *db = p->db;                 /* The database connection */
55466  int i;                               /* Loop counter */
55467  int rc = SQLITE_OK;                  /* Return code */
55468  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
55469
55470  assert( p->explain );
55471  assert( p->magic==VDBE_MAGIC_RUN );
55472  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
55473
55474  /* Even though this opcode does not use dynamic strings for
55475  ** the result, result columns may become dynamic if the user calls
55476  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
55477  */
55478  releaseMemArray(pMem, 8);
55479
55480  if( p->rc==SQLITE_NOMEM ){
55481    /* This happens if a malloc() inside a call to sqlite3_column_text() or
55482    ** sqlite3_column_text16() failed.  */
55483    db->mallocFailed = 1;
55484    return SQLITE_ERROR;
55485  }
55486
55487  /* When the number of output rows reaches nRow, that means the
55488  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
55489  ** nRow is the sum of the number of rows in the main program, plus
55490  ** the sum of the number of rows in all trigger subprograms encountered
55491  ** so far.  The nRow value will increase as new trigger subprograms are
55492  ** encountered, but p->pc will eventually catch up to nRow.
55493  */
55494  nRow = p->nOp;
55495  if( p->explain==1 ){
55496    /* The first 8 memory cells are used for the result set.  So we will
55497    ** commandeer the 9th cell to use as storage for an array of pointers
55498    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
55499    ** cells.  */
55500    assert( p->nMem>9 );
55501    pSub = &p->aMem[9];
55502    if( pSub->flags&MEM_Blob ){
55503      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
55504      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
55505      nSub = pSub->n/sizeof(Vdbe*);
55506      apSub = (SubProgram **)pSub->z;
55507    }
55508    for(i=0; i<nSub; i++){
55509      nRow += apSub[i]->nOp;
55510    }
55511  }
55512
55513  do{
55514    i = p->pc++;
55515  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
55516  if( i>=nRow ){
55517    p->rc = SQLITE_OK;
55518    rc = SQLITE_DONE;
55519  }else if( db->u1.isInterrupted ){
55520    p->rc = SQLITE_INTERRUPT;
55521    rc = SQLITE_ERROR;
55522    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
55523  }else{
55524    char *z;
55525    Op *pOp;
55526    if( i<p->nOp ){
55527      /* The output line number is small enough that we are still in the
55528      ** main program. */
55529      pOp = &p->aOp[i];
55530    }else{
55531      /* We are currently listing subprograms.  Figure out which one and
55532      ** pick up the appropriate opcode. */
55533      int j;
55534      i -= p->nOp;
55535      for(j=0; i>=apSub[j]->nOp; j++){
55536        i -= apSub[j]->nOp;
55537      }
55538      pOp = &apSub[j]->aOp[i];
55539    }
55540    if( p->explain==1 ){
55541      pMem->flags = MEM_Int;
55542      pMem->type = SQLITE_INTEGER;
55543      pMem->u.i = i;                                /* Program counter */
55544      pMem++;
55545
55546      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
55547      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
55548      assert( pMem->z!=0 );
55549      pMem->n = sqlite3Strlen30(pMem->z);
55550      pMem->type = SQLITE_TEXT;
55551      pMem->enc = SQLITE_UTF8;
55552      pMem++;
55553
55554      /* When an OP_Program opcode is encounter (the only opcode that has
55555      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
55556      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
55557      ** has not already been seen.
55558      */
55559      if( pOp->p4type==P4_SUBPROGRAM ){
55560        int nByte = (nSub+1)*sizeof(SubProgram*);
55561        int j;
55562        for(j=0; j<nSub; j++){
55563          if( apSub[j]==pOp->p4.pProgram ) break;
55564        }
55565        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
55566          apSub = (SubProgram **)pSub->z;
55567          apSub[nSub++] = pOp->p4.pProgram;
55568          pSub->flags |= MEM_Blob;
55569          pSub->n = nSub*sizeof(SubProgram*);
55570        }
55571      }
55572    }
55573
55574    pMem->flags = MEM_Int;
55575    pMem->u.i = pOp->p1;                          /* P1 */
55576    pMem->type = SQLITE_INTEGER;
55577    pMem++;
55578
55579    pMem->flags = MEM_Int;
55580    pMem->u.i = pOp->p2;                          /* P2 */
55581    pMem->type = SQLITE_INTEGER;
55582    pMem++;
55583
55584    if( p->explain==1 ){
55585      pMem->flags = MEM_Int;
55586      pMem->u.i = pOp->p3;                          /* P3 */
55587      pMem->type = SQLITE_INTEGER;
55588      pMem++;
55589    }
55590
55591    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
55592      assert( p->db->mallocFailed );
55593      return SQLITE_ERROR;
55594    }
55595    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
55596    z = displayP4(pOp, pMem->z, 32);
55597    if( z!=pMem->z ){
55598      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
55599    }else{
55600      assert( pMem->z!=0 );
55601      pMem->n = sqlite3Strlen30(pMem->z);
55602      pMem->enc = SQLITE_UTF8;
55603    }
55604    pMem->type = SQLITE_TEXT;
55605    pMem++;
55606
55607    if( p->explain==1 ){
55608      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
55609        assert( p->db->mallocFailed );
55610        return SQLITE_ERROR;
55611      }
55612      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
55613      pMem->n = 2;
55614      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
55615      pMem->type = SQLITE_TEXT;
55616      pMem->enc = SQLITE_UTF8;
55617      pMem++;
55618
55619#ifdef SQLITE_DEBUG
55620      if( pOp->zComment ){
55621        pMem->flags = MEM_Str|MEM_Term;
55622        pMem->z = pOp->zComment;
55623        pMem->n = sqlite3Strlen30(pMem->z);
55624        pMem->enc = SQLITE_UTF8;
55625        pMem->type = SQLITE_TEXT;
55626      }else
55627#endif
55628      {
55629        pMem->flags = MEM_Null;                       /* Comment */
55630        pMem->type = SQLITE_NULL;
55631      }
55632    }
55633
55634    p->nResColumn = 8 - 5*(p->explain-1);
55635    p->rc = SQLITE_OK;
55636    rc = SQLITE_ROW;
55637  }
55638  return rc;
55639}
55640#endif /* SQLITE_OMIT_EXPLAIN */
55641
55642#ifdef SQLITE_DEBUG
55643/*
55644** Print the SQL that was used to generate a VDBE program.
55645*/
55646SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
55647  int nOp = p->nOp;
55648  VdbeOp *pOp;
55649  if( nOp<1 ) return;
55650  pOp = &p->aOp[0];
55651  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
55652    const char *z = pOp->p4.z;
55653    while( sqlite3Isspace(*z) ) z++;
55654    printf("SQL: [%s]\n", z);
55655  }
55656}
55657#endif
55658
55659#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
55660/*
55661** Print an IOTRACE message showing SQL content.
55662*/
55663SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
55664  int nOp = p->nOp;
55665  VdbeOp *pOp;
55666  if( sqlite3IoTrace==0 ) return;
55667  if( nOp<1 ) return;
55668  pOp = &p->aOp[0];
55669  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
55670    int i, j;
55671    char z[1000];
55672    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
55673    for(i=0; sqlite3Isspace(z[i]); i++){}
55674    for(j=0; z[i]; i++){
55675      if( sqlite3Isspace(z[i]) ){
55676        if( z[i-1]!=' ' ){
55677          z[j++] = ' ';
55678        }
55679      }else{
55680        z[j++] = z[i];
55681      }
55682    }
55683    z[j] = 0;
55684    sqlite3IoTrace("SQL %s\n", z);
55685  }
55686}
55687#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
55688
55689/*
55690** Allocate space from a fixed size buffer and return a pointer to
55691** that space.  If insufficient space is available, return NULL.
55692**
55693** The pBuf parameter is the initial value of a pointer which will
55694** receive the new memory.  pBuf is normally NULL.  If pBuf is not
55695** NULL, it means that memory space has already been allocated and that
55696** this routine should not allocate any new memory.  When pBuf is not
55697** NULL simply return pBuf.  Only allocate new memory space when pBuf
55698** is NULL.
55699**
55700** nByte is the number of bytes of space needed.
55701**
55702** *ppFrom points to available space and pEnd points to the end of the
55703** available space.  When space is allocated, *ppFrom is advanced past
55704** the end of the allocated space.
55705**
55706** *pnByte is a counter of the number of bytes of space that have failed
55707** to allocate.  If there is insufficient space in *ppFrom to satisfy the
55708** request, then increment *pnByte by the amount of the request.
55709*/
55710static void *allocSpace(
55711  void *pBuf,          /* Where return pointer will be stored */
55712  int nByte,           /* Number of bytes to allocate */
55713  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
55714  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
55715  int *pnByte          /* If allocation cannot be made, increment *pnByte */
55716){
55717  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
55718  if( pBuf ) return pBuf;
55719  nByte = ROUND8(nByte);
55720  if( &(*ppFrom)[nByte] <= pEnd ){
55721    pBuf = (void*)*ppFrom;
55722    *ppFrom += nByte;
55723  }else{
55724    *pnByte += nByte;
55725  }
55726  return pBuf;
55727}
55728
55729/*
55730** Prepare a virtual machine for execution.  This involves things such
55731** as allocating stack space and initializing the program counter.
55732** After the VDBE has be prepped, it can be executed by one or more
55733** calls to sqlite3VdbeExec().
55734**
55735** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
55736** VDBE_MAGIC_RUN.
55737**
55738** This function may be called more than once on a single virtual machine.
55739** The first call is made while compiling the SQL statement. Subsequent
55740** calls are made as part of the process of resetting a statement to be
55741** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
55742** and isExplain parameters are only passed correct values the first time
55743** the function is called. On subsequent calls, from sqlite3_reset(), nVar
55744** is passed -1 and nMem, nCursor and isExplain are all passed zero.
55745*/
55746SQLITE_PRIVATE void sqlite3VdbeMakeReady(
55747  Vdbe *p,                       /* The VDBE */
55748  int nVar,                      /* Number of '?' see in the SQL statement */
55749  int nMem,                      /* Number of memory cells to allocate */
55750  int nCursor,                   /* Number of cursors to allocate */
55751  int nArg,                      /* Maximum number of args in SubPrograms */
55752  int isExplain,                 /* True if the EXPLAIN keywords is present */
55753  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
55754){
55755  int n;
55756  sqlite3 *db = p->db;
55757
55758  assert( p!=0 );
55759  assert( p->magic==VDBE_MAGIC_INIT );
55760
55761  /* There should be at least one opcode.
55762  */
55763  assert( p->nOp>0 );
55764
55765  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
55766  p->magic = VDBE_MAGIC_RUN;
55767
55768  /* For each cursor required, also allocate a memory cell. Memory
55769  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
55770  ** the vdbe program. Instead they are used to allocate space for
55771  ** VdbeCursor/BtCursor structures. The blob of memory associated with
55772  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
55773  ** stores the blob of memory associated with cursor 1, etc.
55774  **
55775  ** See also: allocateCursor().
55776  */
55777  nMem += nCursor;
55778
55779  /* Allocate space for memory registers, SQL variables, VDBE cursors and
55780  ** an array to marshal SQL function arguments in. This is only done the
55781  ** first time this function is called for a given VDBE, not when it is
55782  ** being called from sqlite3_reset() to reset the virtual machine.
55783  */
55784  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
55785    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
55786    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
55787    int nByte;                              /* How much extra memory needed */
55788
55789    resolveP2Values(p, &nArg);
55790    p->usesStmtJournal = (u8)usesStmtJournal;
55791    if( isExplain && nMem<10 ){
55792      nMem = 10;
55793    }
55794    memset(zCsr, 0, zEnd-zCsr);
55795    zCsr += (zCsr - (u8*)0)&7;
55796    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
55797
55798    /* Memory for registers, parameters, cursor, etc, is allocated in two
55799    ** passes.  On the first pass, we try to reuse unused space at the
55800    ** end of the opcode array.  If we are unable to satisfy all memory
55801    ** requirements by reusing the opcode array tail, then the second
55802    ** pass will fill in the rest using a fresh allocation.
55803    **
55804    ** This two-pass approach that reuses as much memory as possible from
55805    ** the leftover space at the end of the opcode array can significantly
55806    ** reduce the amount of memory held by a prepared statement.
55807    */
55808    do {
55809      nByte = 0;
55810      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
55811      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
55812      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
55813      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
55814      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
55815                            &zCsr, zEnd, &nByte);
55816      if( nByte ){
55817        p->pFree = sqlite3DbMallocZero(db, nByte);
55818      }
55819      zCsr = p->pFree;
55820      zEnd = &zCsr[nByte];
55821    }while( nByte && !db->mallocFailed );
55822
55823    p->nCursor = (u16)nCursor;
55824    if( p->aVar ){
55825      p->nVar = (ynVar)nVar;
55826      for(n=0; n<nVar; n++){
55827        p->aVar[n].flags = MEM_Null;
55828        p->aVar[n].db = db;
55829      }
55830    }
55831    if( p->aMem ){
55832      p->aMem--;                      /* aMem[] goes from 1..nMem */
55833      p->nMem = nMem;                 /*       not from 0..nMem-1 */
55834      for(n=1; n<=nMem; n++){
55835        p->aMem[n].flags = MEM_Null;
55836        p->aMem[n].db = db;
55837      }
55838    }
55839  }
55840#ifdef SQLITE_DEBUG
55841  for(n=1; n<p->nMem; n++){
55842    assert( p->aMem[n].db==db );
55843  }
55844#endif
55845
55846  p->pc = -1;
55847  p->rc = SQLITE_OK;
55848  p->errorAction = OE_Abort;
55849  p->explain |= isExplain;
55850  p->magic = VDBE_MAGIC_RUN;
55851  p->nChange = 0;
55852  p->cacheCtr = 1;
55853  p->minWriteFileFormat = 255;
55854  p->iStatement = 0;
55855  p->nFkConstraint = 0;
55856#ifdef VDBE_PROFILE
55857  {
55858    int i;
55859    for(i=0; i<p->nOp; i++){
55860      p->aOp[i].cnt = 0;
55861      p->aOp[i].cycles = 0;
55862    }
55863  }
55864#endif
55865}
55866
55867/*
55868** Close a VDBE cursor and release all the resources that cursor
55869** happens to hold.
55870*/
55871SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
55872  if( pCx==0 ){
55873    return;
55874  }
55875  if( pCx->pBt ){
55876    sqlite3BtreeClose(pCx->pBt);
55877    /* The pCx->pCursor will be close automatically, if it exists, by
55878    ** the call above. */
55879  }else if( pCx->pCursor ){
55880    sqlite3BtreeCloseCursor(pCx->pCursor);
55881  }
55882#ifndef SQLITE_OMIT_VIRTUALTABLE
55883  if( pCx->pVtabCursor ){
55884    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
55885    const sqlite3_module *pModule = pCx->pModule;
55886    p->inVtabMethod = 1;
55887    pModule->xClose(pVtabCursor);
55888    p->inVtabMethod = 0;
55889  }
55890#endif
55891}
55892
55893/*
55894** Copy the values stored in the VdbeFrame structure to its Vdbe. This
55895** is used, for example, when a trigger sub-program is halted to restore
55896** control to the main program.
55897*/
55898SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
55899  Vdbe *v = pFrame->v;
55900  v->aOp = pFrame->aOp;
55901  v->nOp = pFrame->nOp;
55902  v->aMem = pFrame->aMem;
55903  v->nMem = pFrame->nMem;
55904  v->apCsr = pFrame->apCsr;
55905  v->nCursor = pFrame->nCursor;
55906  v->db->lastRowid = pFrame->lastRowid;
55907  v->nChange = pFrame->nChange;
55908  return pFrame->pc;
55909}
55910
55911/*
55912** Close all cursors.
55913**
55914** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
55915** cell array. This is necessary as the memory cell array may contain
55916** pointers to VdbeFrame objects, which may in turn contain pointers to
55917** open cursors.
55918*/
55919static void closeAllCursors(Vdbe *p){
55920  if( p->pFrame ){
55921    VdbeFrame *pFrame = p->pFrame;
55922    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
55923    sqlite3VdbeFrameRestore(pFrame);
55924  }
55925  p->pFrame = 0;
55926  p->nFrame = 0;
55927
55928  if( p->apCsr ){
55929    int i;
55930    for(i=0; i<p->nCursor; i++){
55931      VdbeCursor *pC = p->apCsr[i];
55932      if( pC ){
55933        sqlite3VdbeFreeCursor(p, pC);
55934        p->apCsr[i] = 0;
55935      }
55936    }
55937  }
55938  if( p->aMem ){
55939    releaseMemArray(&p->aMem[1], p->nMem);
55940  }
55941}
55942
55943/*
55944** Clean up the VM after execution.
55945**
55946** This routine will automatically close any cursors, lists, and/or
55947** sorters that were left open.  It also deletes the values of
55948** variables in the aVar[] array.
55949*/
55950static void Cleanup(Vdbe *p){
55951  sqlite3 *db = p->db;
55952
55953#ifdef SQLITE_DEBUG
55954  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
55955  ** Vdbe.aMem[] arrays have already been cleaned up.  */
55956  int i;
55957  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
55958  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
55959#endif
55960
55961  sqlite3DbFree(db, p->zErrMsg);
55962  p->zErrMsg = 0;
55963  p->pResultSet = 0;
55964}
55965
55966/*
55967** Set the number of result columns that will be returned by this SQL
55968** statement. This is now set at compile time, rather than during
55969** execution of the vdbe program so that sqlite3_column_count() can
55970** be called on an SQL statement before sqlite3_step().
55971*/
55972SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
55973  Mem *pColName;
55974  int n;
55975  sqlite3 *db = p->db;
55976
55977  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
55978  sqlite3DbFree(db, p->aColName);
55979  n = nResColumn*COLNAME_N;
55980  p->nResColumn = (u16)nResColumn;
55981  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
55982  if( p->aColName==0 ) return;
55983  while( n-- > 0 ){
55984    pColName->flags = MEM_Null;
55985    pColName->db = p->db;
55986    pColName++;
55987  }
55988}
55989
55990/*
55991** Set the name of the idx'th column to be returned by the SQL statement.
55992** zName must be a pointer to a nul terminated string.
55993**
55994** This call must be made after a call to sqlite3VdbeSetNumCols().
55995**
55996** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
55997** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
55998** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
55999*/
56000SQLITE_PRIVATE int sqlite3VdbeSetColName(
56001  Vdbe *p,                         /* Vdbe being configured */
56002  int idx,                         /* Index of column zName applies to */
56003  int var,                         /* One of the COLNAME_* constants */
56004  const char *zName,               /* Pointer to buffer containing name */
56005  void (*xDel)(void*)              /* Memory management strategy for zName */
56006){
56007  int rc;
56008  Mem *pColName;
56009  assert( idx<p->nResColumn );
56010  assert( var<COLNAME_N );
56011  if( p->db->mallocFailed ){
56012    assert( !zName || xDel!=SQLITE_DYNAMIC );
56013    return SQLITE_NOMEM;
56014  }
56015  assert( p->aColName!=0 );
56016  pColName = &(p->aColName[idx+var*p->nResColumn]);
56017  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
56018  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
56019  return rc;
56020}
56021
56022/*
56023** A read or write transaction may or may not be active on database handle
56024** db. If a transaction is active, commit it. If there is a
56025** write-transaction spanning more than one database file, this routine
56026** takes care of the master journal trickery.
56027*/
56028static int vdbeCommit(sqlite3 *db, Vdbe *p){
56029  int i;
56030  int nTrans = 0;  /* Number of databases with an active write-transaction */
56031  int rc = SQLITE_OK;
56032  int needXcommit = 0;
56033
56034#ifdef SQLITE_OMIT_VIRTUALTABLE
56035  /* With this option, sqlite3VtabSync() is defined to be simply
56036  ** SQLITE_OK so p is not used.
56037  */
56038  UNUSED_PARAMETER(p);
56039#endif
56040
56041  /* Before doing anything else, call the xSync() callback for any
56042  ** virtual module tables written in this transaction. This has to
56043  ** be done before determining whether a master journal file is
56044  ** required, as an xSync() callback may add an attached database
56045  ** to the transaction.
56046  */
56047  rc = sqlite3VtabSync(db, &p->zErrMsg);
56048
56049  /* This loop determines (a) if the commit hook should be invoked and
56050  ** (b) how many database files have open write transactions, not
56051  ** including the temp database. (b) is important because if more than
56052  ** one database file has an open write transaction, a master journal
56053  ** file is required for an atomic commit.
56054  */
56055  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56056    Btree *pBt = db->aDb[i].pBt;
56057    if( sqlite3BtreeIsInTrans(pBt) ){
56058      needXcommit = 1;
56059      if( i!=1 ) nTrans++;
56060      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
56061    }
56062  }
56063  if( rc!=SQLITE_OK ){
56064    return rc;
56065  }
56066
56067  /* If there are any write-transactions at all, invoke the commit hook */
56068  if( needXcommit && db->xCommitCallback ){
56069    rc = db->xCommitCallback(db->pCommitArg);
56070    if( rc ){
56071      return SQLITE_CONSTRAINT;
56072    }
56073  }
56074
56075  /* The simple case - no more than one database file (not counting the
56076  ** TEMP database) has a transaction active.   There is no need for the
56077  ** master-journal.
56078  **
56079  ** If the return value of sqlite3BtreeGetFilename() is a zero length
56080  ** string, it means the main database is :memory: or a temp file.  In
56081  ** that case we do not support atomic multi-file commits, so use the
56082  ** simple case then too.
56083  */
56084  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
56085   || nTrans<=1
56086  ){
56087    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56088      Btree *pBt = db->aDb[i].pBt;
56089      if( pBt ){
56090        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
56091      }
56092    }
56093
56094    /* Do the commit only if all databases successfully complete phase 1.
56095    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
56096    ** IO error while deleting or truncating a journal file. It is unlikely,
56097    ** but could happen. In this case abandon processing and return the error.
56098    */
56099    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56100      Btree *pBt = db->aDb[i].pBt;
56101      if( pBt ){
56102        rc = sqlite3BtreeCommitPhaseTwo(pBt);
56103      }
56104    }
56105    if( rc==SQLITE_OK ){
56106      sqlite3VtabCommit(db);
56107    }
56108  }
56109
56110  /* The complex case - There is a multi-file write-transaction active.
56111  ** This requires a master journal file to ensure the transaction is
56112  ** committed atomicly.
56113  */
56114#ifndef SQLITE_OMIT_DISKIO
56115  else{
56116    sqlite3_vfs *pVfs = db->pVfs;
56117    int needSync = 0;
56118    char *zMaster = 0;   /* File-name for the master journal */
56119    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
56120    sqlite3_file *pMaster = 0;
56121    i64 offset = 0;
56122    int res;
56123
56124    /* Select a master journal file name */
56125    do {
56126      u32 iRandom;
56127      sqlite3DbFree(db, zMaster);
56128      sqlite3_randomness(sizeof(iRandom), &iRandom);
56129      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
56130      if( !zMaster ){
56131        return SQLITE_NOMEM;
56132      }
56133      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
56134    }while( rc==SQLITE_OK && res );
56135    if( rc==SQLITE_OK ){
56136      /* Open the master journal. */
56137      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
56138          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
56139          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
56140      );
56141    }
56142    if( rc!=SQLITE_OK ){
56143      sqlite3DbFree(db, zMaster);
56144      return rc;
56145    }
56146
56147    /* Write the name of each database file in the transaction into the new
56148    ** master journal file. If an error occurs at this point close
56149    ** and delete the master journal file. All the individual journal files
56150    ** still have 'null' as the master journal pointer, so they will roll
56151    ** back independently if a failure occurs.
56152    */
56153    for(i=0; i<db->nDb; i++){
56154      Btree *pBt = db->aDb[i].pBt;
56155      if( sqlite3BtreeIsInTrans(pBt) ){
56156        char const *zFile = sqlite3BtreeGetJournalname(pBt);
56157        if( zFile==0 || zFile[0]==0 ){
56158          continue;  /* Ignore TEMP and :memory: databases */
56159        }
56160        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
56161          needSync = 1;
56162        }
56163        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
56164        offset += sqlite3Strlen30(zFile)+1;
56165        if( rc!=SQLITE_OK ){
56166          sqlite3OsCloseFree(pMaster);
56167          sqlite3OsDelete(pVfs, zMaster, 0);
56168          sqlite3DbFree(db, zMaster);
56169          return rc;
56170        }
56171      }
56172    }
56173
56174    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
56175    ** flag is set this is not required.
56176    */
56177    if( needSync
56178     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
56179     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
56180    ){
56181      sqlite3OsCloseFree(pMaster);
56182      sqlite3OsDelete(pVfs, zMaster, 0);
56183      sqlite3DbFree(db, zMaster);
56184      return rc;
56185    }
56186
56187    /* Sync all the db files involved in the transaction. The same call
56188    ** sets the master journal pointer in each individual journal. If
56189    ** an error occurs here, do not delete the master journal file.
56190    **
56191    ** If the error occurs during the first call to
56192    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
56193    ** master journal file will be orphaned. But we cannot delete it,
56194    ** in case the master journal file name was written into the journal
56195    ** file before the failure occurred.
56196    */
56197    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56198      Btree *pBt = db->aDb[i].pBt;
56199      if( pBt ){
56200        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
56201      }
56202    }
56203    sqlite3OsCloseFree(pMaster);
56204    assert( rc!=SQLITE_BUSY );
56205    if( rc!=SQLITE_OK ){
56206      sqlite3DbFree(db, zMaster);
56207      return rc;
56208    }
56209
56210    /* Delete the master journal file. This commits the transaction. After
56211    ** doing this the directory is synced again before any individual
56212    ** transaction files are deleted.
56213    */
56214    rc = sqlite3OsDelete(pVfs, zMaster, 1);
56215    sqlite3DbFree(db, zMaster);
56216    zMaster = 0;
56217    if( rc ){
56218      return rc;
56219    }
56220
56221    /* All files and directories have already been synced, so the following
56222    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
56223    ** deleting or truncating journals. If something goes wrong while
56224    ** this is happening we don't really care. The integrity of the
56225    ** transaction is already guaranteed, but some stray 'cold' journals
56226    ** may be lying around. Returning an error code won't help matters.
56227    */
56228    disable_simulated_io_errors();
56229    sqlite3BeginBenignMalloc();
56230    for(i=0; i<db->nDb; i++){
56231      Btree *pBt = db->aDb[i].pBt;
56232      if( pBt ){
56233        sqlite3BtreeCommitPhaseTwo(pBt);
56234      }
56235    }
56236    sqlite3EndBenignMalloc();
56237    enable_simulated_io_errors();
56238
56239    sqlite3VtabCommit(db);
56240  }
56241#endif
56242
56243  return rc;
56244}
56245
56246/*
56247** This routine checks that the sqlite3.activeVdbeCnt count variable
56248** matches the number of vdbe's in the list sqlite3.pVdbe that are
56249** currently active. An assertion fails if the two counts do not match.
56250** This is an internal self-check only - it is not an essential processing
56251** step.
56252**
56253** This is a no-op if NDEBUG is defined.
56254*/
56255#ifndef NDEBUG
56256static void checkActiveVdbeCnt(sqlite3 *db){
56257  Vdbe *p;
56258  int cnt = 0;
56259  int nWrite = 0;
56260  p = db->pVdbe;
56261  while( p ){
56262    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
56263      cnt++;
56264      if( p->readOnly==0 ) nWrite++;
56265    }
56266    p = p->pNext;
56267  }
56268  assert( cnt==db->activeVdbeCnt );
56269  assert( nWrite==db->writeVdbeCnt );
56270}
56271#else
56272#define checkActiveVdbeCnt(x)
56273#endif
56274
56275/*
56276** For every Btree that in database connection db which
56277** has been modified, "trip" or invalidate each cursor in
56278** that Btree might have been modified so that the cursor
56279** can never be used again.  This happens when a rollback
56280*** occurs.  We have to trip all the other cursors, even
56281** cursor from other VMs in different database connections,
56282** so that none of them try to use the data at which they
56283** were pointing and which now may have been changed due
56284** to the rollback.
56285**
56286** Remember that a rollback can delete tables complete and
56287** reorder rootpages.  So it is not sufficient just to save
56288** the state of the cursor.  We have to invalidate the cursor
56289** so that it is never used again.
56290*/
56291static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
56292  int i;
56293  for(i=0; i<db->nDb; i++){
56294    Btree *p = db->aDb[i].pBt;
56295    if( p && sqlite3BtreeIsInTrans(p) ){
56296      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
56297    }
56298  }
56299}
56300
56301/*
56302** If the Vdbe passed as the first argument opened a statement-transaction,
56303** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
56304** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
56305** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
56306** statement transaction is commtted.
56307**
56308** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
56309** Otherwise SQLITE_OK.
56310*/
56311SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
56312  sqlite3 *const db = p->db;
56313  int rc = SQLITE_OK;
56314
56315  /* If p->iStatement is greater than zero, then this Vdbe opened a
56316  ** statement transaction that should be closed here. The only exception
56317  ** is that an IO error may have occured, causing an emergency rollback.
56318  ** In this case (db->nStatement==0), and there is nothing to do.
56319  */
56320  if( db->nStatement && p->iStatement ){
56321    int i;
56322    const int iSavepoint = p->iStatement-1;
56323
56324    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
56325    assert( db->nStatement>0 );
56326    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
56327
56328    for(i=0; i<db->nDb; i++){
56329      int rc2 = SQLITE_OK;
56330      Btree *pBt = db->aDb[i].pBt;
56331      if( pBt ){
56332        if( eOp==SAVEPOINT_ROLLBACK ){
56333          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
56334        }
56335        if( rc2==SQLITE_OK ){
56336          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
56337        }
56338        if( rc==SQLITE_OK ){
56339          rc = rc2;
56340        }
56341      }
56342    }
56343    db->nStatement--;
56344    p->iStatement = 0;
56345
56346    /* If the statement transaction is being rolled back, also restore the
56347    ** database handles deferred constraint counter to the value it had when
56348    ** the statement transaction was opened.  */
56349    if( eOp==SAVEPOINT_ROLLBACK ){
56350      db->nDeferredCons = p->nStmtDefCons;
56351    }
56352  }
56353  return rc;
56354}
56355
56356/*
56357** If SQLite is compiled to support shared-cache mode and to be threadsafe,
56358** this routine obtains the mutex associated with each BtShared structure
56359** that may be accessed by the VM passed as an argument. In doing so it
56360** sets the BtShared.db member of each of the BtShared structures, ensuring
56361** that the correct busy-handler callback is invoked if required.
56362**
56363** If SQLite is not threadsafe but does support shared-cache mode, then
56364** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
56365** of all of BtShared structures accessible via the database handle
56366** associated with the VM. Of course only a subset of these structures
56367** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
56368** that subset out, but there is no advantage to doing so.
56369**
56370** If SQLite is not threadsafe and does not support shared-cache mode, this
56371** function is a no-op.
56372*/
56373#ifndef SQLITE_OMIT_SHARED_CACHE
56374SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
56375#if SQLITE_THREADSAFE
56376  sqlite3BtreeMutexArrayEnter(&p->aMutex);
56377#else
56378  sqlite3BtreeEnterAll(p->db);
56379#endif
56380}
56381#endif
56382
56383/*
56384** This function is called when a transaction opened by the database
56385** handle associated with the VM passed as an argument is about to be
56386** committed. If there are outstanding deferred foreign key constraint
56387** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
56388**
56389** If there are outstanding FK violations and this function returns
56390** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
56391** an error message to it. Then return SQLITE_ERROR.
56392*/
56393#ifndef SQLITE_OMIT_FOREIGN_KEY
56394SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
56395  sqlite3 *db = p->db;
56396  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
56397    p->rc = SQLITE_CONSTRAINT;
56398    p->errorAction = OE_Abort;
56399    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
56400    return SQLITE_ERROR;
56401  }
56402  return SQLITE_OK;
56403}
56404#endif
56405
56406/*
56407** This routine is called the when a VDBE tries to halt.  If the VDBE
56408** has made changes and is in autocommit mode, then commit those
56409** changes.  If a rollback is needed, then do the rollback.
56410**
56411** This routine is the only way to move the state of a VM from
56412** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
56413** call this on a VM that is in the SQLITE_MAGIC_HALT state.
56414**
56415** Return an error code.  If the commit could not complete because of
56416** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
56417** means the close did not happen and needs to be repeated.
56418*/
56419SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
56420  int rc;                         /* Used to store transient return codes */
56421  sqlite3 *db = p->db;
56422
56423  /* This function contains the logic that determines if a statement or
56424  ** transaction will be committed or rolled back as a result of the
56425  ** execution of this virtual machine.
56426  **
56427  ** If any of the following errors occur:
56428  **
56429  **     SQLITE_NOMEM
56430  **     SQLITE_IOERR
56431  **     SQLITE_FULL
56432  **     SQLITE_INTERRUPT
56433  **
56434  ** Then the internal cache might have been left in an inconsistent
56435  ** state.  We need to rollback the statement transaction, if there is
56436  ** one, or the complete transaction if there is no statement transaction.
56437  */
56438
56439  if( p->db->mallocFailed ){
56440    p->rc = SQLITE_NOMEM;
56441  }
56442  closeAllCursors(p);
56443  if( p->magic!=VDBE_MAGIC_RUN ){
56444    return SQLITE_OK;
56445  }
56446  checkActiveVdbeCnt(db);
56447
56448  /* No commit or rollback needed if the program never started */
56449  if( p->pc>=0 ){
56450    int mrc;   /* Primary error code from p->rc */
56451    int eStatementOp = 0;
56452    int isSpecialError;            /* Set to true if a 'special' error */
56453
56454    /* Lock all btrees used by the statement */
56455    sqlite3VdbeMutexArrayEnter(p);
56456
56457    /* Check for one of the special errors */
56458    mrc = p->rc & 0xff;
56459    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
56460    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
56461                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
56462    if( isSpecialError ){
56463      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
56464      ** no rollback is necessary. Otherwise, at least a savepoint
56465      ** transaction must be rolled back to restore the database to a
56466      ** consistent state.
56467      **
56468      ** Even if the statement is read-only, it is important to perform
56469      ** a statement or transaction rollback operation. If the error
56470      ** occured while writing to the journal, sub-journal or database
56471      ** file as part of an effort to free up cache space (see function
56472      ** pagerStress() in pager.c), the rollback is required to restore
56473      ** the pager to a consistent state.
56474      */
56475      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
56476        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
56477          eStatementOp = SAVEPOINT_ROLLBACK;
56478        }else{
56479          /* We are forced to roll back the active transaction. Before doing
56480          ** so, abort any other statements this handle currently has active.
56481          */
56482          invalidateCursorsOnModifiedBtrees(db);
56483          sqlite3RollbackAll(db);
56484          sqlite3CloseSavepoints(db);
56485          db->autoCommit = 1;
56486        }
56487      }
56488    }
56489
56490    /* Check for immediate foreign key violations. */
56491    if( p->rc==SQLITE_OK ){
56492      sqlite3VdbeCheckFk(p, 0);
56493    }
56494
56495    /* If the auto-commit flag is set and this is the only active writer
56496    ** VM, then we do either a commit or rollback of the current transaction.
56497    **
56498    ** Note: This block also runs if one of the special errors handled
56499    ** above has occurred.
56500    */
56501    if( !sqlite3VtabInSync(db)
56502     && db->autoCommit
56503     && db->writeVdbeCnt==(p->readOnly==0)
56504    ){
56505      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
56506        if( sqlite3VdbeCheckFk(p, 1) ){
56507          sqlite3BtreeMutexArrayLeave(&p->aMutex);
56508          return SQLITE_ERROR;
56509        }
56510        /* The auto-commit flag is true, the vdbe program was successful
56511        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
56512        ** key constraints to hold up the transaction. This means a commit
56513        ** is required.  */
56514        rc = vdbeCommit(db, p);
56515        if( rc==SQLITE_BUSY ){
56516          sqlite3BtreeMutexArrayLeave(&p->aMutex);
56517          return SQLITE_BUSY;
56518        }else if( rc!=SQLITE_OK ){
56519          p->rc = rc;
56520          sqlite3RollbackAll(db);
56521        }else{
56522          db->nDeferredCons = 0;
56523          sqlite3CommitInternalChanges(db);
56524        }
56525      }else{
56526        sqlite3RollbackAll(db);
56527      }
56528      db->nStatement = 0;
56529    }else if( eStatementOp==0 ){
56530      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
56531        eStatementOp = SAVEPOINT_RELEASE;
56532      }else if( p->errorAction==OE_Abort ){
56533        eStatementOp = SAVEPOINT_ROLLBACK;
56534      }else{
56535        invalidateCursorsOnModifiedBtrees(db);
56536        sqlite3RollbackAll(db);
56537        sqlite3CloseSavepoints(db);
56538        db->autoCommit = 1;
56539      }
56540    }
56541
56542    /* If eStatementOp is non-zero, then a statement transaction needs to
56543    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
56544    ** do so. If this operation returns an error, and the current statement
56545    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
56546    ** current statement error code.
56547    **
56548    ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
56549    ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
56550    ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in
56551    ** the following code.
56552    */
56553    if( eStatementOp ){
56554      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
56555      if( rc ){
56556        assert( eStatementOp==SAVEPOINT_ROLLBACK );
56557        if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
56558          p->rc = rc;
56559          sqlite3DbFree(db, p->zErrMsg);
56560          p->zErrMsg = 0;
56561        }
56562        invalidateCursorsOnModifiedBtrees(db);
56563        sqlite3RollbackAll(db);
56564        sqlite3CloseSavepoints(db);
56565        db->autoCommit = 1;
56566      }
56567    }
56568
56569    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
56570    ** has been rolled back, update the database connection change-counter.
56571    */
56572    if( p->changeCntOn ){
56573      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
56574        sqlite3VdbeSetChanges(db, p->nChange);
56575      }else{
56576        sqlite3VdbeSetChanges(db, 0);
56577      }
56578      p->nChange = 0;
56579    }
56580
56581    /* Rollback or commit any schema changes that occurred. */
56582    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
56583      sqlite3ResetInternalSchema(db, 0);
56584      db->flags = (db->flags | SQLITE_InternChanges);
56585    }
56586
56587    /* Release the locks */
56588    sqlite3BtreeMutexArrayLeave(&p->aMutex);
56589  }
56590
56591  /* We have successfully halted and closed the VM.  Record this fact. */
56592  if( p->pc>=0 ){
56593    db->activeVdbeCnt--;
56594    if( !p->readOnly ){
56595      db->writeVdbeCnt--;
56596    }
56597    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
56598  }
56599  p->magic = VDBE_MAGIC_HALT;
56600  checkActiveVdbeCnt(db);
56601  if( p->db->mallocFailed ){
56602    p->rc = SQLITE_NOMEM;
56603  }
56604
56605  /* If the auto-commit flag is set to true, then any locks that were held
56606  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
56607  ** to invoke any required unlock-notify callbacks.
56608  */
56609  if( db->autoCommit ){
56610    sqlite3ConnectionUnlocked(db);
56611  }
56612
56613  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
56614  return SQLITE_OK;
56615}
56616
56617
56618/*
56619** Each VDBE holds the result of the most recent sqlite3_step() call
56620** in p->rc.  This routine sets that result back to SQLITE_OK.
56621*/
56622SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
56623  p->rc = SQLITE_OK;
56624}
56625
56626/*
56627** Clean up a VDBE after execution but do not delete the VDBE just yet.
56628** Write any error messages into *pzErrMsg.  Return the result code.
56629**
56630** After this routine is run, the VDBE should be ready to be executed
56631** again.
56632**
56633** To look at it another way, this routine resets the state of the
56634** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
56635** VDBE_MAGIC_INIT.
56636*/
56637SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
56638  sqlite3 *db;
56639  db = p->db;
56640
56641  /* If the VM did not run to completion or if it encountered an
56642  ** error, then it might not have been halted properly.  So halt
56643  ** it now.
56644  */
56645  sqlite3VdbeHalt(p);
56646
56647  /* If the VDBE has be run even partially, then transfer the error code
56648  ** and error message from the VDBE into the main database structure.  But
56649  ** if the VDBE has just been set to run but has not actually executed any
56650  ** instructions yet, leave the main database error information unchanged.
56651  */
56652  if( p->pc>=0 ){
56653    if( p->zErrMsg ){
56654      sqlite3BeginBenignMalloc();
56655      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
56656      sqlite3EndBenignMalloc();
56657      db->errCode = p->rc;
56658      sqlite3DbFree(db, p->zErrMsg);
56659      p->zErrMsg = 0;
56660    }else if( p->rc ){
56661      sqlite3Error(db, p->rc, 0);
56662    }else{
56663      sqlite3Error(db, SQLITE_OK, 0);
56664    }
56665    if( p->runOnlyOnce ) p->expired = 1;
56666  }else if( p->rc && p->expired ){
56667    /* The expired flag was set on the VDBE before the first call
56668    ** to sqlite3_step(). For consistency (since sqlite3_step() was
56669    ** called), set the database error in this case as well.
56670    */
56671    sqlite3Error(db, p->rc, 0);
56672    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
56673    sqlite3DbFree(db, p->zErrMsg);
56674    p->zErrMsg = 0;
56675  }
56676
56677  /* Reclaim all memory used by the VDBE
56678  */
56679  Cleanup(p);
56680
56681  /* Save profiling information from this VDBE run.
56682  */
56683#ifdef VDBE_PROFILE
56684  {
56685    FILE *out = fopen("vdbe_profile.out", "a");
56686    if( out ){
56687      int i;
56688      fprintf(out, "---- ");
56689      for(i=0; i<p->nOp; i++){
56690        fprintf(out, "%02x", p->aOp[i].opcode);
56691      }
56692      fprintf(out, "\n");
56693      for(i=0; i<p->nOp; i++){
56694        fprintf(out, "%6d %10lld %8lld ",
56695           p->aOp[i].cnt,
56696           p->aOp[i].cycles,
56697           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
56698        );
56699        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
56700      }
56701      fclose(out);
56702    }
56703  }
56704#endif
56705  p->magic = VDBE_MAGIC_INIT;
56706  return p->rc & db->errMask;
56707}
56708
56709/*
56710** Clean up and delete a VDBE after execution.  Return an integer which is
56711** the result code.  Write any error message text into *pzErrMsg.
56712*/
56713SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
56714  int rc = SQLITE_OK;
56715  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
56716    rc = sqlite3VdbeReset(p);
56717    assert( (rc & p->db->errMask)==rc );
56718  }
56719  sqlite3VdbeDelete(p);
56720  return rc;
56721}
56722
56723/*
56724** Call the destructor for each auxdata entry in pVdbeFunc for which
56725** the corresponding bit in mask is clear.  Auxdata entries beyond 31
56726** are always destroyed.  To destroy all auxdata entries, call this
56727** routine with mask==0.
56728*/
56729SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
56730  int i;
56731  for(i=0; i<pVdbeFunc->nAux; i++){
56732    struct AuxData *pAux = &pVdbeFunc->apAux[i];
56733    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
56734      if( pAux->xDelete ){
56735        pAux->xDelete(pAux->pAux);
56736      }
56737      pAux->pAux = 0;
56738    }
56739  }
56740}
56741
56742/*
56743** Free all memory associated with the Vdbe passed as the second argument.
56744** The difference between this function and sqlite3VdbeDelete() is that
56745** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
56746** the database connection.
56747*/
56748SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
56749  SubProgram *pSub, *pNext;
56750  assert( p->db==0 || p->db==db );
56751  releaseMemArray(p->aVar, p->nVar);
56752  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
56753  for(pSub=p->pProgram; pSub; pSub=pNext){
56754    pNext = pSub->pNext;
56755    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
56756    sqlite3DbFree(db, pSub);
56757  }
56758  vdbeFreeOpArray(db, p->aOp, p->nOp);
56759  sqlite3DbFree(db, p->aLabel);
56760  sqlite3DbFree(db, p->aColName);
56761  sqlite3DbFree(db, p->zSql);
56762  sqlite3DbFree(db, p->pFree);
56763  sqlite3DbFree(db, p);
56764}
56765
56766/*
56767** Delete an entire VDBE.
56768*/
56769SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
56770  sqlite3 *db;
56771
56772  if( NEVER(p==0) ) return;
56773  db = p->db;
56774  if( p->pPrev ){
56775    p->pPrev->pNext = p->pNext;
56776  }else{
56777    assert( db->pVdbe==p );
56778    db->pVdbe = p->pNext;
56779  }
56780  if( p->pNext ){
56781    p->pNext->pPrev = p->pPrev;
56782  }
56783  p->magic = VDBE_MAGIC_DEAD;
56784  p->db = 0;
56785  sqlite3VdbeDeleteObject(db, p);
56786}
56787
56788/*
56789** Make sure the cursor p is ready to read or write the row to which it
56790** was last positioned.  Return an error code if an OOM fault or I/O error
56791** prevents us from positioning the cursor to its correct position.
56792**
56793** If a MoveTo operation is pending on the given cursor, then do that
56794** MoveTo now.  If no move is pending, check to see if the row has been
56795** deleted out from under the cursor and if it has, mark the row as
56796** a NULL row.
56797**
56798** If the cursor is already pointing to the correct row and that row has
56799** not been deleted out from under the cursor, then this routine is a no-op.
56800*/
56801SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
56802  if( p->deferredMoveto ){
56803    int res, rc;
56804#ifdef SQLITE_TEST
56805    extern int sqlite3_search_count;
56806#endif
56807    assert( p->isTable );
56808    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
56809    if( rc ) return rc;
56810    p->lastRowid = p->movetoTarget;
56811    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
56812    p->rowidIsValid = 1;
56813#ifdef SQLITE_TEST
56814    sqlite3_search_count++;
56815#endif
56816    p->deferredMoveto = 0;
56817    p->cacheStatus = CACHE_STALE;
56818  }else if( ALWAYS(p->pCursor) ){
56819    int hasMoved;
56820    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
56821    if( rc ) return rc;
56822    if( hasMoved ){
56823      p->cacheStatus = CACHE_STALE;
56824      p->nullRow = 1;
56825    }
56826  }
56827  return SQLITE_OK;
56828}
56829
56830/*
56831** The following functions:
56832**
56833** sqlite3VdbeSerialType()
56834** sqlite3VdbeSerialTypeLen()
56835** sqlite3VdbeSerialLen()
56836** sqlite3VdbeSerialPut()
56837** sqlite3VdbeSerialGet()
56838**
56839** encapsulate the code that serializes values for storage in SQLite
56840** data and index records. Each serialized value consists of a
56841** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
56842** integer, stored as a varint.
56843**
56844** In an SQLite index record, the serial type is stored directly before
56845** the blob of data that it corresponds to. In a table record, all serial
56846** types are stored at the start of the record, and the blobs of data at
56847** the end. Hence these functions allow the caller to handle the
56848** serial-type and data blob seperately.
56849**
56850** The following table describes the various storage classes for data:
56851**
56852**   serial type        bytes of data      type
56853**   --------------     ---------------    ---------------
56854**      0                     0            NULL
56855**      1                     1            signed integer
56856**      2                     2            signed integer
56857**      3                     3            signed integer
56858**      4                     4            signed integer
56859**      5                     6            signed integer
56860**      6                     8            signed integer
56861**      7                     8            IEEE float
56862**      8                     0            Integer constant 0
56863**      9                     0            Integer constant 1
56864**     10,11                               reserved for expansion
56865**    N>=12 and even       (N-12)/2        BLOB
56866**    N>=13 and odd        (N-13)/2        text
56867**
56868** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
56869** of SQLite will not understand those serial types.
56870*/
56871
56872/*
56873** Return the serial-type for the value stored in pMem.
56874*/
56875SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
56876  int flags = pMem->flags;
56877  int n;
56878
56879  if( flags&MEM_Null ){
56880    return 0;
56881  }
56882  if( flags&MEM_Int ){
56883    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
56884#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
56885    i64 i = pMem->u.i;
56886    u64 u;
56887    if( file_format>=4 && (i&1)==i ){
56888      return 8+(u32)i;
56889    }
56890    u = i<0 ? -i : i;
56891    if( u<=127 ) return 1;
56892    if( u<=32767 ) return 2;
56893    if( u<=8388607 ) return 3;
56894    if( u<=2147483647 ) return 4;
56895    if( u<=MAX_6BYTE ) return 5;
56896    return 6;
56897  }
56898  if( flags&MEM_Real ){
56899    return 7;
56900  }
56901  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
56902  n = pMem->n;
56903  if( flags & MEM_Zero ){
56904    n += pMem->u.nZero;
56905  }
56906  assert( n>=0 );
56907  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
56908}
56909
56910/*
56911** Return the length of the data corresponding to the supplied serial-type.
56912*/
56913SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
56914  if( serial_type>=12 ){
56915    return (serial_type-12)/2;
56916  }else{
56917    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
56918    return aSize[serial_type];
56919  }
56920}
56921
56922/*
56923** If we are on an architecture with mixed-endian floating
56924** points (ex: ARM7) then swap the lower 4 bytes with the
56925** upper 4 bytes.  Return the result.
56926**
56927** For most architectures, this is a no-op.
56928**
56929** (later):  It is reported to me that the mixed-endian problem
56930** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
56931** that early versions of GCC stored the two words of a 64-bit
56932** float in the wrong order.  And that error has been propagated
56933** ever since.  The blame is not necessarily with GCC, though.
56934** GCC might have just copying the problem from a prior compiler.
56935** I am also told that newer versions of GCC that follow a different
56936** ABI get the byte order right.
56937**
56938** Developers using SQLite on an ARM7 should compile and run their
56939** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
56940** enabled, some asserts below will ensure that the byte order of
56941** floating point values is correct.
56942**
56943** (2007-08-30)  Frank van Vugt has studied this problem closely
56944** and has send his findings to the SQLite developers.  Frank
56945** writes that some Linux kernels offer floating point hardware
56946** emulation that uses only 32-bit mantissas instead of a full
56947** 48-bits as required by the IEEE standard.  (This is the
56948** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
56949** byte swapping becomes very complicated.  To avoid problems,
56950** the necessary byte swapping is carried out using a 64-bit integer
56951** rather than a 64-bit float.  Frank assures us that the code here
56952** works for him.  We, the developers, have no way to independently
56953** verify this, but Frank seems to know what he is talking about
56954** so we trust him.
56955*/
56956#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
56957static u64 floatSwap(u64 in){
56958  union {
56959    u64 r;
56960    u32 i[2];
56961  } u;
56962  u32 t;
56963
56964  u.r = in;
56965  t = u.i[0];
56966  u.i[0] = u.i[1];
56967  u.i[1] = t;
56968  return u.r;
56969}
56970# define swapMixedEndianFloat(X)  X = floatSwap(X)
56971#else
56972# define swapMixedEndianFloat(X)
56973#endif
56974
56975/*
56976** Write the serialized data blob for the value stored in pMem into
56977** buf. It is assumed that the caller has allocated sufficient space.
56978** Return the number of bytes written.
56979**
56980** nBuf is the amount of space left in buf[].  nBuf must always be
56981** large enough to hold the entire field.  Except, if the field is
56982** a blob with a zero-filled tail, then buf[] might be just the right
56983** size to hold everything except for the zero-filled tail.  If buf[]
56984** is only big enough to hold the non-zero prefix, then only write that
56985** prefix into buf[].  But if buf[] is large enough to hold both the
56986** prefix and the tail then write the prefix and set the tail to all
56987** zeros.
56988**
56989** Return the number of bytes actually written into buf[].  The number
56990** of bytes in the zero-filled tail is included in the return value only
56991** if those bytes were zeroed in buf[].
56992*/
56993SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
56994  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
56995  u32 len;
56996
56997  /* Integer and Real */
56998  if( serial_type<=7 && serial_type>0 ){
56999    u64 v;
57000    u32 i;
57001    if( serial_type==7 ){
57002      assert( sizeof(v)==sizeof(pMem->r) );
57003      memcpy(&v, &pMem->r, sizeof(v));
57004      swapMixedEndianFloat(v);
57005    }else{
57006      v = pMem->u.i;
57007    }
57008    len = i = sqlite3VdbeSerialTypeLen(serial_type);
57009    assert( len<=(u32)nBuf );
57010    while( i-- ){
57011      buf[i] = (u8)(v&0xFF);
57012      v >>= 8;
57013    }
57014    return len;
57015  }
57016
57017  /* String or blob */
57018  if( serial_type>=12 ){
57019    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
57020             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
57021    assert( pMem->n<=nBuf );
57022    len = pMem->n;
57023    memcpy(buf, pMem->z, len);
57024    if( pMem->flags & MEM_Zero ){
57025      len += pMem->u.nZero;
57026      assert( nBuf>=0 );
57027      if( len > (u32)nBuf ){
57028        len = (u32)nBuf;
57029      }
57030      memset(&buf[pMem->n], 0, len-pMem->n);
57031    }
57032    return len;
57033  }
57034
57035  /* NULL or constants 0 or 1 */
57036  return 0;
57037}
57038
57039/*
57040** Deserialize the data blob pointed to by buf as serial type serial_type
57041** and store the result in pMem.  Return the number of bytes read.
57042*/
57043SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
57044  const unsigned char *buf,     /* Buffer to deserialize from */
57045  u32 serial_type,              /* Serial type to deserialize */
57046  Mem *pMem                     /* Memory cell to write value into */
57047){
57048  switch( serial_type ){
57049    case 10:   /* Reserved for future use */
57050    case 11:   /* Reserved for future use */
57051    case 0: {  /* NULL */
57052      pMem->flags = MEM_Null;
57053      break;
57054    }
57055    case 1: { /* 1-byte signed integer */
57056      pMem->u.i = (signed char)buf[0];
57057      pMem->flags = MEM_Int;
57058      return 1;
57059    }
57060    case 2: { /* 2-byte signed integer */
57061      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
57062      pMem->flags = MEM_Int;
57063      return 2;
57064    }
57065    case 3: { /* 3-byte signed integer */
57066      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
57067      pMem->flags = MEM_Int;
57068      return 3;
57069    }
57070    case 4: { /* 4-byte signed integer */
57071      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
57072      pMem->flags = MEM_Int;
57073      return 4;
57074    }
57075    case 5: { /* 6-byte signed integer */
57076      u64 x = (((signed char)buf[0])<<8) | buf[1];
57077      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
57078      x = (x<<32) | y;
57079      pMem->u.i = *(i64*)&x;
57080      pMem->flags = MEM_Int;
57081      return 6;
57082    }
57083    case 6:   /* 8-byte signed integer */
57084    case 7: { /* IEEE floating point */
57085      u64 x;
57086      u32 y;
57087#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
57088      /* Verify that integers and floating point values use the same
57089      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
57090      ** defined that 64-bit floating point values really are mixed
57091      ** endian.
57092      */
57093      static const u64 t1 = ((u64)0x3ff00000)<<32;
57094      static const double r1 = 1.0;
57095      u64 t2 = t1;
57096      swapMixedEndianFloat(t2);
57097      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
57098#endif
57099
57100      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
57101      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
57102      x = (x<<32) | y;
57103      if( serial_type==6 ){
57104        pMem->u.i = *(i64*)&x;
57105        pMem->flags = MEM_Int;
57106      }else{
57107        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
57108        swapMixedEndianFloat(x);
57109        memcpy(&pMem->r, &x, sizeof(x));
57110        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
57111      }
57112      return 8;
57113    }
57114    case 8:    /* Integer 0 */
57115    case 9: {  /* Integer 1 */
57116      pMem->u.i = serial_type-8;
57117      pMem->flags = MEM_Int;
57118      return 0;
57119    }
57120    default: {
57121      u32 len = (serial_type-12)/2;
57122      pMem->z = (char *)buf;
57123      pMem->n = len;
57124      pMem->xDel = 0;
57125      if( serial_type&0x01 ){
57126        pMem->flags = MEM_Str | MEM_Ephem;
57127      }else{
57128        pMem->flags = MEM_Blob | MEM_Ephem;
57129      }
57130      return len;
57131    }
57132  }
57133  return 0;
57134}
57135
57136
57137/*
57138** Given the nKey-byte encoding of a record in pKey[], parse the
57139** record into a UnpackedRecord structure.  Return a pointer to
57140** that structure.
57141**
57142** The calling function might provide szSpace bytes of memory
57143** space at pSpace.  This space can be used to hold the returned
57144** VDbeParsedRecord structure if it is large enough.  If it is
57145** not big enough, space is obtained from sqlite3_malloc().
57146**
57147** The returned structure should be closed by a call to
57148** sqlite3VdbeDeleteUnpackedRecord().
57149*/
57150SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
57151  KeyInfo *pKeyInfo,     /* Information about the record format */
57152  int nKey,              /* Size of the binary record */
57153  const void *pKey,      /* The binary record */
57154  char *pSpace,          /* Unaligned space available to hold the object */
57155  int szSpace            /* Size of pSpace[] in bytes */
57156){
57157  const unsigned char *aKey = (const unsigned char *)pKey;
57158  UnpackedRecord *p;  /* The unpacked record that we will return */
57159  int nByte;          /* Memory space needed to hold p, in bytes */
57160  int d;
57161  u32 idx;
57162  u16 u;              /* Unsigned loop counter */
57163  u32 szHdr;
57164  Mem *pMem;
57165  int nOff;           /* Increase pSpace by this much to 8-byte align it */
57166
57167  /*
57168  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
57169  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
57170  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
57171  */
57172  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
57173  pSpace += nOff;
57174  szSpace -= nOff;
57175  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
57176  if( nByte>szSpace ){
57177    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
57178    if( p==0 ) return 0;
57179    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
57180  }else{
57181    p = (UnpackedRecord*)pSpace;
57182    p->flags = UNPACKED_NEED_DESTROY;
57183  }
57184  p->pKeyInfo = pKeyInfo;
57185  p->nField = pKeyInfo->nField + 1;
57186  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
57187  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57188  idx = getVarint32(aKey, szHdr);
57189  d = szHdr;
57190  u = 0;
57191  while( idx<szHdr && u<p->nField && d<=nKey ){
57192    u32 serial_type;
57193
57194    idx += getVarint32(&aKey[idx], serial_type);
57195    pMem->enc = pKeyInfo->enc;
57196    pMem->db = pKeyInfo->db;
57197    pMem->flags = 0;
57198    pMem->zMalloc = 0;
57199    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
57200    pMem++;
57201    u++;
57202  }
57203  assert( u<=pKeyInfo->nField + 1 );
57204  p->nField = u;
57205  return (void*)p;
57206}
57207
57208/*
57209** This routine destroys a UnpackedRecord object.
57210*/
57211SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
57212  int i;
57213  Mem *pMem;
57214
57215  assert( p!=0 );
57216  assert( p->flags & UNPACKED_NEED_DESTROY );
57217  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
57218    /* The unpacked record is always constructed by the
57219    ** sqlite3VdbeUnpackRecord() function above, which makes all
57220    ** strings and blobs static.  And none of the elements are
57221    ** ever transformed, so there is never anything to delete.
57222    */
57223    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
57224  }
57225  if( p->flags & UNPACKED_NEED_FREE ){
57226    sqlite3DbFree(p->pKeyInfo->db, p);
57227  }
57228}
57229
57230/*
57231** This function compares the two table rows or index records
57232** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
57233** or positive integer if key1 is less than, equal to or
57234** greater than key2.  The {nKey1, pKey1} key must be a blob
57235** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
57236** key must be a parsed key such as obtained from
57237** sqlite3VdbeParseRecord.
57238**
57239** Key1 and Key2 do not have to contain the same number of fields.
57240** The key with fewer fields is usually compares less than the
57241** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
57242** and the common prefixes are equal, then key1 is less than key2.
57243** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
57244** equal, then the keys are considered to be equal and
57245** the parts beyond the common prefix are ignored.
57246**
57247** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
57248** the header of pKey1 is ignored.  It is assumed that pKey1 is
57249** an index key, and thus ends with a rowid value.  The last byte
57250** of the header will therefore be the serial type of the rowid:
57251** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
57252** The serial type of the final rowid will always be a single byte.
57253** By ignoring this last byte of the header, we force the comparison
57254** to ignore the rowid at the end of key1.
57255*/
57256SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
57257  int nKey1, const void *pKey1, /* Left key */
57258  UnpackedRecord *pPKey2        /* Right key */
57259){
57260  int d1;            /* Offset into aKey[] of next data element */
57261  u32 idx1;          /* Offset into aKey[] of next header element */
57262  u32 szHdr1;        /* Number of bytes in header */
57263  int i = 0;
57264  int nField;
57265  int rc = 0;
57266  const unsigned char *aKey1 = (const unsigned char *)pKey1;
57267  KeyInfo *pKeyInfo;
57268  Mem mem1;
57269
57270  pKeyInfo = pPKey2->pKeyInfo;
57271  mem1.enc = pKeyInfo->enc;
57272  mem1.db = pKeyInfo->db;
57273  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
57274  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
57275
57276  /* Compilers may complain that mem1.u.i is potentially uninitialized.
57277  ** We could initialize it, as shown here, to silence those complaints.
57278  ** But in fact, mem1.u.i will never actually be used initialized, and doing
57279  ** the unnecessary initialization has a measurable negative performance
57280  ** impact, since this routine is a very high runner.  And so, we choose
57281  ** to ignore the compiler warnings and leave this variable uninitialized.
57282  */
57283  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
57284
57285  idx1 = getVarint32(aKey1, szHdr1);
57286  d1 = szHdr1;
57287  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
57288    szHdr1--;
57289  }
57290  nField = pKeyInfo->nField;
57291  while( idx1<szHdr1 && i<pPKey2->nField ){
57292    u32 serial_type1;
57293
57294    /* Read the serial types for the next element in each key. */
57295    idx1 += getVarint32( aKey1+idx1, serial_type1 );
57296    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
57297
57298    /* Extract the values to be compared.
57299    */
57300    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
57301
57302    /* Do the comparison
57303    */
57304    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
57305                           i<nField ? pKeyInfo->aColl[i] : 0);
57306    if( rc!=0 ){
57307      assert( mem1.zMalloc==0 );  /* See comment below */
57308
57309      /* Invert the result if we are using DESC sort order. */
57310      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
57311        rc = -rc;
57312      }
57313
57314      /* If the PREFIX_SEARCH flag is set and all fields except the final
57315      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
57316      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
57317      ** This is used by the OP_IsUnique opcode.
57318      */
57319      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
57320        assert( idx1==szHdr1 && rc );
57321        assert( mem1.flags & MEM_Int );
57322        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
57323        pPKey2->rowid = mem1.u.i;
57324      }
57325
57326      return rc;
57327    }
57328    i++;
57329  }
57330
57331  /* No memory allocation is ever used on mem1.  Prove this using
57332  ** the following assert().  If the assert() fails, it indicates a
57333  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
57334  */
57335  assert( mem1.zMalloc==0 );
57336
57337  /* rc==0 here means that one of the keys ran out of fields and
57338  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
57339  ** flag is set, then break the tie by treating key2 as larger.
57340  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
57341  ** are considered to be equal.  Otherwise, the longer key is the
57342  ** larger.  As it happens, the pPKey2 will always be the longer
57343  ** if there is a difference.
57344  */
57345  assert( rc==0 );
57346  if( pPKey2->flags & UNPACKED_INCRKEY ){
57347    rc = -1;
57348  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
57349    /* Leave rc==0 */
57350  }else if( idx1<szHdr1 ){
57351    rc = 1;
57352  }
57353  return rc;
57354}
57355
57356
57357/*
57358** pCur points at an index entry created using the OP_MakeRecord opcode.
57359** Read the rowid (the last field in the record) and store it in *rowid.
57360** Return SQLITE_OK if everything works, or an error code otherwise.
57361**
57362** pCur might be pointing to text obtained from a corrupt database file.
57363** So the content cannot be trusted.  Do appropriate checks on the content.
57364*/
57365SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
57366  i64 nCellKey = 0;
57367  int rc;
57368  u32 szHdr;        /* Size of the header */
57369  u32 typeRowid;    /* Serial type of the rowid */
57370  u32 lenRowid;     /* Size of the rowid */
57371  Mem m, v;
57372
57373  UNUSED_PARAMETER(db);
57374
57375  /* Get the size of the index entry.  Only indices entries of less
57376  ** than 2GiB are support - anything large must be database corruption.
57377  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
57378  ** this code can safely assume that nCellKey is 32-bits
57379  */
57380  assert( sqlite3BtreeCursorIsValid(pCur) );
57381  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
57382  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
57383  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
57384
57385  /* Read in the complete content of the index entry */
57386  memset(&m, 0, sizeof(m));
57387  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
57388  if( rc ){
57389    return rc;
57390  }
57391
57392  /* The index entry must begin with a header size */
57393  (void)getVarint32((u8*)m.z, szHdr);
57394  testcase( szHdr==3 );
57395  testcase( szHdr==m.n );
57396  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
57397    goto idx_rowid_corruption;
57398  }
57399
57400  /* The last field of the index should be an integer - the ROWID.
57401  ** Verify that the last entry really is an integer. */
57402  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
57403  testcase( typeRowid==1 );
57404  testcase( typeRowid==2 );
57405  testcase( typeRowid==3 );
57406  testcase( typeRowid==4 );
57407  testcase( typeRowid==5 );
57408  testcase( typeRowid==6 );
57409  testcase( typeRowid==8 );
57410  testcase( typeRowid==9 );
57411  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
57412    goto idx_rowid_corruption;
57413  }
57414  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
57415  testcase( (u32)m.n==szHdr+lenRowid );
57416  if( unlikely((u32)m.n<szHdr+lenRowid) ){
57417    goto idx_rowid_corruption;
57418  }
57419
57420  /* Fetch the integer off the end of the index record */
57421  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
57422  *rowid = v.u.i;
57423  sqlite3VdbeMemRelease(&m);
57424  return SQLITE_OK;
57425
57426  /* Jump here if database corruption is detected after m has been
57427  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
57428idx_rowid_corruption:
57429  testcase( m.zMalloc!=0 );
57430  sqlite3VdbeMemRelease(&m);
57431  return SQLITE_CORRUPT_BKPT;
57432}
57433
57434/*
57435** Compare the key of the index entry that cursor pC is pointing to against
57436** the key string in pUnpacked.  Write into *pRes a number
57437** that is negative, zero, or positive if pC is less than, equal to,
57438** or greater than pUnpacked.  Return SQLITE_OK on success.
57439**
57440** pUnpacked is either created without a rowid or is truncated so that it
57441** omits the rowid at the end.  The rowid at the end of the index entry
57442** is ignored as well.  Hence, this routine only compares the prefixes
57443** of the keys prior to the final rowid, not the entire key.
57444*/
57445SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
57446  VdbeCursor *pC,             /* The cursor to compare against */
57447  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
57448  int *res                    /* Write the comparison result here */
57449){
57450  i64 nCellKey = 0;
57451  int rc;
57452  BtCursor *pCur = pC->pCursor;
57453  Mem m;
57454
57455  assert( sqlite3BtreeCursorIsValid(pCur) );
57456  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
57457  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
57458  /* nCellKey will always be between 0 and 0xffffffff because of the say
57459  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
57460  if( nCellKey<=0 || nCellKey>0x7fffffff ){
57461    *res = 0;
57462    return SQLITE_CORRUPT_BKPT;
57463  }
57464  memset(&m, 0, sizeof(m));
57465  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
57466  if( rc ){
57467    return rc;
57468  }
57469  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
57470  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
57471  sqlite3VdbeMemRelease(&m);
57472  return SQLITE_OK;
57473}
57474
57475/*
57476** This routine sets the value to be returned by subsequent calls to
57477** sqlite3_changes() on the database handle 'db'.
57478*/
57479SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
57480  assert( sqlite3_mutex_held(db->mutex) );
57481  db->nChange = nChange;
57482  db->nTotalChange += nChange;
57483}
57484
57485/*
57486** Set a flag in the vdbe to update the change counter when it is finalised
57487** or reset.
57488*/
57489SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
57490  v->changeCntOn = 1;
57491}
57492
57493/*
57494** Mark every prepared statement associated with a database connection
57495** as expired.
57496**
57497** An expired statement means that recompilation of the statement is
57498** recommend.  Statements expire when things happen that make their
57499** programs obsolete.  Removing user-defined functions or collating
57500** sequences, or changing an authorization function are the types of
57501** things that make prepared statements obsolete.
57502*/
57503SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
57504  Vdbe *p;
57505  for(p = db->pVdbe; p; p=p->pNext){
57506    p->expired = 1;
57507  }
57508}
57509
57510/*
57511** Return the database associated with the Vdbe.
57512*/
57513SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
57514  return v->db;
57515}
57516
57517/*
57518** Return a pointer to an sqlite3_value structure containing the value bound
57519** parameter iVar of VM v. Except, if the value is an SQL NULL, return
57520** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
57521** constants) to the value before returning it.
57522**
57523** The returned value must be freed by the caller using sqlite3ValueFree().
57524*/
57525SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
57526  assert( iVar>0 );
57527  if( v ){
57528    Mem *pMem = &v->aVar[iVar-1];
57529    if( 0==(pMem->flags & MEM_Null) ){
57530      sqlite3_value *pRet = sqlite3ValueNew(v->db);
57531      if( pRet ){
57532        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
57533        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
57534        sqlite3VdbeMemStoreType((Mem *)pRet);
57535      }
57536      return pRet;
57537    }
57538  }
57539  return 0;
57540}
57541
57542/*
57543** Configure SQL variable iVar so that binding a new value to it signals
57544** to sqlite3_reoptimize() that re-preparing the statement may result
57545** in a better query plan.
57546*/
57547SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
57548  assert( iVar>0 );
57549  if( iVar>32 ){
57550    v->expmask = 0xffffffff;
57551  }else{
57552    v->expmask |= ((u32)1 << (iVar-1));
57553  }
57554}
57555
57556/************** End of vdbeaux.c *********************************************/
57557/************** Begin file vdbeapi.c *****************************************/
57558/*
57559** 2004 May 26
57560**
57561** The author disclaims copyright to this source code.  In place of
57562** a legal notice, here is a blessing:
57563**
57564**    May you do good and not evil.
57565**    May you find forgiveness for yourself and forgive others.
57566**    May you share freely, never taking more than you give.
57567**
57568*************************************************************************
57569**
57570** This file contains code use to implement APIs that are part of the
57571** VDBE.
57572*/
57573
57574#ifndef SQLITE_OMIT_DEPRECATED
57575/*
57576** Return TRUE (non-zero) of the statement supplied as an argument needs
57577** to be recompiled.  A statement needs to be recompiled whenever the
57578** execution environment changes in a way that would alter the program
57579** that sqlite3_prepare() generates.  For example, if new functions or
57580** collating sequences are registered or if an authorizer function is
57581** added or changed.
57582*/
57583SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
57584  Vdbe *p = (Vdbe*)pStmt;
57585  return p==0 || p->expired;
57586}
57587#endif
57588
57589/*
57590** Check on a Vdbe to make sure it has not been finalized.  Log
57591** an error and return true if it has been finalized (or is otherwise
57592** invalid).  Return false if it is ok.
57593*/
57594static int vdbeSafety(Vdbe *p){
57595  if( p->db==0 ){
57596    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
57597    return 1;
57598  }else{
57599    return 0;
57600  }
57601}
57602static int vdbeSafetyNotNull(Vdbe *p){
57603  if( p==0 ){
57604    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
57605    return 1;
57606  }else{
57607    return vdbeSafety(p);
57608  }
57609}
57610
57611/*
57612** The following routine destroys a virtual machine that is created by
57613** the sqlite3_compile() routine. The integer returned is an SQLITE_
57614** success/failure code that describes the result of executing the virtual
57615** machine.
57616**
57617** This routine sets the error code and string returned by
57618** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
57619*/
57620SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
57621  int rc;
57622  if( pStmt==0 ){
57623    rc = SQLITE_OK;
57624  }else{
57625    Vdbe *v = (Vdbe*)pStmt;
57626    sqlite3 *db = v->db;
57627#if SQLITE_THREADSAFE
57628    sqlite3_mutex *mutex;
57629#endif
57630    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
57631#if SQLITE_THREADSAFE
57632    mutex = v->db->mutex;
57633#endif
57634    sqlite3_mutex_enter(mutex);
57635    rc = sqlite3VdbeFinalize(v);
57636    rc = sqlite3ApiExit(db, rc);
57637    sqlite3_mutex_leave(mutex);
57638  }
57639  return rc;
57640}
57641
57642/*
57643** Terminate the current execution of an SQL statement and reset it
57644** back to its starting state so that it can be reused. A success code from
57645** the prior execution is returned.
57646**
57647** This routine sets the error code and string returned by
57648** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
57649*/
57650SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
57651  int rc;
57652  if( pStmt==0 ){
57653    rc = SQLITE_OK;
57654  }else{
57655    Vdbe *v = (Vdbe*)pStmt;
57656    sqlite3_mutex_enter(v->db->mutex);
57657    rc = sqlite3VdbeReset(v);
57658    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
57659    assert( (rc & (v->db->errMask))==rc );
57660    rc = sqlite3ApiExit(v->db, rc);
57661    sqlite3_mutex_leave(v->db->mutex);
57662  }
57663  return rc;
57664}
57665
57666/*
57667** Set all the parameters in the compiled SQL statement to NULL.
57668*/
57669SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
57670  int i;
57671  int rc = SQLITE_OK;
57672  Vdbe *p = (Vdbe*)pStmt;
57673#if SQLITE_THREADSAFE
57674  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
57675#endif
57676  sqlite3_mutex_enter(mutex);
57677  for(i=0; i<p->nVar; i++){
57678    sqlite3VdbeMemRelease(&p->aVar[i]);
57679    p->aVar[i].flags = MEM_Null;
57680  }
57681  if( p->isPrepareV2 && p->expmask ){
57682    p->expired = 1;
57683  }
57684  sqlite3_mutex_leave(mutex);
57685  return rc;
57686}
57687
57688
57689/**************************** sqlite3_value_  *******************************
57690** The following routines extract information from a Mem or sqlite3_value
57691** structure.
57692*/
57693SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
57694  Mem *p = (Mem*)pVal;
57695  if( p->flags & (MEM_Blob|MEM_Str) ){
57696    sqlite3VdbeMemExpandBlob(p);
57697    p->flags &= ~MEM_Str;
57698    p->flags |= MEM_Blob;
57699    return p->z;
57700  }else{
57701    return sqlite3_value_text(pVal);
57702  }
57703}
57704SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
57705  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
57706}
57707SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
57708  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
57709}
57710SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
57711  return sqlite3VdbeRealValue((Mem*)pVal);
57712}
57713SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
57714  return (int)sqlite3VdbeIntValue((Mem*)pVal);
57715}
57716SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
57717  return sqlite3VdbeIntValue((Mem*)pVal);
57718}
57719SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
57720  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
57721}
57722#ifndef SQLITE_OMIT_UTF16
57723SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
57724  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
57725}
57726SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
57727  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
57728}
57729SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
57730  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
57731}
57732#endif /* SQLITE_OMIT_UTF16 */
57733SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
57734  return pVal->type;
57735}
57736
57737/**************************** sqlite3_result_  *******************************
57738** The following routines are used by user-defined functions to specify
57739** the function result.
57740**
57741** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
57742** result as a string or blob but if the string or blob is too large, it
57743** then sets the error code to SQLITE_TOOBIG
57744*/
57745static void setResultStrOrError(
57746  sqlite3_context *pCtx,  /* Function context */
57747  const char *z,          /* String pointer */
57748  int n,                  /* Bytes in string, or negative */
57749  u8 enc,                 /* Encoding of z.  0 for BLOBs */
57750  void (*xDel)(void*)     /* Destructor function */
57751){
57752  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
57753    sqlite3_result_error_toobig(pCtx);
57754  }
57755}
57756SQLITE_API void sqlite3_result_blob(
57757  sqlite3_context *pCtx,
57758  const void *z,
57759  int n,
57760  void (*xDel)(void *)
57761){
57762  assert( n>=0 );
57763  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57764  setResultStrOrError(pCtx, z, n, 0, xDel);
57765}
57766SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
57767  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57768  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
57769}
57770SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
57771  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57772  pCtx->isError = SQLITE_ERROR;
57773  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
57774}
57775#ifndef SQLITE_OMIT_UTF16
57776SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
57777  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57778  pCtx->isError = SQLITE_ERROR;
57779  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
57780}
57781#endif
57782SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
57783  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57784  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
57785}
57786SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
57787  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57788  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
57789}
57790SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
57791  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57792  sqlite3VdbeMemSetNull(&pCtx->s);
57793}
57794SQLITE_API void sqlite3_result_text(
57795  sqlite3_context *pCtx,
57796  const char *z,
57797  int n,
57798  void (*xDel)(void *)
57799){
57800  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57801  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
57802}
57803#ifndef SQLITE_OMIT_UTF16
57804SQLITE_API void sqlite3_result_text16(
57805  sqlite3_context *pCtx,
57806  const void *z,
57807  int n,
57808  void (*xDel)(void *)
57809){
57810  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57811  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
57812}
57813SQLITE_API void sqlite3_result_text16be(
57814  sqlite3_context *pCtx,
57815  const void *z,
57816  int n,
57817  void (*xDel)(void *)
57818){
57819  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57820  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
57821}
57822SQLITE_API void sqlite3_result_text16le(
57823  sqlite3_context *pCtx,
57824  const void *z,
57825  int n,
57826  void (*xDel)(void *)
57827){
57828  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57829  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
57830}
57831#endif /* SQLITE_OMIT_UTF16 */
57832SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
57833  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57834  sqlite3VdbeMemCopy(&pCtx->s, pValue);
57835}
57836SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
57837  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57838  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
57839}
57840SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
57841  pCtx->isError = errCode;
57842  if( pCtx->s.flags & MEM_Null ){
57843    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
57844                         SQLITE_UTF8, SQLITE_STATIC);
57845  }
57846}
57847
57848/* Force an SQLITE_TOOBIG error. */
57849SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
57850  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57851  pCtx->isError = SQLITE_TOOBIG;
57852  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
57853                       SQLITE_UTF8, SQLITE_STATIC);
57854}
57855
57856/* An SQLITE_NOMEM error. */
57857SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
57858  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
57859  sqlite3VdbeMemSetNull(&pCtx->s);
57860  pCtx->isError = SQLITE_NOMEM;
57861  pCtx->s.db->mallocFailed = 1;
57862}
57863
57864/*
57865** This function is called after a transaction has been committed. It
57866** invokes callbacks registered with sqlite3_wal_hook() as required.
57867*/
57868static int doWalCallbacks(sqlite3 *db){
57869  int rc = SQLITE_OK;
57870#ifndef SQLITE_OMIT_WAL
57871  int i;
57872  for(i=0; i<db->nDb; i++){
57873    Btree *pBt = db->aDb[i].pBt;
57874    if( pBt ){
57875      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
57876      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
57877        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
57878      }
57879    }
57880  }
57881#endif
57882  return rc;
57883}
57884
57885/*
57886** Execute the statement pStmt, either until a row of data is ready, the
57887** statement is completely executed or an error occurs.
57888**
57889** This routine implements the bulk of the logic behind the sqlite_step()
57890** API.  The only thing omitted is the automatic recompile if a
57891** schema change has occurred.  That detail is handled by the
57892** outer sqlite3_step() wrapper procedure.
57893*/
57894static int sqlite3Step(Vdbe *p){
57895  sqlite3 *db;
57896  int rc;
57897
57898  assert(p);
57899  if( p->magic!=VDBE_MAGIC_RUN ){
57900    /* We used to require that sqlite3_reset() be called before retrying
57901    ** sqlite3_step() after any error.  But after 3.6.23, we changed this
57902    ** so that sqlite3_reset() would be called automatically instead of
57903    ** throwing the error.
57904    */
57905    sqlite3_reset((sqlite3_stmt*)p);
57906  }
57907
57908  /* Check that malloc() has not failed. If it has, return early. */
57909  db = p->db;
57910  if( db->mallocFailed ){
57911    p->rc = SQLITE_NOMEM;
57912    return SQLITE_NOMEM;
57913  }
57914
57915  if( p->pc<=0 && p->expired ){
57916    p->rc = SQLITE_SCHEMA;
57917    rc = SQLITE_ERROR;
57918    goto end_of_step;
57919  }
57920  if( p->pc<0 ){
57921    /* If there are no other statements currently running, then
57922    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
57923    ** from interrupting a statement that has not yet started.
57924    */
57925    if( db->activeVdbeCnt==0 ){
57926      db->u1.isInterrupted = 0;
57927    }
57928
57929    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
57930
57931#ifndef SQLITE_OMIT_TRACE
57932    if( db->xProfile && !db->init.busy ){
57933      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
57934    }
57935#endif
57936
57937    db->activeVdbeCnt++;
57938    if( p->readOnly==0 ) db->writeVdbeCnt++;
57939    p->pc = 0;
57940  }
57941#ifndef SQLITE_OMIT_EXPLAIN
57942  if( p->explain ){
57943    rc = sqlite3VdbeList(p);
57944  }else
57945#endif /* SQLITE_OMIT_EXPLAIN */
57946  {
57947    rc = sqlite3VdbeExec(p);
57948  }
57949
57950#ifndef SQLITE_OMIT_TRACE
57951  /* Invoke the profile callback if there is one
57952  */
57953  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
57954    sqlite3_int64 iNow;
57955    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
57956    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
57957  }
57958#endif
57959
57960  if( rc==SQLITE_DONE ){
57961    assert( p->rc==SQLITE_OK );
57962    p->rc = doWalCallbacks(db);
57963    if( p->rc!=SQLITE_OK ){
57964      rc = SQLITE_ERROR;
57965    }
57966  }
57967
57968  db->errCode = rc;
57969  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
57970    p->rc = SQLITE_NOMEM;
57971  }
57972end_of_step:
57973  /* At this point local variable rc holds the value that should be
57974  ** returned if this statement was compiled using the legacy
57975  ** sqlite3_prepare() interface. According to the docs, this can only
57976  ** be one of the values in the first assert() below. Variable p->rc
57977  ** contains the value that would be returned if sqlite3_finalize()
57978  ** were called on statement p.
57979  */
57980  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
57981       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
57982  );
57983  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
57984  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
57985    /* If this statement was prepared using sqlite3_prepare_v2(), and an
57986    ** error has occured, then return the error code in p->rc to the
57987    ** caller. Set the error code in the database handle to the same value.
57988    */
57989    rc = db->errCode = p->rc;
57990  }
57991  return (rc&db->errMask);
57992}
57993
57994/*
57995** This is the top-level implementation of sqlite3_step().  Call
57996** sqlite3Step() to do most of the work.  If a schema error occurs,
57997** call sqlite3Reprepare() and try again.
57998*/
57999SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
58000  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
58001  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
58002  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
58003  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
58004  sqlite3 *db;             /* The database connection */
58005
58006  if( vdbeSafetyNotNull(v) ){
58007    return SQLITE_MISUSE_BKPT;
58008  }
58009  db = v->db;
58010  sqlite3_mutex_enter(db->mutex);
58011  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
58012         && cnt++ < 5
58013         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
58014    sqlite3_reset(pStmt);
58015    v->expired = 0;
58016  }
58017  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
58018    /* This case occurs after failing to recompile an sql statement.
58019    ** The error message from the SQL compiler has already been loaded
58020    ** into the database handle. This block copies the error message
58021    ** from the database handle into the statement and sets the statement
58022    ** program counter to 0 to ensure that when the statement is
58023    ** finalized or reset the parser error message is available via
58024    ** sqlite3_errmsg() and sqlite3_errcode().
58025    */
58026    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
58027    sqlite3DbFree(db, v->zErrMsg);
58028    if( !db->mallocFailed ){
58029      v->zErrMsg = sqlite3DbStrDup(db, zErr);
58030      v->rc = rc2;
58031    } else {
58032      v->zErrMsg = 0;
58033      v->rc = rc = SQLITE_NOMEM;
58034    }
58035  }
58036  rc = sqlite3ApiExit(db, rc);
58037  sqlite3_mutex_leave(db->mutex);
58038  return rc;
58039}
58040
58041/*
58042** Extract the user data from a sqlite3_context structure and return a
58043** pointer to it.
58044*/
58045SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
58046  assert( p && p->pFunc );
58047  return p->pFunc->pUserData;
58048}
58049
58050/*
58051** Extract the user data from a sqlite3_context structure and return a
58052** pointer to it.
58053*/
58054SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
58055  assert( p && p->pFunc );
58056  return p->s.db;
58057}
58058
58059/*
58060** The following is the implementation of an SQL function that always
58061** fails with an error message stating that the function is used in the
58062** wrong context.  The sqlite3_overload_function() API might construct
58063** SQL function that use this routine so that the functions will exist
58064** for name resolution but are actually overloaded by the xFindFunction
58065** method of virtual tables.
58066*/
58067SQLITE_PRIVATE void sqlite3InvalidFunction(
58068  sqlite3_context *context,  /* The function calling context */
58069  int NotUsed,               /* Number of arguments to the function */
58070  sqlite3_value **NotUsed2   /* Value of each argument */
58071){
58072  const char *zName = context->pFunc->zName;
58073  char *zErr;
58074  UNUSED_PARAMETER2(NotUsed, NotUsed2);
58075  zErr = sqlite3_mprintf(
58076      "unable to use function %s in the requested context", zName);
58077  sqlite3_result_error(context, zErr, -1);
58078  sqlite3_free(zErr);
58079}
58080
58081/*
58082** Allocate or return the aggregate context for a user function.  A new
58083** context is allocated on the first call.  Subsequent calls return the
58084** same context that was returned on prior calls.
58085*/
58086SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
58087  Mem *pMem;
58088  assert( p && p->pFunc && p->pFunc->xStep );
58089  assert( sqlite3_mutex_held(p->s.db->mutex) );
58090  pMem = p->pMem;
58091  testcase( nByte<0 );
58092  if( (pMem->flags & MEM_Agg)==0 ){
58093    if( nByte<=0 ){
58094      sqlite3VdbeMemReleaseExternal(pMem);
58095      pMem->flags = MEM_Null;
58096      pMem->z = 0;
58097    }else{
58098      sqlite3VdbeMemGrow(pMem, nByte, 0);
58099      pMem->flags = MEM_Agg;
58100      pMem->u.pDef = p->pFunc;
58101      if( pMem->z ){
58102        memset(pMem->z, 0, nByte);
58103      }
58104    }
58105  }
58106  return (void*)pMem->z;
58107}
58108
58109/*
58110** Return the auxilary data pointer, if any, for the iArg'th argument to
58111** the user-function defined by pCtx.
58112*/
58113SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
58114  VdbeFunc *pVdbeFunc;
58115
58116  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58117  pVdbeFunc = pCtx->pVdbeFunc;
58118  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
58119    return 0;
58120  }
58121  return pVdbeFunc->apAux[iArg].pAux;
58122}
58123
58124/*
58125** Set the auxilary data pointer and delete function, for the iArg'th
58126** argument to the user-function defined by pCtx. Any previous value is
58127** deleted by calling the delete function specified when it was set.
58128*/
58129SQLITE_API void sqlite3_set_auxdata(
58130  sqlite3_context *pCtx,
58131  int iArg,
58132  void *pAux,
58133  void (*xDelete)(void*)
58134){
58135  struct AuxData *pAuxData;
58136  VdbeFunc *pVdbeFunc;
58137  if( iArg<0 ) goto failed;
58138
58139  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58140  pVdbeFunc = pCtx->pVdbeFunc;
58141  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
58142    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
58143    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
58144    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
58145    if( !pVdbeFunc ){
58146      goto failed;
58147    }
58148    pCtx->pVdbeFunc = pVdbeFunc;
58149    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
58150    pVdbeFunc->nAux = iArg+1;
58151    pVdbeFunc->pFunc = pCtx->pFunc;
58152  }
58153
58154  pAuxData = &pVdbeFunc->apAux[iArg];
58155  if( pAuxData->pAux && pAuxData->xDelete ){
58156    pAuxData->xDelete(pAuxData->pAux);
58157  }
58158  pAuxData->pAux = pAux;
58159  pAuxData->xDelete = xDelete;
58160  return;
58161
58162failed:
58163  if( xDelete ){
58164    xDelete(pAux);
58165  }
58166}
58167
58168#ifndef SQLITE_OMIT_DEPRECATED
58169/*
58170** Return the number of times the Step function of a aggregate has been
58171** called.
58172**
58173** This function is deprecated.  Do not use it for new code.  It is
58174** provide only to avoid breaking legacy code.  New aggregate function
58175** implementations should keep their own counts within their aggregate
58176** context.
58177*/
58178SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
58179  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
58180  return p->pMem->n;
58181}
58182#endif
58183
58184/*
58185** Return the number of columns in the result set for the statement pStmt.
58186*/
58187SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
58188  Vdbe *pVm = (Vdbe *)pStmt;
58189  return pVm ? pVm->nResColumn : 0;
58190}
58191
58192/*
58193** Return the number of values available from the current row of the
58194** currently executing statement pStmt.
58195*/
58196SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
58197  Vdbe *pVm = (Vdbe *)pStmt;
58198  if( pVm==0 || pVm->pResultSet==0 ) return 0;
58199  return pVm->nResColumn;
58200}
58201
58202
58203/*
58204** Check to see if column iCol of the given statement is valid.  If
58205** it is, return a pointer to the Mem for the value of that column.
58206** If iCol is not valid, return a pointer to a Mem which has a value
58207** of NULL.
58208*/
58209static Mem *columnMem(sqlite3_stmt *pStmt, int i){
58210  Vdbe *pVm;
58211  int vals;
58212  Mem *pOut;
58213
58214  pVm = (Vdbe *)pStmt;
58215  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
58216    sqlite3_mutex_enter(pVm->db->mutex);
58217    vals = sqlite3_data_count(pStmt);
58218    pOut = &pVm->pResultSet[i];
58219  }else{
58220    /* If the value passed as the second argument is out of range, return
58221    ** a pointer to the following static Mem object which contains the
58222    ** value SQL NULL. Even though the Mem structure contains an element
58223    ** of type i64, on certain architecture (x86) with certain compiler
58224    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
58225    ** instead of an 8-byte one. This all works fine, except that when
58226    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
58227    ** that a Mem structure is located on an 8-byte boundary. To prevent
58228    ** this assert() from failing, when building with SQLITE_DEBUG defined
58229    ** using gcc, force nullMem to be 8-byte aligned using the magical
58230    ** __attribute__((aligned(8))) macro.  */
58231    static const Mem nullMem
58232#if defined(SQLITE_DEBUG) && defined(__GNUC__)
58233      __attribute__((aligned(8)))
58234#endif
58235      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
58236
58237    if( pVm && ALWAYS(pVm->db) ){
58238      sqlite3_mutex_enter(pVm->db->mutex);
58239      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
58240    }
58241    pOut = (Mem*)&nullMem;
58242  }
58243  return pOut;
58244}
58245
58246/*
58247** This function is called after invoking an sqlite3_value_XXX function on a
58248** column value (i.e. a value returned by evaluating an SQL expression in the
58249** select list of a SELECT statement) that may cause a malloc() failure. If
58250** malloc() has failed, the threads mallocFailed flag is cleared and the result
58251** code of statement pStmt set to SQLITE_NOMEM.
58252**
58253** Specifically, this is called from within:
58254**
58255**     sqlite3_column_int()
58256**     sqlite3_column_int64()
58257**     sqlite3_column_text()
58258**     sqlite3_column_text16()
58259**     sqlite3_column_real()
58260**     sqlite3_column_bytes()
58261**     sqlite3_column_bytes16()
58262**
58263** But not for sqlite3_column_blob(), which never calls malloc().
58264*/
58265static void columnMallocFailure(sqlite3_stmt *pStmt)
58266{
58267  /* If malloc() failed during an encoding conversion within an
58268  ** sqlite3_column_XXX API, then set the return code of the statement to
58269  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
58270  ** and _finalize() will return NOMEM.
58271  */
58272  Vdbe *p = (Vdbe *)pStmt;
58273  if( p ){
58274    p->rc = sqlite3ApiExit(p->db, p->rc);
58275    sqlite3_mutex_leave(p->db->mutex);
58276  }
58277}
58278
58279/**************************** sqlite3_column_  *******************************
58280** The following routines are used to access elements of the current row
58281** in the result set.
58282*/
58283SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
58284  const void *val;
58285  val = sqlite3_value_blob( columnMem(pStmt,i) );
58286  /* Even though there is no encoding conversion, value_blob() might
58287  ** need to call malloc() to expand the result of a zeroblob()
58288  ** expression.
58289  */
58290  columnMallocFailure(pStmt);
58291  return val;
58292}
58293SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
58294  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
58295  columnMallocFailure(pStmt);
58296  return val;
58297}
58298SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
58299  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
58300  columnMallocFailure(pStmt);
58301  return val;
58302}
58303SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
58304  double val = sqlite3_value_double( columnMem(pStmt,i) );
58305  columnMallocFailure(pStmt);
58306  return val;
58307}
58308SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
58309  int val = sqlite3_value_int( columnMem(pStmt,i) );
58310  columnMallocFailure(pStmt);
58311  return val;
58312}
58313SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
58314  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
58315  columnMallocFailure(pStmt);
58316  return val;
58317}
58318SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
58319  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
58320  columnMallocFailure(pStmt);
58321  return val;
58322}
58323SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
58324  Mem *pOut = columnMem(pStmt, i);
58325  if( pOut->flags&MEM_Static ){
58326    pOut->flags &= ~MEM_Static;
58327    pOut->flags |= MEM_Ephem;
58328  }
58329  columnMallocFailure(pStmt);
58330  return (sqlite3_value *)pOut;
58331}
58332#ifndef SQLITE_OMIT_UTF16
58333SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
58334  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
58335  columnMallocFailure(pStmt);
58336  return val;
58337}
58338#endif /* SQLITE_OMIT_UTF16 */
58339SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
58340  int iType = sqlite3_value_type( columnMem(pStmt,i) );
58341  columnMallocFailure(pStmt);
58342  return iType;
58343}
58344
58345/* The following function is experimental and subject to change or
58346** removal */
58347/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
58348**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
58349**}
58350*/
58351
58352/*
58353** Convert the N-th element of pStmt->pColName[] into a string using
58354** xFunc() then return that string.  If N is out of range, return 0.
58355**
58356** There are up to 5 names for each column.  useType determines which
58357** name is returned.  Here are the names:
58358**
58359**    0      The column name as it should be displayed for output
58360**    1      The datatype name for the column
58361**    2      The name of the database that the column derives from
58362**    3      The name of the table that the column derives from
58363**    4      The name of the table column that the result column derives from
58364**
58365** If the result is not a simple column reference (if it is an expression
58366** or a constant) then useTypes 2, 3, and 4 return NULL.
58367*/
58368static const void *columnName(
58369  sqlite3_stmt *pStmt,
58370  int N,
58371  const void *(*xFunc)(Mem*),
58372  int useType
58373){
58374  const void *ret = 0;
58375  Vdbe *p = (Vdbe *)pStmt;
58376  int n;
58377  sqlite3 *db = p->db;
58378
58379  assert( db!=0 );
58380  n = sqlite3_column_count(pStmt);
58381  if( N<n && N>=0 ){
58382    N += useType*n;
58383    sqlite3_mutex_enter(db->mutex);
58384    assert( db->mallocFailed==0 );
58385    ret = xFunc(&p->aColName[N]);
58386     /* A malloc may have failed inside of the xFunc() call. If this
58387    ** is the case, clear the mallocFailed flag and return NULL.
58388    */
58389    if( db->mallocFailed ){
58390      db->mallocFailed = 0;
58391      ret = 0;
58392    }
58393    sqlite3_mutex_leave(db->mutex);
58394  }
58395  return ret;
58396}
58397
58398/*
58399** Return the name of the Nth column of the result set returned by SQL
58400** statement pStmt.
58401*/
58402SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
58403  return columnName(
58404      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
58405}
58406#ifndef SQLITE_OMIT_UTF16
58407SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
58408  return columnName(
58409      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
58410}
58411#endif
58412
58413/*
58414** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
58415** not define OMIT_DECLTYPE.
58416*/
58417#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
58418# error "Must not define both SQLITE_OMIT_DECLTYPE \
58419         and SQLITE_ENABLE_COLUMN_METADATA"
58420#endif
58421
58422#ifndef SQLITE_OMIT_DECLTYPE
58423/*
58424** Return the column declaration type (if applicable) of the 'i'th column
58425** of the result set of SQL statement pStmt.
58426*/
58427SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
58428  return columnName(
58429      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
58430}
58431#ifndef SQLITE_OMIT_UTF16
58432SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
58433  return columnName(
58434      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
58435}
58436#endif /* SQLITE_OMIT_UTF16 */
58437#endif /* SQLITE_OMIT_DECLTYPE */
58438
58439#ifdef SQLITE_ENABLE_COLUMN_METADATA
58440/*
58441** Return the name of the database from which a result column derives.
58442** NULL is returned if the result column is an expression or constant or
58443** anything else which is not an unabiguous reference to a database column.
58444*/
58445SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
58446  return columnName(
58447      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
58448}
58449#ifndef SQLITE_OMIT_UTF16
58450SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
58451  return columnName(
58452      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
58453}
58454#endif /* SQLITE_OMIT_UTF16 */
58455
58456/*
58457** Return the name of the table from which a result column derives.
58458** NULL is returned if the result column is an expression or constant or
58459** anything else which is not an unabiguous reference to a database column.
58460*/
58461SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
58462  return columnName(
58463      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
58464}
58465#ifndef SQLITE_OMIT_UTF16
58466SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
58467  return columnName(
58468      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
58469}
58470#endif /* SQLITE_OMIT_UTF16 */
58471
58472/*
58473** Return the name of the table column from which a result column derives.
58474** NULL is returned if the result column is an expression or constant or
58475** anything else which is not an unabiguous reference to a database column.
58476*/
58477SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
58478  return columnName(
58479      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
58480}
58481#ifndef SQLITE_OMIT_UTF16
58482SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
58483  return columnName(
58484      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
58485}
58486#endif /* SQLITE_OMIT_UTF16 */
58487#endif /* SQLITE_ENABLE_COLUMN_METADATA */
58488
58489
58490/******************************* sqlite3_bind_  ***************************
58491**
58492** Routines used to attach values to wildcards in a compiled SQL statement.
58493*/
58494/*
58495** Unbind the value bound to variable i in virtual machine p. This is the
58496** the same as binding a NULL value to the column. If the "i" parameter is
58497** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
58498**
58499** A successful evaluation of this routine acquires the mutex on p.
58500** the mutex is released if any kind of error occurs.
58501**
58502** The error code stored in database p->db is overwritten with the return
58503** value in any case.
58504*/
58505static int vdbeUnbind(Vdbe *p, int i){
58506  Mem *pVar;
58507  if( vdbeSafetyNotNull(p) ){
58508    return SQLITE_MISUSE_BKPT;
58509  }
58510  sqlite3_mutex_enter(p->db->mutex);
58511  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
58512    sqlite3Error(p->db, SQLITE_MISUSE, 0);
58513    sqlite3_mutex_leave(p->db->mutex);
58514    sqlite3_log(SQLITE_MISUSE,
58515        "bind on a busy prepared statement: [%s]", p->zSql);
58516    return SQLITE_MISUSE_BKPT;
58517  }
58518  if( i<1 || i>p->nVar ){
58519    sqlite3Error(p->db, SQLITE_RANGE, 0);
58520    sqlite3_mutex_leave(p->db->mutex);
58521    return SQLITE_RANGE;
58522  }
58523  i--;
58524  pVar = &p->aVar[i];
58525  sqlite3VdbeMemRelease(pVar);
58526  pVar->flags = MEM_Null;
58527  sqlite3Error(p->db, SQLITE_OK, 0);
58528
58529  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
58530  ** binding a new value to this variable invalidates the current query plan.
58531  */
58532  if( p->isPrepareV2 &&
58533     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
58534  ){
58535    p->expired = 1;
58536  }
58537  return SQLITE_OK;
58538}
58539
58540/*
58541** Bind a text or BLOB value.
58542*/
58543static int bindText(
58544  sqlite3_stmt *pStmt,   /* The statement to bind against */
58545  int i,                 /* Index of the parameter to bind */
58546  const void *zData,     /* Pointer to the data to be bound */
58547  int nData,             /* Number of bytes of data to be bound */
58548  void (*xDel)(void*),   /* Destructor for the data */
58549  u8 encoding            /* Encoding for the data */
58550){
58551  Vdbe *p = (Vdbe *)pStmt;
58552  Mem *pVar;
58553  int rc;
58554
58555  rc = vdbeUnbind(p, i);
58556  if( rc==SQLITE_OK ){
58557    if( zData!=0 ){
58558      pVar = &p->aVar[i-1];
58559      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
58560      if( rc==SQLITE_OK && encoding!=0 ){
58561        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
58562      }
58563      sqlite3Error(p->db, rc, 0);
58564      rc = sqlite3ApiExit(p->db, rc);
58565    }
58566    sqlite3_mutex_leave(p->db->mutex);
58567  }
58568  return rc;
58569}
58570
58571
58572/*
58573** Bind a blob value to an SQL statement variable.
58574*/
58575SQLITE_API int sqlite3_bind_blob(
58576  sqlite3_stmt *pStmt,
58577  int i,
58578  const void *zData,
58579  int nData,
58580  void (*xDel)(void*)
58581){
58582  return bindText(pStmt, i, zData, nData, xDel, 0);
58583}
58584SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
58585  int rc;
58586  Vdbe *p = (Vdbe *)pStmt;
58587  rc = vdbeUnbind(p, i);
58588  if( rc==SQLITE_OK ){
58589    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
58590    sqlite3_mutex_leave(p->db->mutex);
58591  }
58592  return rc;
58593}
58594SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
58595  return sqlite3_bind_int64(p, i, (i64)iValue);
58596}
58597SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
58598  int rc;
58599  Vdbe *p = (Vdbe *)pStmt;
58600  rc = vdbeUnbind(p, i);
58601  if( rc==SQLITE_OK ){
58602    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
58603    sqlite3_mutex_leave(p->db->mutex);
58604  }
58605  return rc;
58606}
58607SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
58608  int rc;
58609  Vdbe *p = (Vdbe*)pStmt;
58610  rc = vdbeUnbind(p, i);
58611  if( rc==SQLITE_OK ){
58612    sqlite3_mutex_leave(p->db->mutex);
58613  }
58614  return rc;
58615}
58616SQLITE_API int sqlite3_bind_text(
58617  sqlite3_stmt *pStmt,
58618  int i,
58619  const char *zData,
58620  int nData,
58621  void (*xDel)(void*)
58622){
58623  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
58624}
58625#ifndef SQLITE_OMIT_UTF16
58626SQLITE_API int sqlite3_bind_text16(
58627  sqlite3_stmt *pStmt,
58628  int i,
58629  const void *zData,
58630  int nData,
58631  void (*xDel)(void*)
58632){
58633  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
58634}
58635#endif /* SQLITE_OMIT_UTF16 */
58636SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
58637  int rc;
58638  switch( pValue->type ){
58639    case SQLITE_INTEGER: {
58640      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
58641      break;
58642    }
58643    case SQLITE_FLOAT: {
58644      rc = sqlite3_bind_double(pStmt, i, pValue->r);
58645      break;
58646    }
58647    case SQLITE_BLOB: {
58648      if( pValue->flags & MEM_Zero ){
58649        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
58650      }else{
58651        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
58652      }
58653      break;
58654    }
58655    case SQLITE_TEXT: {
58656      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
58657                              pValue->enc);
58658      break;
58659    }
58660    default: {
58661      rc = sqlite3_bind_null(pStmt, i);
58662      break;
58663    }
58664  }
58665  return rc;
58666}
58667SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
58668  int rc;
58669  Vdbe *p = (Vdbe *)pStmt;
58670  rc = vdbeUnbind(p, i);
58671  if( rc==SQLITE_OK ){
58672    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
58673    sqlite3_mutex_leave(p->db->mutex);
58674  }
58675  return rc;
58676}
58677
58678/*
58679** Return the number of wildcards that can be potentially bound to.
58680** This routine is added to support DBD::SQLite.
58681*/
58682SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
58683  Vdbe *p = (Vdbe*)pStmt;
58684  return p ? p->nVar : 0;
58685}
58686
58687/*
58688** Create a mapping from variable numbers to variable names
58689** in the Vdbe.azVar[] array, if such a mapping does not already
58690** exist.
58691*/
58692static void createVarMap(Vdbe *p){
58693  if( !p->okVar ){
58694    int j;
58695    Op *pOp;
58696    sqlite3_mutex_enter(p->db->mutex);
58697    /* The race condition here is harmless.  If two threads call this
58698    ** routine on the same Vdbe at the same time, they both might end
58699    ** up initializing the Vdbe.azVar[] array.  That is a little extra
58700    ** work but it results in the same answer.
58701    */
58702    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
58703      if( pOp->opcode==OP_Variable ){
58704        assert( pOp->p1>0 && pOp->p1<=p->nVar );
58705        p->azVar[pOp->p1-1] = pOp->p4.z;
58706      }
58707    }
58708    p->okVar = 1;
58709    sqlite3_mutex_leave(p->db->mutex);
58710  }
58711}
58712
58713/*
58714** Return the name of a wildcard parameter.  Return NULL if the index
58715** is out of range or if the wildcard is unnamed.
58716**
58717** The result is always UTF-8.
58718*/
58719SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
58720  Vdbe *p = (Vdbe*)pStmt;
58721  if( p==0 || i<1 || i>p->nVar ){
58722    return 0;
58723  }
58724  createVarMap(p);
58725  return p->azVar[i-1];
58726}
58727
58728/*
58729** Given a wildcard parameter name, return the index of the variable
58730** with that name.  If there is no variable with the given name,
58731** return 0.
58732*/
58733SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
58734  int i;
58735  if( p==0 ){
58736    return 0;
58737  }
58738  createVarMap(p);
58739  if( zName ){
58740    for(i=0; i<p->nVar; i++){
58741      const char *z = p->azVar[i];
58742      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
58743        return i+1;
58744      }
58745    }
58746  }
58747  return 0;
58748}
58749SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
58750  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
58751}
58752
58753/*
58754** Transfer all bindings from the first statement over to the second.
58755*/
58756SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
58757  Vdbe *pFrom = (Vdbe*)pFromStmt;
58758  Vdbe *pTo = (Vdbe*)pToStmt;
58759  int i;
58760  assert( pTo->db==pFrom->db );
58761  assert( pTo->nVar==pFrom->nVar );
58762  sqlite3_mutex_enter(pTo->db->mutex);
58763  for(i=0; i<pFrom->nVar; i++){
58764    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
58765  }
58766  sqlite3_mutex_leave(pTo->db->mutex);
58767  return SQLITE_OK;
58768}
58769
58770#ifndef SQLITE_OMIT_DEPRECATED
58771/*
58772** Deprecated external interface.  Internal/core SQLite code
58773** should call sqlite3TransferBindings.
58774**
58775** Is is misuse to call this routine with statements from different
58776** database connections.  But as this is a deprecated interface, we
58777** will not bother to check for that condition.
58778**
58779** If the two statements contain a different number of bindings, then
58780** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
58781** SQLITE_OK is returned.
58782*/
58783SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
58784  Vdbe *pFrom = (Vdbe*)pFromStmt;
58785  Vdbe *pTo = (Vdbe*)pToStmt;
58786  if( pFrom->nVar!=pTo->nVar ){
58787    return SQLITE_ERROR;
58788  }
58789  if( pTo->isPrepareV2 && pTo->expmask ){
58790    pTo->expired = 1;
58791  }
58792  if( pFrom->isPrepareV2 && pFrom->expmask ){
58793    pFrom->expired = 1;
58794  }
58795  return sqlite3TransferBindings(pFromStmt, pToStmt);
58796}
58797#endif
58798
58799/*
58800** Return the sqlite3* database handle to which the prepared statement given
58801** in the argument belongs.  This is the same database handle that was
58802** the first argument to the sqlite3_prepare() that was used to create
58803** the statement in the first place.
58804*/
58805SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
58806  return pStmt ? ((Vdbe*)pStmt)->db : 0;
58807}
58808
58809/*
58810** Return a pointer to the next prepared statement after pStmt associated
58811** with database connection pDb.  If pStmt is NULL, return the first
58812** prepared statement for the database connection.  Return NULL if there
58813** are no more.
58814*/
58815SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
58816  sqlite3_stmt *pNext;
58817  sqlite3_mutex_enter(pDb->mutex);
58818  if( pStmt==0 ){
58819    pNext = (sqlite3_stmt*)pDb->pVdbe;
58820  }else{
58821    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
58822  }
58823  sqlite3_mutex_leave(pDb->mutex);
58824  return pNext;
58825}
58826
58827/*
58828** Return the value of a status counter for a prepared statement
58829*/
58830SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
58831  Vdbe *pVdbe = (Vdbe*)pStmt;
58832  int v = pVdbe->aCounter[op-1];
58833  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
58834  return v;
58835}
58836
58837/************** End of vdbeapi.c *********************************************/
58838/************** Begin file vdbetrace.c ***************************************/
58839/*
58840** 2009 November 25
58841**
58842** The author disclaims copyright to this source code.  In place of
58843** a legal notice, here is a blessing:
58844**
58845**    May you do good and not evil.
58846**    May you find forgiveness for yourself and forgive others.
58847**    May you share freely, never taking more than you give.
58848**
58849*************************************************************************
58850**
58851** This file contains code used to insert the values of host parameters
58852** (aka "wildcards") into the SQL text output by sqlite3_trace().
58853*/
58854
58855#ifndef SQLITE_OMIT_TRACE
58856
58857/*
58858** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
58859** bytes in this text up to but excluding the first character in
58860** a host parameter.  If the text contains no host parameters, return
58861** the total number of bytes in the text.
58862*/
58863static int findNextHostParameter(const char *zSql, int *pnToken){
58864  int tokenType;
58865  int nTotal = 0;
58866  int n;
58867
58868  *pnToken = 0;
58869  while( zSql[0] ){
58870    n = sqlite3GetToken((u8*)zSql, &tokenType);
58871    assert( n>0 && tokenType!=TK_ILLEGAL );
58872    if( tokenType==TK_VARIABLE ){
58873      *pnToken = n;
58874      break;
58875    }
58876    nTotal += n;
58877    zSql += n;
58878  }
58879  return nTotal;
58880}
58881
58882/*
58883** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
58884** holds a copy of zRawSql but with host parameters expanded to their
58885** current bindings.
58886**
58887** The calling function is responsible for making sure the memory returned
58888** is eventually freed.
58889**
58890** ALGORITHM:  Scan the input string looking for host parameters in any of
58891** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
58892** string literals, quoted identifier names, and comments.  For text forms,
58893** the host parameter index is found by scanning the perpared
58894** statement for the corresponding OP_Variable opcode.  Once the host
58895** parameter index is known, locate the value in p->aVar[].  Then render
58896** the value as a literal in place of the host parameter name.
58897*/
58898SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
58899  Vdbe *p,                 /* The prepared statement being evaluated */
58900  const char *zRawSql      /* Raw text of the SQL statement */
58901){
58902  sqlite3 *db;             /* The database connection */
58903  int idx = 0;             /* Index of a host parameter */
58904  int nextIndex = 1;       /* Index of next ? host parameter */
58905  int n;                   /* Length of a token prefix */
58906  int nToken;              /* Length of the parameter token */
58907  int i;                   /* Loop counter */
58908  Mem *pVar;               /* Value of a host parameter */
58909  StrAccum out;            /* Accumulate the output here */
58910  char zBase[100];         /* Initial working space */
58911
58912  db = p->db;
58913  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
58914                      db->aLimit[SQLITE_LIMIT_LENGTH]);
58915  out.db = db;
58916  while( zRawSql[0] ){
58917    n = findNextHostParameter(zRawSql, &nToken);
58918    assert( n>0 );
58919    sqlite3StrAccumAppend(&out, zRawSql, n);
58920    zRawSql += n;
58921    assert( zRawSql[0] || nToken==0 );
58922    if( nToken==0 ) break;
58923    if( zRawSql[0]=='?' ){
58924      if( nToken>1 ){
58925        assert( sqlite3Isdigit(zRawSql[1]) );
58926        sqlite3GetInt32(&zRawSql[1], &idx);
58927      }else{
58928        idx = nextIndex;
58929      }
58930    }else{
58931      assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
58932      testcase( zRawSql[0]==':' );
58933      testcase( zRawSql[0]=='$' );
58934      testcase( zRawSql[0]=='@' );
58935      idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
58936      assert( idx>0 );
58937    }
58938    zRawSql += nToken;
58939    nextIndex = idx + 1;
58940    assert( idx>0 && idx<=p->nVar );
58941    pVar = &p->aVar[idx-1];
58942    if( pVar->flags & MEM_Null ){
58943      sqlite3StrAccumAppend(&out, "NULL", 4);
58944    }else if( pVar->flags & MEM_Int ){
58945      sqlite3XPrintf(&out, "%lld", pVar->u.i);
58946    }else if( pVar->flags & MEM_Real ){
58947      sqlite3XPrintf(&out, "%!.15g", pVar->r);
58948    }else if( pVar->flags & MEM_Str ){
58949#ifndef SQLITE_OMIT_UTF16
58950      u8 enc = ENC(db);
58951      if( enc!=SQLITE_UTF8 ){
58952        Mem utf8;
58953        memset(&utf8, 0, sizeof(utf8));
58954        utf8.db = db;
58955        sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
58956        sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
58957        sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
58958        sqlite3VdbeMemRelease(&utf8);
58959      }else
58960#endif
58961      {
58962        sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
58963      }
58964    }else if( pVar->flags & MEM_Zero ){
58965      sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
58966    }else{
58967      assert( pVar->flags & MEM_Blob );
58968      sqlite3StrAccumAppend(&out, "x'", 2);
58969      for(i=0; i<pVar->n; i++){
58970        sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
58971      }
58972      sqlite3StrAccumAppend(&out, "'", 1);
58973    }
58974  }
58975  return sqlite3StrAccumFinish(&out);
58976}
58977
58978#endif /* #ifndef SQLITE_OMIT_TRACE */
58979
58980/************** End of vdbetrace.c *******************************************/
58981/************** Begin file vdbe.c ********************************************/
58982/*
58983** 2001 September 15
58984**
58985** The author disclaims copyright to this source code.  In place of
58986** a legal notice, here is a blessing:
58987**
58988**    May you do good and not evil.
58989**    May you find forgiveness for yourself and forgive others.
58990**    May you share freely, never taking more than you give.
58991**
58992*************************************************************************
58993** The code in this file implements execution method of the
58994** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
58995** handles housekeeping details such as creating and deleting
58996** VDBE instances.  This file is solely interested in executing
58997** the VDBE program.
58998**
58999** In the external interface, an "sqlite3_stmt*" is an opaque pointer
59000** to a VDBE.
59001**
59002** The SQL parser generates a program which is then executed by
59003** the VDBE to do the work of the SQL statement.  VDBE programs are
59004** similar in form to assembly language.  The program consists of
59005** a linear sequence of operations.  Each operation has an opcode
59006** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
59007** is a null-terminated string.  Operand P5 is an unsigned character.
59008** Few opcodes use all 5 operands.
59009**
59010** Computation results are stored on a set of registers numbered beginning
59011** with 1 and going up to Vdbe.nMem.  Each register can store
59012** either an integer, a null-terminated string, a floating point
59013** number, or the SQL "NULL" value.  An implicit conversion from one
59014** type to the other occurs as necessary.
59015**
59016** Most of the code in this file is taken up by the sqlite3VdbeExec()
59017** function which does the work of interpreting a VDBE program.
59018** But other routines are also provided to help in building up
59019** a program instruction by instruction.
59020**
59021** Various scripts scan this source file in order to generate HTML
59022** documentation, headers files, or other derived files.  The formatting
59023** of the code in this file is, therefore, important.  See other comments
59024** in this file for details.  If in doubt, do not deviate from existing
59025** commenting and indentation practices when changing or adding code.
59026*/
59027
59028/*
59029** The following global variable is incremented every time a cursor
59030** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
59031** procedures use this information to make sure that indices are
59032** working correctly.  This variable has no function other than to
59033** help verify the correct operation of the library.
59034*/
59035#ifdef SQLITE_TEST
59036SQLITE_API int sqlite3_search_count = 0;
59037#endif
59038
59039/*
59040** When this global variable is positive, it gets decremented once before
59041** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
59042** field of the sqlite3 structure is set in order to simulate and interrupt.
59043**
59044** This facility is used for testing purposes only.  It does not function
59045** in an ordinary build.
59046*/
59047#ifdef SQLITE_TEST
59048SQLITE_API int sqlite3_interrupt_count = 0;
59049#endif
59050
59051/*
59052** The next global variable is incremented each type the OP_Sort opcode
59053** is executed.  The test procedures use this information to make sure that
59054** sorting is occurring or not occurring at appropriate times.   This variable
59055** has no function other than to help verify the correct operation of the
59056** library.
59057*/
59058#ifdef SQLITE_TEST
59059SQLITE_API int sqlite3_sort_count = 0;
59060#endif
59061
59062/*
59063** The next global variable records the size of the largest MEM_Blob
59064** or MEM_Str that has been used by a VDBE opcode.  The test procedures
59065** use this information to make sure that the zero-blob functionality
59066** is working correctly.   This variable has no function other than to
59067** help verify the correct operation of the library.
59068*/
59069#ifdef SQLITE_TEST
59070SQLITE_API int sqlite3_max_blobsize = 0;
59071static void updateMaxBlobsize(Mem *p){
59072  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
59073    sqlite3_max_blobsize = p->n;
59074  }
59075}
59076#endif
59077
59078/*
59079** The next global variable is incremented each type the OP_Found opcode
59080** is executed. This is used to test whether or not the foreign key
59081** operation implemented using OP_FkIsZero is working. This variable
59082** has no function other than to help verify the correct operation of the
59083** library.
59084*/
59085#ifdef SQLITE_TEST
59086SQLITE_API int sqlite3_found_count = 0;
59087#endif
59088
59089/*
59090** Test a register to see if it exceeds the current maximum blob size.
59091** If it does, record the new maximum blob size.
59092*/
59093#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
59094# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
59095#else
59096# define UPDATE_MAX_BLOBSIZE(P)
59097#endif
59098
59099/*
59100** Convert the given register into a string if it isn't one
59101** already. Return non-zero if a malloc() fails.
59102*/
59103#define Stringify(P, enc) \
59104   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
59105     { goto no_mem; }
59106
59107/*
59108** An ephemeral string value (signified by the MEM_Ephem flag) contains
59109** a pointer to a dynamically allocated string where some other entity
59110** is responsible for deallocating that string.  Because the register
59111** does not control the string, it might be deleted without the register
59112** knowing it.
59113**
59114** This routine converts an ephemeral string into a dynamically allocated
59115** string that the register itself controls.  In other words, it
59116** converts an MEM_Ephem string into an MEM_Dyn string.
59117*/
59118#define Deephemeralize(P) \
59119   if( ((P)->flags&MEM_Ephem)!=0 \
59120       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
59121
59122/*
59123** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
59124** P if required.
59125*/
59126#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
59127
59128/*
59129** Argument pMem points at a register that will be passed to a
59130** user-defined function or returned to the user as the result of a query.
59131** This routine sets the pMem->type variable used by the sqlite3_value_*()
59132** routines.
59133*/
59134SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
59135  int flags = pMem->flags;
59136  if( flags & MEM_Null ){
59137    pMem->type = SQLITE_NULL;
59138  }
59139  else if( flags & MEM_Int ){
59140    pMem->type = SQLITE_INTEGER;
59141  }
59142  else if( flags & MEM_Real ){
59143    pMem->type = SQLITE_FLOAT;
59144  }
59145  else if( flags & MEM_Str ){
59146    pMem->type = SQLITE_TEXT;
59147  }else{
59148    pMem->type = SQLITE_BLOB;
59149  }
59150}
59151
59152/*
59153** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
59154** if we run out of memory.
59155*/
59156static VdbeCursor *allocateCursor(
59157  Vdbe *p,              /* The virtual machine */
59158  int iCur,             /* Index of the new VdbeCursor */
59159  int nField,           /* Number of fields in the table or index */
59160  int iDb,              /* When database the cursor belongs to, or -1 */
59161  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
59162){
59163  /* Find the memory cell that will be used to store the blob of memory
59164  ** required for this VdbeCursor structure. It is convenient to use a
59165  ** vdbe memory cell to manage the memory allocation required for a
59166  ** VdbeCursor structure for the following reasons:
59167  **
59168  **   * Sometimes cursor numbers are used for a couple of different
59169  **     purposes in a vdbe program. The different uses might require
59170  **     different sized allocations. Memory cells provide growable
59171  **     allocations.
59172  **
59173  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
59174  **     be freed lazily via the sqlite3_release_memory() API. This
59175  **     minimizes the number of malloc calls made by the system.
59176  **
59177  ** Memory cells for cursors are allocated at the top of the address
59178  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
59179  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
59180  */
59181  Mem *pMem = &p->aMem[p->nMem-iCur];
59182
59183  int nByte;
59184  VdbeCursor *pCx = 0;
59185  nByte =
59186      ROUND8(sizeof(VdbeCursor)) +
59187      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
59188      2*nField*sizeof(u32);
59189
59190  assert( iCur<p->nCursor );
59191  if( p->apCsr[iCur] ){
59192    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
59193    p->apCsr[iCur] = 0;
59194  }
59195  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59196    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
59197    memset(pCx, 0, sizeof(VdbeCursor));
59198    pCx->iDb = iDb;
59199    pCx->nField = nField;
59200    if( nField ){
59201      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
59202    }
59203    if( isBtreeCursor ){
59204      pCx->pCursor = (BtCursor*)
59205          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
59206      sqlite3BtreeCursorZero(pCx->pCursor);
59207    }
59208  }
59209  return pCx;
59210}
59211
59212/*
59213** Try to convert a value into a numeric representation if we can
59214** do so without loss of information.  In other words, if the string
59215** looks like a number, convert it into a number.  If it does not
59216** look like a number, leave it alone.
59217*/
59218static void applyNumericAffinity(Mem *pRec){
59219  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
59220    int realnum;
59221    u8 enc = pRec->enc;
59222    sqlite3VdbeMemNulTerminate(pRec);
59223    if( (pRec->flags&MEM_Str) && sqlite3IsNumber(pRec->z, &realnum, enc) ){
59224      i64 value;
59225      char *zUtf8 = pRec->z;
59226#ifndef SQLITE_OMIT_UTF16
59227      if( enc!=SQLITE_UTF8 ){
59228        assert( pRec->db );
59229        zUtf8 = sqlite3Utf16to8(pRec->db, pRec->z, pRec->n, enc);
59230        if( !zUtf8 ) return;
59231      }
59232#endif
59233      if( !realnum && sqlite3Atoi64(zUtf8, &value) ){
59234        pRec->u.i = value;
59235        MemSetTypeFlag(pRec, MEM_Int);
59236      }else{
59237        sqlite3AtoF(zUtf8, &pRec->r);
59238        MemSetTypeFlag(pRec, MEM_Real);
59239      }
59240#ifndef SQLITE_OMIT_UTF16
59241      if( enc!=SQLITE_UTF8 ){
59242        sqlite3DbFree(pRec->db, zUtf8);
59243      }
59244#endif
59245    }
59246  }
59247}
59248
59249/*
59250** Processing is determine by the affinity parameter:
59251**
59252** SQLITE_AFF_INTEGER:
59253** SQLITE_AFF_REAL:
59254** SQLITE_AFF_NUMERIC:
59255**    Try to convert pRec to an integer representation or a
59256**    floating-point representation if an integer representation
59257**    is not possible.  Note that the integer representation is
59258**    always preferred, even if the affinity is REAL, because
59259**    an integer representation is more space efficient on disk.
59260**
59261** SQLITE_AFF_TEXT:
59262**    Convert pRec to a text representation.
59263**
59264** SQLITE_AFF_NONE:
59265**    No-op.  pRec is unchanged.
59266*/
59267static void applyAffinity(
59268  Mem *pRec,          /* The value to apply affinity to */
59269  char affinity,      /* The affinity to be applied */
59270  u8 enc              /* Use this text encoding */
59271){
59272  if( affinity==SQLITE_AFF_TEXT ){
59273    /* Only attempt the conversion to TEXT if there is an integer or real
59274    ** representation (blob and NULL do not get converted) but no string
59275    ** representation.
59276    */
59277    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
59278      sqlite3VdbeMemStringify(pRec, enc);
59279    }
59280    pRec->flags &= ~(MEM_Real|MEM_Int);
59281  }else if( affinity!=SQLITE_AFF_NONE ){
59282    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
59283             || affinity==SQLITE_AFF_NUMERIC );
59284    applyNumericAffinity(pRec);
59285    if( pRec->flags & MEM_Real ){
59286      sqlite3VdbeIntegerAffinity(pRec);
59287    }
59288  }
59289}
59290
59291/*
59292** Try to convert the type of a function argument or a result column
59293** into a numeric representation.  Use either INTEGER or REAL whichever
59294** is appropriate.  But only do the conversion if it is possible without
59295** loss of information and return the revised type of the argument.
59296**
59297** This is an EXPERIMENTAL api and is subject to change or removal.
59298*/
59299SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
59300  Mem *pMem = (Mem*)pVal;
59301  applyNumericAffinity(pMem);
59302  sqlite3VdbeMemStoreType(pMem);
59303  return pMem->type;
59304}
59305
59306/*
59307** Exported version of applyAffinity(). This one works on sqlite3_value*,
59308** not the internal Mem* type.
59309*/
59310SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
59311  sqlite3_value *pVal,
59312  u8 affinity,
59313  u8 enc
59314){
59315  applyAffinity((Mem *)pVal, affinity, enc);
59316}
59317
59318#ifdef SQLITE_DEBUG
59319/*
59320** Write a nice string representation of the contents of cell pMem
59321** into buffer zBuf, length nBuf.
59322*/
59323SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
59324  char *zCsr = zBuf;
59325  int f = pMem->flags;
59326
59327  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
59328
59329  if( f&MEM_Blob ){
59330    int i;
59331    char c;
59332    if( f & MEM_Dyn ){
59333      c = 'z';
59334      assert( (f & (MEM_Static|MEM_Ephem))==0 );
59335    }else if( f & MEM_Static ){
59336      c = 't';
59337      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
59338    }else if( f & MEM_Ephem ){
59339      c = 'e';
59340      assert( (f & (MEM_Static|MEM_Dyn))==0 );
59341    }else{
59342      c = 's';
59343    }
59344
59345    sqlite3_snprintf(100, zCsr, "%c", c);
59346    zCsr += sqlite3Strlen30(zCsr);
59347    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
59348    zCsr += sqlite3Strlen30(zCsr);
59349    for(i=0; i<16 && i<pMem->n; i++){
59350      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
59351      zCsr += sqlite3Strlen30(zCsr);
59352    }
59353    for(i=0; i<16 && i<pMem->n; i++){
59354      char z = pMem->z[i];
59355      if( z<32 || z>126 ) *zCsr++ = '.';
59356      else *zCsr++ = z;
59357    }
59358
59359    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
59360    zCsr += sqlite3Strlen30(zCsr);
59361    if( f & MEM_Zero ){
59362      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
59363      zCsr += sqlite3Strlen30(zCsr);
59364    }
59365    *zCsr = '\0';
59366  }else if( f & MEM_Str ){
59367    int j, k;
59368    zBuf[0] = ' ';
59369    if( f & MEM_Dyn ){
59370      zBuf[1] = 'z';
59371      assert( (f & (MEM_Static|MEM_Ephem))==0 );
59372    }else if( f & MEM_Static ){
59373      zBuf[1] = 't';
59374      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
59375    }else if( f & MEM_Ephem ){
59376      zBuf[1] = 'e';
59377      assert( (f & (MEM_Static|MEM_Dyn))==0 );
59378    }else{
59379      zBuf[1] = 's';
59380    }
59381    k = 2;
59382    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
59383    k += sqlite3Strlen30(&zBuf[k]);
59384    zBuf[k++] = '[';
59385    for(j=0; j<15 && j<pMem->n; j++){
59386      u8 c = pMem->z[j];
59387      if( c>=0x20 && c<0x7f ){
59388        zBuf[k++] = c;
59389      }else{
59390        zBuf[k++] = '.';
59391      }
59392    }
59393    zBuf[k++] = ']';
59394    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
59395    k += sqlite3Strlen30(&zBuf[k]);
59396    zBuf[k++] = 0;
59397  }
59398}
59399#endif
59400
59401#ifdef SQLITE_DEBUG
59402/*
59403** Print the value of a register for tracing purposes:
59404*/
59405static void memTracePrint(FILE *out, Mem *p){
59406  if( p->flags & MEM_Null ){
59407    fprintf(out, " NULL");
59408  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
59409    fprintf(out, " si:%lld", p->u.i);
59410  }else if( p->flags & MEM_Int ){
59411    fprintf(out, " i:%lld", p->u.i);
59412#ifndef SQLITE_OMIT_FLOATING_POINT
59413  }else if( p->flags & MEM_Real ){
59414    fprintf(out, " r:%g", p->r);
59415#endif
59416  }else if( p->flags & MEM_RowSet ){
59417    fprintf(out, " (rowset)");
59418  }else{
59419    char zBuf[200];
59420    sqlite3VdbeMemPrettyPrint(p, zBuf);
59421    fprintf(out, " ");
59422    fprintf(out, "%s", zBuf);
59423  }
59424}
59425static void registerTrace(FILE *out, int iReg, Mem *p){
59426  fprintf(out, "REG[%d] = ", iReg);
59427  memTracePrint(out, p);
59428  fprintf(out, "\n");
59429}
59430#endif
59431
59432#ifdef SQLITE_DEBUG
59433#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
59434#else
59435#  define REGISTER_TRACE(R,M)
59436#endif
59437
59438
59439#ifdef VDBE_PROFILE
59440
59441/*
59442** hwtime.h contains inline assembler code for implementing
59443** high-performance timing routines.
59444*/
59445/************** Include hwtime.h in the middle of vdbe.c *********************/
59446/************** Begin file hwtime.h ******************************************/
59447/*
59448** 2008 May 27
59449**
59450** The author disclaims copyright to this source code.  In place of
59451** a legal notice, here is a blessing:
59452**
59453**    May you do good and not evil.
59454**    May you find forgiveness for yourself and forgive others.
59455**    May you share freely, never taking more than you give.
59456**
59457******************************************************************************
59458**
59459** This file contains inline asm code for retrieving "high-performance"
59460** counters for x86 class CPUs.
59461*/
59462#ifndef _HWTIME_H_
59463#define _HWTIME_H_
59464
59465/*
59466** The following routine only works on pentium-class (or newer) processors.
59467** It uses the RDTSC opcode to read the cycle count value out of the
59468** processor and returns that value.  This can be used for high-res
59469** profiling.
59470*/
59471#if (defined(__GNUC__) || defined(_MSC_VER)) && \
59472      (defined(i386) || defined(__i386__) || defined(_M_IX86))
59473
59474  #if defined(__GNUC__)
59475
59476  __inline__ sqlite_uint64 sqlite3Hwtime(void){
59477     unsigned int lo, hi;
59478     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
59479     return (sqlite_uint64)hi << 32 | lo;
59480  }
59481
59482  #elif defined(_MSC_VER)
59483
59484  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
59485     __asm {
59486        rdtsc
59487        ret       ; return value at EDX:EAX
59488     }
59489  }
59490
59491  #endif
59492
59493#elif (defined(__GNUC__) && defined(__x86_64__))
59494
59495  __inline__ sqlite_uint64 sqlite3Hwtime(void){
59496      unsigned long val;
59497      __asm__ __volatile__ ("rdtsc" : "=A" (val));
59498      return val;
59499  }
59500
59501#elif (defined(__GNUC__) && defined(__ppc__))
59502
59503  __inline__ sqlite_uint64 sqlite3Hwtime(void){
59504      unsigned long long retval;
59505      unsigned long junk;
59506      __asm__ __volatile__ ("\n\
59507          1:      mftbu   %1\n\
59508                  mftb    %L0\n\
59509                  mftbu   %0\n\
59510                  cmpw    %0,%1\n\
59511                  bne     1b"
59512                  : "=r" (retval), "=r" (junk));
59513      return retval;
59514  }
59515
59516#else
59517
59518  #error Need implementation of sqlite3Hwtime() for your platform.
59519
59520  /*
59521  ** To compile without implementing sqlite3Hwtime() for your platform,
59522  ** you can remove the above #error and use the following
59523  ** stub function.  You will lose timing support for many
59524  ** of the debugging and testing utilities, but it should at
59525  ** least compile and run.
59526  */
59527SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
59528
59529#endif
59530
59531#endif /* !defined(_HWTIME_H_) */
59532
59533/************** End of hwtime.h **********************************************/
59534/************** Continuing where we left off in vdbe.c ***********************/
59535
59536#endif
59537
59538/*
59539** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
59540** sqlite3_interrupt() routine has been called.  If it has been, then
59541** processing of the VDBE program is interrupted.
59542**
59543** This macro added to every instruction that does a jump in order to
59544** implement a loop.  This test used to be on every single instruction,
59545** but that meant we more testing that we needed.  By only testing the
59546** flag on jump instructions, we get a (small) speed improvement.
59547*/
59548#define CHECK_FOR_INTERRUPT \
59549   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
59550
59551
59552#ifndef NDEBUG
59553/*
59554** This function is only called from within an assert() expression. It
59555** checks that the sqlite3.nTransaction variable is correctly set to
59556** the number of non-transaction savepoints currently in the
59557** linked list starting at sqlite3.pSavepoint.
59558**
59559** Usage:
59560**
59561**     assert( checkSavepointCount(db) );
59562*/
59563static int checkSavepointCount(sqlite3 *db){
59564  int n = 0;
59565  Savepoint *p;
59566  for(p=db->pSavepoint; p; p=p->pNext) n++;
59567  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
59568  return 1;
59569}
59570#endif
59571
59572/*
59573** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
59574** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
59575** in memory obtained from sqlite3DbMalloc).
59576*/
59577static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
59578  sqlite3 *db = p->db;
59579  sqlite3DbFree(db, p->zErrMsg);
59580  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
59581  sqlite3_free(pVtab->zErrMsg);
59582  pVtab->zErrMsg = 0;
59583}
59584
59585
59586/*
59587** Execute as much of a VDBE program as we can then return.
59588**
59589** sqlite3VdbeMakeReady() must be called before this routine in order to
59590** close the program with a final OP_Halt and to set up the callbacks
59591** and the error message pointer.
59592**
59593** Whenever a row or result data is available, this routine will either
59594** invoke the result callback (if there is one) or return with
59595** SQLITE_ROW.
59596**
59597** If an attempt is made to open a locked database, then this routine
59598** will either invoke the busy callback (if there is one) or it will
59599** return SQLITE_BUSY.
59600**
59601** If an error occurs, an error message is written to memory obtained
59602** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
59603** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
59604**
59605** If the callback ever returns non-zero, then the program exits
59606** immediately.  There will be no error message but the p->rc field is
59607** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
59608**
59609** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
59610** routine to return SQLITE_ERROR.
59611**
59612** Other fatal errors return SQLITE_ERROR.
59613**
59614** After this routine has finished, sqlite3VdbeFinalize() should be
59615** used to clean up the mess that was left behind.
59616*/
59617SQLITE_PRIVATE int sqlite3VdbeExec(
59618  Vdbe *p                    /* The VDBE */
59619){
59620  int pc=0;                  /* The program counter */
59621  Op *aOp = p->aOp;          /* Copy of p->aOp */
59622  Op *pOp;                   /* Current operation */
59623  int rc = SQLITE_OK;        /* Value to return */
59624  sqlite3 *db = p->db;       /* The database */
59625  u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
59626  u8 encoding = ENC(db);     /* The database encoding */
59627#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
59628  int checkProgress;         /* True if progress callbacks are enabled */
59629  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
59630#endif
59631  Mem *aMem = p->aMem;       /* Copy of p->aMem */
59632  Mem *pIn1 = 0;             /* 1st input operand */
59633  Mem *pIn2 = 0;             /* 2nd input operand */
59634  Mem *pIn3 = 0;             /* 3rd input operand */
59635  Mem *pOut = 0;             /* Output operand */
59636  int iCompare = 0;          /* Result of last OP_Compare operation */
59637  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
59638#ifdef VDBE_PROFILE
59639  u64 start;                 /* CPU clock count at start of opcode */
59640  int origPc;                /* Program counter at start of opcode */
59641#endif
59642  /********************************************************************
59643  ** Automatically generated code
59644  **
59645  ** The following union is automatically generated by the
59646  ** vdbe-compress.tcl script.  The purpose of this union is to
59647  ** reduce the amount of stack space required by this function.
59648  ** See comments in the vdbe-compress.tcl script for details.
59649  */
59650  union vdbeExecUnion {
59651    struct OP_Yield_stack_vars {
59652      int pcDest;
59653    } aa;
59654    struct OP_Variable_stack_vars {
59655      Mem *pVar;       /* Value being transferred */
59656    } ab;
59657    struct OP_Move_stack_vars {
59658      char *zMalloc;   /* Holding variable for allocated memory */
59659      int n;           /* Number of registers left to copy */
59660      int p1;          /* Register to copy from */
59661      int p2;          /* Register to copy to */
59662    } ac;
59663    struct OP_ResultRow_stack_vars {
59664      Mem *pMem;
59665      int i;
59666    } ad;
59667    struct OP_Concat_stack_vars {
59668      i64 nByte;
59669    } ae;
59670    struct OP_Remainder_stack_vars {
59671      int flags;      /* Combined MEM_* flags from both inputs */
59672      i64 iA;         /* Integer value of left operand */
59673      i64 iB;         /* Integer value of right operand */
59674      double rA;      /* Real value of left operand */
59675      double rB;      /* Real value of right operand */
59676    } af;
59677    struct OP_Function_stack_vars {
59678      int i;
59679      Mem *pArg;
59680      sqlite3_context ctx;
59681      sqlite3_value **apVal;
59682      int n;
59683    } ag;
59684    struct OP_ShiftRight_stack_vars {
59685      i64 a;
59686      i64 b;
59687    } ah;
59688    struct OP_Ge_stack_vars {
59689      int res;            /* Result of the comparison of pIn1 against pIn3 */
59690      char affinity;      /* Affinity to use for comparison */
59691      u16 flags1;         /* Copy of initial value of pIn1->flags */
59692      u16 flags3;         /* Copy of initial value of pIn3->flags */
59693    } ai;
59694    struct OP_Compare_stack_vars {
59695      int n;
59696      int i;
59697      int p1;
59698      int p2;
59699      const KeyInfo *pKeyInfo;
59700      int idx;
59701      CollSeq *pColl;    /* Collating sequence to use on this term */
59702      int bRev;          /* True for DESCENDING sort order */
59703    } aj;
59704    struct OP_Or_stack_vars {
59705      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
59706      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
59707    } ak;
59708    struct OP_IfNot_stack_vars {
59709      int c;
59710    } al;
59711    struct OP_Column_stack_vars {
59712      u32 payloadSize;   /* Number of bytes in the record */
59713      i64 payloadSize64; /* Number of bytes in the record */
59714      int p1;            /* P1 value of the opcode */
59715      int p2;            /* column number to retrieve */
59716      VdbeCursor *pC;    /* The VDBE cursor */
59717      char *zRec;        /* Pointer to complete record-data */
59718      BtCursor *pCrsr;   /* The BTree cursor */
59719      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
59720      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
59721      int nField;        /* number of fields in the record */
59722      int len;           /* The length of the serialized data for the column */
59723      int i;             /* Loop counter */
59724      char *zData;       /* Part of the record being decoded */
59725      Mem *pDest;        /* Where to write the extracted value */
59726      Mem sMem;          /* For storing the record being decoded */
59727      u8 *zIdx;          /* Index into header */
59728      u8 *zEndHdr;       /* Pointer to first byte after the header */
59729      u32 offset;        /* Offset into the data */
59730      u32 szField;       /* Number of bytes in the content of a field */
59731      int szHdr;         /* Size of the header size field at start of record */
59732      int avail;         /* Number of bytes of available data */
59733      Mem *pReg;         /* PseudoTable input register */
59734    } am;
59735    struct OP_Affinity_stack_vars {
59736      const char *zAffinity;   /* The affinity to be applied */
59737      char cAff;               /* A single character of affinity */
59738    } an;
59739    struct OP_MakeRecord_stack_vars {
59740      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
59741      Mem *pRec;             /* The new record */
59742      u64 nData;             /* Number of bytes of data space */
59743      int nHdr;              /* Number of bytes of header space */
59744      i64 nByte;             /* Data space required for this record */
59745      int nZero;             /* Number of zero bytes at the end of the record */
59746      int nVarint;           /* Number of bytes in a varint */
59747      u32 serial_type;       /* Type field */
59748      Mem *pData0;           /* First field to be combined into the record */
59749      Mem *pLast;            /* Last field of the record */
59750      int nField;            /* Number of fields in the record */
59751      char *zAffinity;       /* The affinity string for the record */
59752      int file_format;       /* File format to use for encoding */
59753      int i;                 /* Space used in zNewRecord[] */
59754      int len;               /* Length of a field */
59755    } ao;
59756    struct OP_Count_stack_vars {
59757      i64 nEntry;
59758      BtCursor *pCrsr;
59759    } ap;
59760    struct OP_Savepoint_stack_vars {
59761      int p1;                         /* Value of P1 operand */
59762      char *zName;                    /* Name of savepoint */
59763      int nName;
59764      Savepoint *pNew;
59765      Savepoint *pSavepoint;
59766      Savepoint *pTmp;
59767      int iSavepoint;
59768      int ii;
59769    } aq;
59770    struct OP_AutoCommit_stack_vars {
59771      int desiredAutoCommit;
59772      int iRollback;
59773      int turnOnAC;
59774    } ar;
59775    struct OP_Transaction_stack_vars {
59776      Btree *pBt;
59777    } as;
59778    struct OP_ReadCookie_stack_vars {
59779      int iMeta;
59780      int iDb;
59781      int iCookie;
59782    } at;
59783    struct OP_SetCookie_stack_vars {
59784      Db *pDb;
59785    } au;
59786    struct OP_VerifyCookie_stack_vars {
59787      int iMeta;
59788      Btree *pBt;
59789    } av;
59790    struct OP_OpenWrite_stack_vars {
59791      int nField;
59792      KeyInfo *pKeyInfo;
59793      int p2;
59794      int iDb;
59795      int wrFlag;
59796      Btree *pX;
59797      VdbeCursor *pCur;
59798      Db *pDb;
59799    } aw;
59800    struct OP_OpenEphemeral_stack_vars {
59801      VdbeCursor *pCx;
59802    } ax;
59803    struct OP_OpenPseudo_stack_vars {
59804      VdbeCursor *pCx;
59805    } ay;
59806    struct OP_SeekGt_stack_vars {
59807      int res;
59808      int oc;
59809      VdbeCursor *pC;
59810      UnpackedRecord r;
59811      int nField;
59812      i64 iKey;      /* The rowid we are to seek to */
59813    } az;
59814    struct OP_Seek_stack_vars {
59815      VdbeCursor *pC;
59816    } ba;
59817    struct OP_Found_stack_vars {
59818      int alreadyExists;
59819      VdbeCursor *pC;
59820      int res;
59821      UnpackedRecord *pIdxKey;
59822      UnpackedRecord r;
59823      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
59824    } bb;
59825    struct OP_IsUnique_stack_vars {
59826      u16 ii;
59827      VdbeCursor *pCx;
59828      BtCursor *pCrsr;
59829      u16 nField;
59830      Mem *aMx;
59831      UnpackedRecord r;                  /* B-Tree index search key */
59832      i64 R;                             /* Rowid stored in register P3 */
59833    } bc;
59834    struct OP_NotExists_stack_vars {
59835      VdbeCursor *pC;
59836      BtCursor *pCrsr;
59837      int res;
59838      u64 iKey;
59839    } bd;
59840    struct OP_NewRowid_stack_vars {
59841      i64 v;                 /* The new rowid */
59842      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
59843      int res;               /* Result of an sqlite3BtreeLast() */
59844      int cnt;               /* Counter to limit the number of searches */
59845      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
59846      VdbeFrame *pFrame;     /* Root frame of VDBE */
59847    } be;
59848    struct OP_InsertInt_stack_vars {
59849      Mem *pData;       /* MEM cell holding data for the record to be inserted */
59850      Mem *pKey;        /* MEM cell holding key  for the record */
59851      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
59852      VdbeCursor *pC;   /* Cursor to table into which insert is written */
59853      int nZero;        /* Number of zero-bytes to append */
59854      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
59855      const char *zDb;  /* database name - used by the update hook */
59856      const char *zTbl; /* Table name - used by the opdate hook */
59857      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
59858    } bf;
59859    struct OP_Delete_stack_vars {
59860      i64 iKey;
59861      VdbeCursor *pC;
59862    } bg;
59863    struct OP_RowData_stack_vars {
59864      VdbeCursor *pC;
59865      BtCursor *pCrsr;
59866      u32 n;
59867      i64 n64;
59868    } bh;
59869    struct OP_Rowid_stack_vars {
59870      VdbeCursor *pC;
59871      i64 v;
59872      sqlite3_vtab *pVtab;
59873      const sqlite3_module *pModule;
59874    } bi;
59875    struct OP_NullRow_stack_vars {
59876      VdbeCursor *pC;
59877    } bj;
59878    struct OP_Last_stack_vars {
59879      VdbeCursor *pC;
59880      BtCursor *pCrsr;
59881      int res;
59882    } bk;
59883    struct OP_Rewind_stack_vars {
59884      VdbeCursor *pC;
59885      BtCursor *pCrsr;
59886      int res;
59887    } bl;
59888    struct OP_Next_stack_vars {
59889      VdbeCursor *pC;
59890      BtCursor *pCrsr;
59891      int res;
59892    } bm;
59893    struct OP_IdxInsert_stack_vars {
59894      VdbeCursor *pC;
59895      BtCursor *pCrsr;
59896      int nKey;
59897      const char *zKey;
59898    } bn;
59899    struct OP_IdxDelete_stack_vars {
59900      VdbeCursor *pC;
59901      BtCursor *pCrsr;
59902      int res;
59903      UnpackedRecord r;
59904    } bo;
59905    struct OP_IdxRowid_stack_vars {
59906      BtCursor *pCrsr;
59907      VdbeCursor *pC;
59908      i64 rowid;
59909    } bp;
59910    struct OP_IdxGE_stack_vars {
59911      VdbeCursor *pC;
59912      int res;
59913      UnpackedRecord r;
59914    } bq;
59915    struct OP_Destroy_stack_vars {
59916      int iMoved;
59917      int iCnt;
59918      Vdbe *pVdbe;
59919      int iDb;
59920    } br;
59921    struct OP_Clear_stack_vars {
59922      int nChange;
59923    } bs;
59924    struct OP_CreateTable_stack_vars {
59925      int pgno;
59926      int flags;
59927      Db *pDb;
59928    } bt;
59929    struct OP_ParseSchema_stack_vars {
59930      int iDb;
59931      const char *zMaster;
59932      char *zSql;
59933      InitData initData;
59934    } bu;
59935    struct OP_IntegrityCk_stack_vars {
59936      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
59937      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
59938      int j;          /* Loop counter */
59939      int nErr;       /* Number of errors reported */
59940      char *z;        /* Text of the error report */
59941      Mem *pnErr;     /* Register keeping track of errors remaining */
59942    } bv;
59943    struct OP_RowSetRead_stack_vars {
59944      i64 val;
59945    } bw;
59946    struct OP_RowSetTest_stack_vars {
59947      int iSet;
59948      int exists;
59949    } bx;
59950    struct OP_Program_stack_vars {
59951      int nMem;               /* Number of memory registers for sub-program */
59952      int nByte;              /* Bytes of runtime space required for sub-program */
59953      Mem *pRt;               /* Register to allocate runtime space */
59954      Mem *pMem;              /* Used to iterate through memory cells */
59955      Mem *pEnd;              /* Last memory cell in new array */
59956      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
59957      SubProgram *pProgram;   /* Sub-program to execute */
59958      void *t;                /* Token identifying trigger */
59959    } by;
59960    struct OP_Param_stack_vars {
59961      VdbeFrame *pFrame;
59962      Mem *pIn;
59963    } bz;
59964    struct OP_MemMax_stack_vars {
59965      Mem *pIn1;
59966      VdbeFrame *pFrame;
59967    } ca;
59968    struct OP_AggStep_stack_vars {
59969      int n;
59970      int i;
59971      Mem *pMem;
59972      Mem *pRec;
59973      sqlite3_context ctx;
59974      sqlite3_value **apVal;
59975    } cb;
59976    struct OP_AggFinal_stack_vars {
59977      Mem *pMem;
59978    } cc;
59979    struct OP_JournalMode_stack_vars {
59980      Btree *pBt;                     /* Btree to change journal mode of */
59981      Pager *pPager;                  /* Pager associated with pBt */
59982      int eNew;                       /* New journal mode */
59983      int eOld;                       /* The old journal mode */
59984      const char *zFilename;          /* Name of database file for pPager */
59985    } cd;
59986    struct OP_IncrVacuum_stack_vars {
59987      Btree *pBt;
59988    } ce;
59989    struct OP_VBegin_stack_vars {
59990      VTable *pVTab;
59991    } cf;
59992    struct OP_VOpen_stack_vars {
59993      VdbeCursor *pCur;
59994      sqlite3_vtab_cursor *pVtabCursor;
59995      sqlite3_vtab *pVtab;
59996      sqlite3_module *pModule;
59997    } cg;
59998    struct OP_VFilter_stack_vars {
59999      int nArg;
60000      int iQuery;
60001      const sqlite3_module *pModule;
60002      Mem *pQuery;
60003      Mem *pArgc;
60004      sqlite3_vtab_cursor *pVtabCursor;
60005      sqlite3_vtab *pVtab;
60006      VdbeCursor *pCur;
60007      int res;
60008      int i;
60009      Mem **apArg;
60010    } ch;
60011    struct OP_VColumn_stack_vars {
60012      sqlite3_vtab *pVtab;
60013      const sqlite3_module *pModule;
60014      Mem *pDest;
60015      sqlite3_context sContext;
60016    } ci;
60017    struct OP_VNext_stack_vars {
60018      sqlite3_vtab *pVtab;
60019      const sqlite3_module *pModule;
60020      int res;
60021      VdbeCursor *pCur;
60022    } cj;
60023    struct OP_VRename_stack_vars {
60024      sqlite3_vtab *pVtab;
60025      Mem *pName;
60026    } ck;
60027    struct OP_VUpdate_stack_vars {
60028      sqlite3_vtab *pVtab;
60029      sqlite3_module *pModule;
60030      int nArg;
60031      int i;
60032      sqlite_int64 rowid;
60033      Mem **apArg;
60034      Mem *pX;
60035    } cl;
60036    struct OP_Trace_stack_vars {
60037      char *zTrace;
60038    } cm;
60039  } u;
60040  /* End automatically generated code
60041  ********************************************************************/
60042
60043  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
60044  sqlite3VdbeMutexArrayEnter(p);
60045  if( p->rc==SQLITE_NOMEM ){
60046    /* This happens if a malloc() inside a call to sqlite3_column_text() or
60047    ** sqlite3_column_text16() failed.  */
60048    goto no_mem;
60049  }
60050  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
60051  p->rc = SQLITE_OK;
60052  assert( p->explain==0 );
60053  p->pResultSet = 0;
60054  db->busyHandler.nBusy = 0;
60055  CHECK_FOR_INTERRUPT;
60056  sqlite3VdbeIOTraceSql(p);
60057#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60058  checkProgress = db->xProgress!=0;
60059#endif
60060#ifdef SQLITE_DEBUG
60061  sqlite3BeginBenignMalloc();
60062  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
60063    int i;
60064    printf("VDBE Program Listing:\n");
60065    sqlite3VdbePrintSql(p);
60066    for(i=0; i<p->nOp; i++){
60067      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
60068    }
60069  }
60070  sqlite3EndBenignMalloc();
60071#endif
60072  for(pc=p->pc; rc==SQLITE_OK; pc++){
60073    assert( pc>=0 && pc<p->nOp );
60074    if( db->mallocFailed ) goto no_mem;
60075#ifdef VDBE_PROFILE
60076    origPc = pc;
60077    start = sqlite3Hwtime();
60078#endif
60079    pOp = &aOp[pc];
60080
60081    /* Only allow tracing if SQLITE_DEBUG is defined.
60082    */
60083#ifdef SQLITE_DEBUG
60084    if( p->trace ){
60085      if( pc==0 ){
60086        printf("VDBE Execution Trace:\n");
60087        sqlite3VdbePrintSql(p);
60088      }
60089      sqlite3VdbePrintOp(p->trace, pc, pOp);
60090    }
60091#endif
60092
60093
60094    /* Check to see if we need to simulate an interrupt.  This only happens
60095    ** if we have a special test build.
60096    */
60097#ifdef SQLITE_TEST
60098    if( sqlite3_interrupt_count>0 ){
60099      sqlite3_interrupt_count--;
60100      if( sqlite3_interrupt_count==0 ){
60101        sqlite3_interrupt(db);
60102      }
60103    }
60104#endif
60105
60106#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60107    /* Call the progress callback if it is configured and the required number
60108    ** of VDBE ops have been executed (either since this invocation of
60109    ** sqlite3VdbeExec() or since last time the progress callback was called).
60110    ** If the progress callback returns non-zero, exit the virtual machine with
60111    ** a return code SQLITE_ABORT.
60112    */
60113    if( checkProgress ){
60114      if( db->nProgressOps==nProgressOps ){
60115        int prc;
60116        prc = db->xProgress(db->pProgressArg);
60117        if( prc!=0 ){
60118          rc = SQLITE_INTERRUPT;
60119          goto vdbe_error_halt;
60120        }
60121        nProgressOps = 0;
60122      }
60123      nProgressOps++;
60124    }
60125#endif
60126
60127    /* On any opcode with the "out2-prerelase" tag, free any
60128    ** external allocations out of mem[p2] and set mem[p2] to be
60129    ** an undefined integer.  Opcodes will either fill in the integer
60130    ** value or convert mem[p2] to a different type.
60131    */
60132    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
60133    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
60134      assert( pOp->p2>0 );
60135      assert( pOp->p2<=p->nMem );
60136      pOut = &aMem[pOp->p2];
60137      sqlite3VdbeMemReleaseExternal(pOut);
60138      pOut->flags = MEM_Int;
60139    }
60140
60141    /* Sanity checking on other operands */
60142#ifdef SQLITE_DEBUG
60143    if( (pOp->opflags & OPFLG_IN1)!=0 ){
60144      assert( pOp->p1>0 );
60145      assert( pOp->p1<=p->nMem );
60146      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
60147    }
60148    if( (pOp->opflags & OPFLG_IN2)!=0 ){
60149      assert( pOp->p2>0 );
60150      assert( pOp->p2<=p->nMem );
60151      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
60152    }
60153    if( (pOp->opflags & OPFLG_IN3)!=0 ){
60154      assert( pOp->p3>0 );
60155      assert( pOp->p3<=p->nMem );
60156      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
60157    }
60158    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
60159      assert( pOp->p2>0 );
60160      assert( pOp->p2<=p->nMem );
60161    }
60162    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
60163      assert( pOp->p3>0 );
60164      assert( pOp->p3<=p->nMem );
60165    }
60166#endif
60167
60168    switch( pOp->opcode ){
60169
60170/*****************************************************************************
60171** What follows is a massive switch statement where each case implements a
60172** separate instruction in the virtual machine.  If we follow the usual
60173** indentation conventions, each case should be indented by 6 spaces.  But
60174** that is a lot of wasted space on the left margin.  So the code within
60175** the switch statement will break with convention and be flush-left. Another
60176** big comment (similar to this one) will mark the point in the code where
60177** we transition back to normal indentation.
60178**
60179** The formatting of each case is important.  The makefile for SQLite
60180** generates two C files "opcodes.h" and "opcodes.c" by scanning this
60181** file looking for lines that begin with "case OP_".  The opcodes.h files
60182** will be filled with #defines that give unique integer values to each
60183** opcode and the opcodes.c file is filled with an array of strings where
60184** each string is the symbolic name for the corresponding opcode.  If the
60185** case statement is followed by a comment of the form "/# same as ... #/"
60186** that comment is used to determine the particular value of the opcode.
60187**
60188** Other keywords in the comment that follows each case are used to
60189** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
60190** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
60191** the mkopcodeh.awk script for additional information.
60192**
60193** Documentation about VDBE opcodes is generated by scanning this file
60194** for lines of that contain "Opcode:".  That line and all subsequent
60195** comment lines are used in the generation of the opcode.html documentation
60196** file.
60197**
60198** SUMMARY:
60199**
60200**     Formatting is important to scripts that scan this file.
60201**     Do not deviate from the formatting style currently in use.
60202**
60203*****************************************************************************/
60204
60205/* Opcode:  Goto * P2 * * *
60206**
60207** An unconditional jump to address P2.
60208** The next instruction executed will be
60209** the one at index P2 from the beginning of
60210** the program.
60211*/
60212case OP_Goto: {             /* jump */
60213  CHECK_FOR_INTERRUPT;
60214  pc = pOp->p2 - 1;
60215  break;
60216}
60217
60218/* Opcode:  Gosub P1 P2 * * *
60219**
60220** Write the current address onto register P1
60221** and then jump to address P2.
60222*/
60223case OP_Gosub: {            /* jump, in1 */
60224  pIn1 = &aMem[pOp->p1];
60225  assert( (pIn1->flags & MEM_Dyn)==0 );
60226  pIn1->flags = MEM_Int;
60227  pIn1->u.i = pc;
60228  REGISTER_TRACE(pOp->p1, pIn1);
60229  pc = pOp->p2 - 1;
60230  break;
60231}
60232
60233/* Opcode:  Return P1 * * * *
60234**
60235** Jump to the next instruction after the address in register P1.
60236*/
60237case OP_Return: {           /* in1 */
60238  pIn1 = &aMem[pOp->p1];
60239  assert( pIn1->flags & MEM_Int );
60240  pc = (int)pIn1->u.i;
60241  break;
60242}
60243
60244/* Opcode:  Yield P1 * * * *
60245**
60246** Swap the program counter with the value in register P1.
60247*/
60248case OP_Yield: {            /* in1 */
60249#if 0  /* local variables moved into u.aa */
60250  int pcDest;
60251#endif /* local variables moved into u.aa */
60252  pIn1 = &aMem[pOp->p1];
60253  assert( (pIn1->flags & MEM_Dyn)==0 );
60254  pIn1->flags = MEM_Int;
60255  u.aa.pcDest = (int)pIn1->u.i;
60256  pIn1->u.i = pc;
60257  REGISTER_TRACE(pOp->p1, pIn1);
60258  pc = u.aa.pcDest;
60259  break;
60260}
60261
60262/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
60263**
60264** Check the value in register P3.  If is is NULL then Halt using
60265** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
60266** value in register P3 is not NULL, then this routine is a no-op.
60267*/
60268case OP_HaltIfNull: {      /* in3 */
60269  pIn3 = &aMem[pOp->p3];
60270  if( (pIn3->flags & MEM_Null)==0 ) break;
60271  /* Fall through into OP_Halt */
60272}
60273
60274/* Opcode:  Halt P1 P2 * P4 *
60275**
60276** Exit immediately.  All open cursors, etc are closed
60277** automatically.
60278**
60279** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
60280** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
60281** For errors, it can be some other value.  If P1!=0 then P2 will determine
60282** whether or not to rollback the current transaction.  Do not rollback
60283** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
60284** then back out all changes that have occurred during this execution of the
60285** VDBE, but do not rollback the transaction.
60286**
60287** If P4 is not null then it is an error message string.
60288**
60289** There is an implied "Halt 0 0 0" instruction inserted at the very end of
60290** every program.  So a jump past the last instruction of the program
60291** is the same as executing Halt.
60292*/
60293case OP_Halt: {
60294  if( pOp->p1==SQLITE_OK && p->pFrame ){
60295    /* Halt the sub-program. Return control to the parent frame. */
60296    VdbeFrame *pFrame = p->pFrame;
60297    p->pFrame = pFrame->pParent;
60298    p->nFrame--;
60299    sqlite3VdbeSetChanges(db, p->nChange);
60300    pc = sqlite3VdbeFrameRestore(pFrame);
60301    if( pOp->p2==OE_Ignore ){
60302      /* Instruction pc is the OP_Program that invoked the sub-program
60303      ** currently being halted. If the p2 instruction of this OP_Halt
60304      ** instruction is set to OE_Ignore, then the sub-program is throwing
60305      ** an IGNORE exception. In this case jump to the address specified
60306      ** as the p2 of the calling OP_Program.  */
60307      pc = p->aOp[pc].p2-1;
60308    }
60309    aOp = p->aOp;
60310    aMem = p->aMem;
60311    break;
60312  }
60313
60314  p->rc = pOp->p1;
60315  p->errorAction = (u8)pOp->p2;
60316  p->pc = pc;
60317  if( pOp->p4.z ){
60318    assert( p->rc!=SQLITE_OK );
60319    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
60320    testcase( sqlite3GlobalConfig.xLog!=0 );
60321    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
60322  }else if( p->rc ){
60323    testcase( sqlite3GlobalConfig.xLog!=0 );
60324    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
60325  }
60326  rc = sqlite3VdbeHalt(p);
60327  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
60328  if( rc==SQLITE_BUSY ){
60329    p->rc = rc = SQLITE_BUSY;
60330  }else{
60331    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
60332    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
60333    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
60334  }
60335  goto vdbe_return;
60336}
60337
60338/* Opcode: Integer P1 P2 * * *
60339**
60340** The 32-bit integer value P1 is written into register P2.
60341*/
60342case OP_Integer: {         /* out2-prerelease */
60343  pOut->u.i = pOp->p1;
60344  break;
60345}
60346
60347/* Opcode: Int64 * P2 * P4 *
60348**
60349** P4 is a pointer to a 64-bit integer value.
60350** Write that value into register P2.
60351*/
60352case OP_Int64: {           /* out2-prerelease */
60353  assert( pOp->p4.pI64!=0 );
60354  pOut->u.i = *pOp->p4.pI64;
60355  break;
60356}
60357
60358#ifndef SQLITE_OMIT_FLOATING_POINT
60359/* Opcode: Real * P2 * P4 *
60360**
60361** P4 is a pointer to a 64-bit floating point value.
60362** Write that value into register P2.
60363*/
60364case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
60365  pOut->flags = MEM_Real;
60366  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
60367  pOut->r = *pOp->p4.pReal;
60368  break;
60369}
60370#endif
60371
60372/* Opcode: String8 * P2 * P4 *
60373**
60374** P4 points to a nul terminated UTF-8 string. This opcode is transformed
60375** into an OP_String before it is executed for the first time.
60376*/
60377case OP_String8: {         /* same as TK_STRING, out2-prerelease */
60378  assert( pOp->p4.z!=0 );
60379  pOp->opcode = OP_String;
60380  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
60381
60382#ifndef SQLITE_OMIT_UTF16
60383  if( encoding!=SQLITE_UTF8 ){
60384    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
60385    if( rc==SQLITE_TOOBIG ) goto too_big;
60386    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
60387    assert( pOut->zMalloc==pOut->z );
60388    assert( pOut->flags & MEM_Dyn );
60389    pOut->zMalloc = 0;
60390    pOut->flags |= MEM_Static;
60391    pOut->flags &= ~MEM_Dyn;
60392    if( pOp->p4type==P4_DYNAMIC ){
60393      sqlite3DbFree(db, pOp->p4.z);
60394    }
60395    pOp->p4type = P4_DYNAMIC;
60396    pOp->p4.z = pOut->z;
60397    pOp->p1 = pOut->n;
60398  }
60399#endif
60400  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
60401    goto too_big;
60402  }
60403  /* Fall through to the next case, OP_String */
60404}
60405
60406/* Opcode: String P1 P2 * P4 *
60407**
60408** The string value P4 of length P1 (bytes) is stored in register P2.
60409*/
60410case OP_String: {          /* out2-prerelease */
60411  assert( pOp->p4.z!=0 );
60412  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
60413  pOut->z = pOp->p4.z;
60414  pOut->n = pOp->p1;
60415  pOut->enc = encoding;
60416  UPDATE_MAX_BLOBSIZE(pOut);
60417  break;
60418}
60419
60420/* Opcode: Null * P2 * * *
60421**
60422** Write a NULL into register P2.
60423*/
60424case OP_Null: {           /* out2-prerelease */
60425  pOut->flags = MEM_Null;
60426  break;
60427}
60428
60429
60430/* Opcode: Blob P1 P2 * P4
60431**
60432** P4 points to a blob of data P1 bytes long.  Store this
60433** blob in register P2. This instruction is not coded directly
60434** by the compiler. Instead, the compiler layer specifies
60435** an OP_HexBlob opcode, with the hex string representation of
60436** the blob as P4. This opcode is transformed to an OP_Blob
60437** the first time it is executed.
60438*/
60439case OP_Blob: {                /* out2-prerelease */
60440  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
60441  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
60442  pOut->enc = encoding;
60443  UPDATE_MAX_BLOBSIZE(pOut);
60444  break;
60445}
60446
60447/* Opcode: Variable P1 P2 * P4 *
60448**
60449** Transfer the values of bound parameter P1 into register P2
60450**
60451** If the parameter is named, then its name appears in P4 and P3==1.
60452** The P4 value is used by sqlite3_bind_parameter_name().
60453*/
60454case OP_Variable: {            /* out2-prerelease */
60455#if 0  /* local variables moved into u.ab */
60456  Mem *pVar;       /* Value being transferred */
60457#endif /* local variables moved into u.ab */
60458
60459  assert( pOp->p1>0 && pOp->p1<=p->nVar );
60460  u.ab.pVar = &p->aVar[pOp->p1 - 1];
60461  if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
60462    goto too_big;
60463  }
60464  sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
60465  UPDATE_MAX_BLOBSIZE(pOut);
60466  break;
60467}
60468
60469/* Opcode: Move P1 P2 P3 * *
60470**
60471** Move the values in register P1..P1+P3-1 over into
60472** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
60473** left holding a NULL.  It is an error for register ranges
60474** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
60475*/
60476case OP_Move: {
60477#if 0  /* local variables moved into u.ac */
60478  char *zMalloc;   /* Holding variable for allocated memory */
60479  int n;           /* Number of registers left to copy */
60480  int p1;          /* Register to copy from */
60481  int p2;          /* Register to copy to */
60482#endif /* local variables moved into u.ac */
60483
60484  u.ac.n = pOp->p3;
60485  u.ac.p1 = pOp->p1;
60486  u.ac.p2 = pOp->p2;
60487  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
60488  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
60489
60490  pIn1 = &aMem[u.ac.p1];
60491  pOut = &aMem[u.ac.p2];
60492  while( u.ac.n-- ){
60493    assert( pOut<=&aMem[p->nMem] );
60494    assert( pIn1<=&aMem[p->nMem] );
60495    u.ac.zMalloc = pOut->zMalloc;
60496    pOut->zMalloc = 0;
60497    sqlite3VdbeMemMove(pOut, pIn1);
60498    pIn1->zMalloc = u.ac.zMalloc;
60499    REGISTER_TRACE(u.ac.p2++, pOut);
60500    pIn1++;
60501    pOut++;
60502  }
60503  break;
60504}
60505
60506/* Opcode: Copy P1 P2 * * *
60507**
60508** Make a copy of register P1 into register P2.
60509**
60510** This instruction makes a deep copy of the value.  A duplicate
60511** is made of any string or blob constant.  See also OP_SCopy.
60512*/
60513case OP_Copy: {             /* in1, out2 */
60514  pIn1 = &aMem[pOp->p1];
60515  pOut = &aMem[pOp->p2];
60516  assert( pOut!=pIn1 );
60517  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
60518  Deephemeralize(pOut);
60519  REGISTER_TRACE(pOp->p2, pOut);
60520  break;
60521}
60522
60523/* Opcode: SCopy P1 P2 * * *
60524**
60525** Make a shallow copy of register P1 into register P2.
60526**
60527** This instruction makes a shallow copy of the value.  If the value
60528** is a string or blob, then the copy is only a pointer to the
60529** original and hence if the original changes so will the copy.
60530** Worse, if the original is deallocated, the copy becomes invalid.
60531** Thus the program must guarantee that the original will not change
60532** during the lifetime of the copy.  Use OP_Copy to make a complete
60533** copy.
60534*/
60535case OP_SCopy: {            /* in1, out2 */
60536  pIn1 = &aMem[pOp->p1];
60537  pOut = &aMem[pOp->p2];
60538  assert( pOut!=pIn1 );
60539  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
60540  REGISTER_TRACE(pOp->p2, pOut);
60541  break;
60542}
60543
60544/* Opcode: ResultRow P1 P2 * * *
60545**
60546** The registers P1 through P1+P2-1 contain a single row of
60547** results. This opcode causes the sqlite3_step() call to terminate
60548** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
60549** structure to provide access to the top P1 values as the result
60550** row.
60551*/
60552case OP_ResultRow: {
60553#if 0  /* local variables moved into u.ad */
60554  Mem *pMem;
60555  int i;
60556#endif /* local variables moved into u.ad */
60557  assert( p->nResColumn==pOp->p2 );
60558  assert( pOp->p1>0 );
60559  assert( pOp->p1+pOp->p2<=p->nMem+1 );
60560
60561  /* If this statement has violated immediate foreign key constraints, do
60562  ** not return the number of rows modified. And do not RELEASE the statement
60563  ** transaction. It needs to be rolled back.  */
60564  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
60565    assert( db->flags&SQLITE_CountRows );
60566    assert( p->usesStmtJournal );
60567    break;
60568  }
60569
60570  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
60571  ** DML statements invoke this opcode to return the number of rows
60572  ** modified to the user. This is the only way that a VM that
60573  ** opens a statement transaction may invoke this opcode.
60574  **
60575  ** In case this is such a statement, close any statement transaction
60576  ** opened by this VM before returning control to the user. This is to
60577  ** ensure that statement-transactions are always nested, not overlapping.
60578  ** If the open statement-transaction is not closed here, then the user
60579  ** may step another VM that opens its own statement transaction. This
60580  ** may lead to overlapping statement transactions.
60581  **
60582  ** The statement transaction is never a top-level transaction.  Hence
60583  ** the RELEASE call below can never fail.
60584  */
60585  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
60586  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
60587  if( NEVER(rc!=SQLITE_OK) ){
60588    break;
60589  }
60590
60591  /* Invalidate all ephemeral cursor row caches */
60592  p->cacheCtr = (p->cacheCtr + 2)|1;
60593
60594  /* Make sure the results of the current row are \000 terminated
60595  ** and have an assigned type.  The results are de-ephemeralized as
60596  ** as side effect.
60597  */
60598  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
60599  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
60600    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
60601    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
60602    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
60603  }
60604  if( db->mallocFailed ) goto no_mem;
60605
60606  /* Return SQLITE_ROW
60607  */
60608  p->pc = pc + 1;
60609  rc = SQLITE_ROW;
60610  goto vdbe_return;
60611}
60612
60613/* Opcode: Concat P1 P2 P3 * *
60614**
60615** Add the text in register P1 onto the end of the text in
60616** register P2 and store the result in register P3.
60617** If either the P1 or P2 text are NULL then store NULL in P3.
60618**
60619**   P3 = P2 || P1
60620**
60621** It is illegal for P1 and P3 to be the same register. Sometimes,
60622** if P3 is the same register as P2, the implementation is able
60623** to avoid a memcpy().
60624*/
60625case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
60626#if 0  /* local variables moved into u.ae */
60627  i64 nByte;
60628#endif /* local variables moved into u.ae */
60629
60630  pIn1 = &aMem[pOp->p1];
60631  pIn2 = &aMem[pOp->p2];
60632  pOut = &aMem[pOp->p3];
60633  assert( pIn1!=pOut );
60634  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
60635    sqlite3VdbeMemSetNull(pOut);
60636    break;
60637  }
60638  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
60639  Stringify(pIn1, encoding);
60640  Stringify(pIn2, encoding);
60641  u.ae.nByte = pIn1->n + pIn2->n;
60642  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
60643    goto too_big;
60644  }
60645  MemSetTypeFlag(pOut, MEM_Str);
60646  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
60647    goto no_mem;
60648  }
60649  if( pOut!=pIn2 ){
60650    memcpy(pOut->z, pIn2->z, pIn2->n);
60651  }
60652  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
60653  pOut->z[u.ae.nByte] = 0;
60654  pOut->z[u.ae.nByte+1] = 0;
60655  pOut->flags |= MEM_Term;
60656  pOut->n = (int)u.ae.nByte;
60657  pOut->enc = encoding;
60658  UPDATE_MAX_BLOBSIZE(pOut);
60659  break;
60660}
60661
60662/* Opcode: Add P1 P2 P3 * *
60663**
60664** Add the value in register P1 to the value in register P2
60665** and store the result in register P3.
60666** If either input is NULL, the result is NULL.
60667*/
60668/* Opcode: Multiply P1 P2 P3 * *
60669**
60670**
60671** Multiply the value in register P1 by the value in register P2
60672** and store the result in register P3.
60673** If either input is NULL, the result is NULL.
60674*/
60675/* Opcode: Subtract P1 P2 P3 * *
60676**
60677** Subtract the value in register P1 from the value in register P2
60678** and store the result in register P3.
60679** If either input is NULL, the result is NULL.
60680*/
60681/* Opcode: Divide P1 P2 P3 * *
60682**
60683** Divide the value in register P1 by the value in register P2
60684** and store the result in register P3 (P3=P2/P1). If the value in
60685** register P1 is zero, then the result is NULL. If either input is
60686** NULL, the result is NULL.
60687*/
60688/* Opcode: Remainder P1 P2 P3 * *
60689**
60690** Compute the remainder after integer division of the value in
60691** register P1 by the value in register P2 and store the result in P3.
60692** If the value in register P2 is zero the result is NULL.
60693** If either operand is NULL, the result is NULL.
60694*/
60695case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
60696case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
60697case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
60698case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
60699case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
60700#if 0  /* local variables moved into u.af */
60701  int flags;      /* Combined MEM_* flags from both inputs */
60702  i64 iA;         /* Integer value of left operand */
60703  i64 iB;         /* Integer value of right operand */
60704  double rA;      /* Real value of left operand */
60705  double rB;      /* Real value of right operand */
60706#endif /* local variables moved into u.af */
60707
60708  pIn1 = &aMem[pOp->p1];
60709  applyNumericAffinity(pIn1);
60710  pIn2 = &aMem[pOp->p2];
60711  applyNumericAffinity(pIn2);
60712  pOut = &aMem[pOp->p3];
60713  u.af.flags = pIn1->flags | pIn2->flags;
60714  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
60715  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
60716    u.af.iA = pIn1->u.i;
60717    u.af.iB = pIn2->u.i;
60718    switch( pOp->opcode ){
60719      case OP_Add:         u.af.iB += u.af.iA;       break;
60720      case OP_Subtract:    u.af.iB -= u.af.iA;       break;
60721      case OP_Multiply:    u.af.iB *= u.af.iA;       break;
60722      case OP_Divide: {
60723        if( u.af.iA==0 ) goto arithmetic_result_is_null;
60724        /* Dividing the largest possible negative 64-bit integer (1<<63) by
60725        ** -1 returns an integer too large to store in a 64-bit data-type. On
60726        ** some architectures, the value overflows to (1<<63). On others,
60727        ** a SIGFPE is issued. The following statement normalizes this
60728        ** behavior so that all architectures behave as if integer
60729        ** overflow occurred.
60730        */
60731        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
60732        u.af.iB /= u.af.iA;
60733        break;
60734      }
60735      default: {
60736        if( u.af.iA==0 ) goto arithmetic_result_is_null;
60737        if( u.af.iA==-1 ) u.af.iA = 1;
60738        u.af.iB %= u.af.iA;
60739        break;
60740      }
60741    }
60742    pOut->u.i = u.af.iB;
60743    MemSetTypeFlag(pOut, MEM_Int);
60744  }else{
60745    u.af.rA = sqlite3VdbeRealValue(pIn1);
60746    u.af.rB = sqlite3VdbeRealValue(pIn2);
60747    switch( pOp->opcode ){
60748      case OP_Add:         u.af.rB += u.af.rA;       break;
60749      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
60750      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
60751      case OP_Divide: {
60752        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
60753        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
60754        u.af.rB /= u.af.rA;
60755        break;
60756      }
60757      default: {
60758        u.af.iA = (i64)u.af.rA;
60759        u.af.iB = (i64)u.af.rB;
60760        if( u.af.iA==0 ) goto arithmetic_result_is_null;
60761        if( u.af.iA==-1 ) u.af.iA = 1;
60762        u.af.rB = (double)(u.af.iB % u.af.iA);
60763        break;
60764      }
60765    }
60766#ifdef SQLITE_OMIT_FLOATING_POINT
60767    pOut->u.i = u.af.rB;
60768    MemSetTypeFlag(pOut, MEM_Int);
60769#else
60770    if( sqlite3IsNaN(u.af.rB) ){
60771      goto arithmetic_result_is_null;
60772    }
60773    pOut->r = u.af.rB;
60774    MemSetTypeFlag(pOut, MEM_Real);
60775    if( (u.af.flags & MEM_Real)==0 ){
60776      sqlite3VdbeIntegerAffinity(pOut);
60777    }
60778#endif
60779  }
60780  break;
60781
60782arithmetic_result_is_null:
60783  sqlite3VdbeMemSetNull(pOut);
60784  break;
60785}
60786
60787/* Opcode: CollSeq * * P4
60788**
60789** P4 is a pointer to a CollSeq struct. If the next call to a user function
60790** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
60791** be returned. This is used by the built-in min(), max() and nullif()
60792** functions.
60793**
60794** The interface used by the implementation of the aforementioned functions
60795** to retrieve the collation sequence set by this opcode is not available
60796** publicly, only to user functions defined in func.c.
60797*/
60798case OP_CollSeq: {
60799  assert( pOp->p4type==P4_COLLSEQ );
60800  break;
60801}
60802
60803/* Opcode: Function P1 P2 P3 P4 P5
60804**
60805** Invoke a user function (P4 is a pointer to a Function structure that
60806** defines the function) with P5 arguments taken from register P2 and
60807** successors.  The result of the function is stored in register P3.
60808** Register P3 must not be one of the function inputs.
60809**
60810** P1 is a 32-bit bitmask indicating whether or not each argument to the
60811** function was determined to be constant at compile time. If the first
60812** argument was constant then bit 0 of P1 is set. This is used to determine
60813** whether meta data associated with a user function argument using the
60814** sqlite3_set_auxdata() API may be safely retained until the next
60815** invocation of this opcode.
60816**
60817** See also: AggStep and AggFinal
60818*/
60819case OP_Function: {
60820#if 0  /* local variables moved into u.ag */
60821  int i;
60822  Mem *pArg;
60823  sqlite3_context ctx;
60824  sqlite3_value **apVal;
60825  int n;
60826#endif /* local variables moved into u.ag */
60827
60828  u.ag.n = pOp->p5;
60829  u.ag.apVal = p->apArg;
60830  assert( u.ag.apVal || u.ag.n==0 );
60831
60832  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
60833  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
60834  u.ag.pArg = &aMem[pOp->p2];
60835  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
60836    u.ag.apVal[u.ag.i] = u.ag.pArg;
60837    sqlite3VdbeMemStoreType(u.ag.pArg);
60838    REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
60839  }
60840
60841  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
60842  if( pOp->p4type==P4_FUNCDEF ){
60843    u.ag.ctx.pFunc = pOp->p4.pFunc;
60844    u.ag.ctx.pVdbeFunc = 0;
60845  }else{
60846    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
60847    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
60848  }
60849
60850  assert( pOp->p3>0 && pOp->p3<=p->nMem );
60851  pOut = &aMem[pOp->p3];
60852  u.ag.ctx.s.flags = MEM_Null;
60853  u.ag.ctx.s.db = db;
60854  u.ag.ctx.s.xDel = 0;
60855  u.ag.ctx.s.zMalloc = 0;
60856
60857  /* The output cell may already have a buffer allocated. Move
60858  ** the pointer to u.ag.ctx.s so in case the user-function can use
60859  ** the already allocated buffer instead of allocating a new one.
60860  */
60861  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
60862  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
60863
60864  u.ag.ctx.isError = 0;
60865  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
60866    assert( pOp>aOp );
60867    assert( pOp[-1].p4type==P4_COLLSEQ );
60868    assert( pOp[-1].opcode==OP_CollSeq );
60869    u.ag.ctx.pColl = pOp[-1].p4.pColl;
60870  }
60871  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
60872  if( db->mallocFailed ){
60873    /* Even though a malloc() has failed, the implementation of the
60874    ** user function may have called an sqlite3_result_XXX() function
60875    ** to return a value. The following call releases any resources
60876    ** associated with such a value.
60877    */
60878    sqlite3VdbeMemRelease(&u.ag.ctx.s);
60879    goto no_mem;
60880  }
60881
60882  /* If any auxiliary data functions have been called by this user function,
60883  ** immediately call the destructor for any non-static values.
60884  */
60885  if( u.ag.ctx.pVdbeFunc ){
60886    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
60887    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
60888    pOp->p4type = P4_VDBEFUNC;
60889  }
60890
60891  /* If the function returned an error, throw an exception */
60892  if( u.ag.ctx.isError ){
60893    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
60894    rc = u.ag.ctx.isError;
60895  }
60896
60897  /* Copy the result of the function into register P3 */
60898  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
60899  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
60900  if( sqlite3VdbeMemTooBig(pOut) ){
60901    goto too_big;
60902  }
60903  REGISTER_TRACE(pOp->p3, pOut);
60904  UPDATE_MAX_BLOBSIZE(pOut);
60905  break;
60906}
60907
60908/* Opcode: BitAnd P1 P2 P3 * *
60909**
60910** Take the bit-wise AND of the values in register P1 and P2 and
60911** store the result in register P3.
60912** If either input is NULL, the result is NULL.
60913*/
60914/* Opcode: BitOr P1 P2 P3 * *
60915**
60916** Take the bit-wise OR of the values in register P1 and P2 and
60917** store the result in register P3.
60918** If either input is NULL, the result is NULL.
60919*/
60920/* Opcode: ShiftLeft P1 P2 P3 * *
60921**
60922** Shift the integer value in register P2 to the left by the
60923** number of bits specified by the integer in regiser P1.
60924** Store the result in register P3.
60925** If either input is NULL, the result is NULL.
60926*/
60927/* Opcode: ShiftRight P1 P2 P3 * *
60928**
60929** Shift the integer value in register P2 to the right by the
60930** number of bits specified by the integer in register P1.
60931** Store the result in register P3.
60932** If either input is NULL, the result is NULL.
60933*/
60934case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
60935case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
60936case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
60937case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
60938#if 0  /* local variables moved into u.ah */
60939  i64 a;
60940  i64 b;
60941#endif /* local variables moved into u.ah */
60942
60943  pIn1 = &aMem[pOp->p1];
60944  pIn2 = &aMem[pOp->p2];
60945  pOut = &aMem[pOp->p3];
60946  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
60947    sqlite3VdbeMemSetNull(pOut);
60948    break;
60949  }
60950  u.ah.a = sqlite3VdbeIntValue(pIn2);
60951  u.ah.b = sqlite3VdbeIntValue(pIn1);
60952  switch( pOp->opcode ){
60953    case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
60954    case OP_BitOr:       u.ah.a |= u.ah.b;     break;
60955    case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
60956    default:  assert( pOp->opcode==OP_ShiftRight );
60957                         u.ah.a >>= u.ah.b;    break;
60958  }
60959  pOut->u.i = u.ah.a;
60960  MemSetTypeFlag(pOut, MEM_Int);
60961  break;
60962}
60963
60964/* Opcode: AddImm  P1 P2 * * *
60965**
60966** Add the constant P2 to the value in register P1.
60967** The result is always an integer.
60968**
60969** To force any register to be an integer, just add 0.
60970*/
60971case OP_AddImm: {            /* in1 */
60972  pIn1 = &aMem[pOp->p1];
60973  sqlite3VdbeMemIntegerify(pIn1);
60974  pIn1->u.i += pOp->p2;
60975  break;
60976}
60977
60978/* Opcode: MustBeInt P1 P2 * * *
60979**
60980** Force the value in register P1 to be an integer.  If the value
60981** in P1 is not an integer and cannot be converted into an integer
60982** without data loss, then jump immediately to P2, or if P2==0
60983** raise an SQLITE_MISMATCH exception.
60984*/
60985case OP_MustBeInt: {            /* jump, in1 */
60986  pIn1 = &aMem[pOp->p1];
60987  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
60988  if( (pIn1->flags & MEM_Int)==0 ){
60989    if( pOp->p2==0 ){
60990      rc = SQLITE_MISMATCH;
60991      goto abort_due_to_error;
60992    }else{
60993      pc = pOp->p2 - 1;
60994    }
60995  }else{
60996    MemSetTypeFlag(pIn1, MEM_Int);
60997  }
60998  break;
60999}
61000
61001#ifndef SQLITE_OMIT_FLOATING_POINT
61002/* Opcode: RealAffinity P1 * * * *
61003**
61004** If register P1 holds an integer convert it to a real value.
61005**
61006** This opcode is used when extracting information from a column that
61007** has REAL affinity.  Such column values may still be stored as
61008** integers, for space efficiency, but after extraction we want them
61009** to have only a real value.
61010*/
61011case OP_RealAffinity: {                  /* in1 */
61012  pIn1 = &aMem[pOp->p1];
61013  if( pIn1->flags & MEM_Int ){
61014    sqlite3VdbeMemRealify(pIn1);
61015  }
61016  break;
61017}
61018#endif
61019
61020#ifndef SQLITE_OMIT_CAST
61021/* Opcode: ToText P1 * * * *
61022**
61023** Force the value in register P1 to be text.
61024** If the value is numeric, convert it to a string using the
61025** equivalent of printf().  Blob values are unchanged and
61026** are afterwards simply interpreted as text.
61027**
61028** A NULL value is not changed by this routine.  It remains NULL.
61029*/
61030case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
61031  pIn1 = &aMem[pOp->p1];
61032  if( pIn1->flags & MEM_Null ) break;
61033  assert( MEM_Str==(MEM_Blob>>3) );
61034  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
61035  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61036  rc = ExpandBlob(pIn1);
61037  assert( pIn1->flags & MEM_Str || db->mallocFailed );
61038  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
61039  UPDATE_MAX_BLOBSIZE(pIn1);
61040  break;
61041}
61042
61043/* Opcode: ToBlob P1 * * * *
61044**
61045** Force the value in register P1 to be a BLOB.
61046** If the value is numeric, convert it to a string first.
61047** Strings are simply reinterpreted as blobs with no change
61048** to the underlying data.
61049**
61050** A NULL value is not changed by this routine.  It remains NULL.
61051*/
61052case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
61053  pIn1 = &aMem[pOp->p1];
61054  if( pIn1->flags & MEM_Null ) break;
61055  if( (pIn1->flags & MEM_Blob)==0 ){
61056    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61057    assert( pIn1->flags & MEM_Str || db->mallocFailed );
61058    MemSetTypeFlag(pIn1, MEM_Blob);
61059  }else{
61060    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
61061  }
61062  UPDATE_MAX_BLOBSIZE(pIn1);
61063  break;
61064}
61065
61066/* Opcode: ToNumeric P1 * * * *
61067**
61068** Force the value in register P1 to be numeric (either an
61069** integer or a floating-point number.)
61070** If the value is text or blob, try to convert it to an using the
61071** equivalent of atoi() or atof() and store 0 if no such conversion
61072** is possible.
61073**
61074** A NULL value is not changed by this routine.  It remains NULL.
61075*/
61076case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
61077  pIn1 = &aMem[pOp->p1];
61078  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
61079    sqlite3VdbeMemNumerify(pIn1);
61080  }
61081  break;
61082}
61083#endif /* SQLITE_OMIT_CAST */
61084
61085/* Opcode: ToInt P1 * * * *
61086**
61087** Force the value in register P1 be an integer.  If
61088** The value is currently a real number, drop its fractional part.
61089** If the value is text or blob, try to convert it to an integer using the
61090** equivalent of atoi() and store 0 if no such conversion is possible.
61091**
61092** A NULL value is not changed by this routine.  It remains NULL.
61093*/
61094case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
61095  pIn1 = &aMem[pOp->p1];
61096  if( (pIn1->flags & MEM_Null)==0 ){
61097    sqlite3VdbeMemIntegerify(pIn1);
61098  }
61099  break;
61100}
61101
61102#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
61103/* Opcode: ToReal P1 * * * *
61104**
61105** Force the value in register P1 to be a floating point number.
61106** If The value is currently an integer, convert it.
61107** If the value is text or blob, try to convert it to an integer using the
61108** equivalent of atoi() and store 0.0 if no such conversion is possible.
61109**
61110** A NULL value is not changed by this routine.  It remains NULL.
61111*/
61112case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
61113  pIn1 = &aMem[pOp->p1];
61114  if( (pIn1->flags & MEM_Null)==0 ){
61115    sqlite3VdbeMemRealify(pIn1);
61116  }
61117  break;
61118}
61119#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
61120
61121/* Opcode: Lt P1 P2 P3 P4 P5
61122**
61123** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
61124** jump to address P2.
61125**
61126** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
61127** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
61128** bit is clear then fall thru if either operand is NULL.
61129**
61130** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
61131** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
61132** to coerce both inputs according to this affinity before the
61133** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
61134** affinity is used. Note that the affinity conversions are stored
61135** back into the input registers P1 and P3.  So this opcode can cause
61136** persistent changes to registers P1 and P3.
61137**
61138** Once any conversions have taken place, and neither value is NULL,
61139** the values are compared. If both values are blobs then memcmp() is
61140** used to determine the results of the comparison.  If both values
61141** are text, then the appropriate collating function specified in
61142** P4 is  used to do the comparison.  If P4 is not specified then
61143** memcmp() is used to compare text string.  If both values are
61144** numeric, then a numeric comparison is used. If the two values
61145** are of different types, then numbers are considered less than
61146** strings and strings are considered less than blobs.
61147**
61148** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
61149** store a boolean result (either 0, or 1, or NULL) in register P2.
61150*/
61151/* Opcode: Ne P1 P2 P3 P4 P5
61152**
61153** This works just like the Lt opcode except that the jump is taken if
61154** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
61155** additional information.
61156**
61157** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
61158** true or false and is never NULL.  If both operands are NULL then the result
61159** of comparison is false.  If either operand is NULL then the result is true.
61160** If neither operand is NULL the the result is the same as it would be if
61161** the SQLITE_NULLEQ flag were omitted from P5.
61162*/
61163/* Opcode: Eq P1 P2 P3 P4 P5
61164**
61165** This works just like the Lt opcode except that the jump is taken if
61166** the operands in registers P1 and P3 are equal.
61167** See the Lt opcode for additional information.
61168**
61169** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
61170** true or false and is never NULL.  If both operands are NULL then the result
61171** of comparison is true.  If either operand is NULL then the result is false.
61172** If neither operand is NULL the the result is the same as it would be if
61173** the SQLITE_NULLEQ flag were omitted from P5.
61174*/
61175/* Opcode: Le P1 P2 P3 P4 P5
61176**
61177** This works just like the Lt opcode except that the jump is taken if
61178** the content of register P3 is less than or equal to the content of
61179** register P1.  See the Lt opcode for additional information.
61180*/
61181/* Opcode: Gt P1 P2 P3 P4 P5
61182**
61183** This works just like the Lt opcode except that the jump is taken if
61184** the content of register P3 is greater than the content of
61185** register P1.  See the Lt opcode for additional information.
61186*/
61187/* Opcode: Ge P1 P2 P3 P4 P5
61188**
61189** This works just like the Lt opcode except that the jump is taken if
61190** the content of register P3 is greater than or equal to the content of
61191** register P1.  See the Lt opcode for additional information.
61192*/
61193case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
61194case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
61195case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
61196case OP_Le:               /* same as TK_LE, jump, in1, in3 */
61197case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
61198case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
61199#if 0  /* local variables moved into u.ai */
61200  int res;            /* Result of the comparison of pIn1 against pIn3 */
61201  char affinity;      /* Affinity to use for comparison */
61202  u16 flags1;         /* Copy of initial value of pIn1->flags */
61203  u16 flags3;         /* Copy of initial value of pIn3->flags */
61204#endif /* local variables moved into u.ai */
61205
61206  pIn1 = &aMem[pOp->p1];
61207  pIn3 = &aMem[pOp->p3];
61208  u.ai.flags1 = pIn1->flags;
61209  u.ai.flags3 = pIn3->flags;
61210  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
61211    /* One or both operands are NULL */
61212    if( pOp->p5 & SQLITE_NULLEQ ){
61213      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
61214      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
61215      ** or not both operands are null.
61216      */
61217      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
61218      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
61219    }else{
61220      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
61221      ** then the result is always NULL.
61222      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
61223      */
61224      if( pOp->p5 & SQLITE_STOREP2 ){
61225        pOut = &aMem[pOp->p2];
61226        MemSetTypeFlag(pOut, MEM_Null);
61227        REGISTER_TRACE(pOp->p2, pOut);
61228      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
61229        pc = pOp->p2-1;
61230      }
61231      break;
61232    }
61233  }else{
61234    /* Neither operand is NULL.  Do a comparison. */
61235    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
61236    if( u.ai.affinity ){
61237      applyAffinity(pIn1, u.ai.affinity, encoding);
61238      applyAffinity(pIn3, u.ai.affinity, encoding);
61239      if( db->mallocFailed ) goto no_mem;
61240    }
61241
61242    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
61243    ExpandBlob(pIn1);
61244    ExpandBlob(pIn3);
61245    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
61246  }
61247  switch( pOp->opcode ){
61248    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
61249    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
61250    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
61251    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
61252    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
61253    default:       u.ai.res = u.ai.res>=0;     break;
61254  }
61255
61256  if( pOp->p5 & SQLITE_STOREP2 ){
61257    pOut = &aMem[pOp->p2];
61258    MemSetTypeFlag(pOut, MEM_Int);
61259    pOut->u.i = u.ai.res;
61260    REGISTER_TRACE(pOp->p2, pOut);
61261  }else if( u.ai.res ){
61262    pc = pOp->p2-1;
61263  }
61264
61265  /* Undo any changes made by applyAffinity() to the input registers. */
61266  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
61267  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
61268  break;
61269}
61270
61271/* Opcode: Permutation * * * P4 *
61272**
61273** Set the permutation used by the OP_Compare operator to be the array
61274** of integers in P4.
61275**
61276** The permutation is only valid until the next OP_Permutation, OP_Compare,
61277** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
61278** immediately prior to the OP_Compare.
61279*/
61280case OP_Permutation: {
61281  assert( pOp->p4type==P4_INTARRAY );
61282  assert( pOp->p4.ai );
61283  aPermute = pOp->p4.ai;
61284  break;
61285}
61286
61287/* Opcode: Compare P1 P2 P3 P4 *
61288**
61289** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
61290** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
61291** the comparison for use by the next OP_Jump instruct.
61292**
61293** P4 is a KeyInfo structure that defines collating sequences and sort
61294** orders for the comparison.  The permutation applies to registers
61295** only.  The KeyInfo elements are used sequentially.
61296**
61297** The comparison is a sort comparison, so NULLs compare equal,
61298** NULLs are less than numbers, numbers are less than strings,
61299** and strings are less than blobs.
61300*/
61301case OP_Compare: {
61302#if 0  /* local variables moved into u.aj */
61303  int n;
61304  int i;
61305  int p1;
61306  int p2;
61307  const KeyInfo *pKeyInfo;
61308  int idx;
61309  CollSeq *pColl;    /* Collating sequence to use on this term */
61310  int bRev;          /* True for DESCENDING sort order */
61311#endif /* local variables moved into u.aj */
61312
61313  u.aj.n = pOp->p3;
61314  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
61315  assert( u.aj.n>0 );
61316  assert( u.aj.pKeyInfo!=0 );
61317  u.aj.p1 = pOp->p1;
61318  u.aj.p2 = pOp->p2;
61319#if SQLITE_DEBUG
61320  if( aPermute ){
61321    int k, mx = 0;
61322    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
61323    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
61324    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
61325  }else{
61326    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
61327    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
61328  }
61329#endif /* SQLITE_DEBUG */
61330  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
61331    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
61332    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
61333    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
61334    assert( u.aj.i<u.aj.pKeyInfo->nField );
61335    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
61336    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
61337    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
61338    if( iCompare ){
61339      if( u.aj.bRev ) iCompare = -iCompare;
61340      break;
61341    }
61342  }
61343  aPermute = 0;
61344  break;
61345}
61346
61347/* Opcode: Jump P1 P2 P3 * *
61348**
61349** Jump to the instruction at address P1, P2, or P3 depending on whether
61350** in the most recent OP_Compare instruction the P1 vector was less than
61351** equal to, or greater than the P2 vector, respectively.
61352*/
61353case OP_Jump: {             /* jump */
61354  if( iCompare<0 ){
61355    pc = pOp->p1 - 1;
61356  }else if( iCompare==0 ){
61357    pc = pOp->p2 - 1;
61358  }else{
61359    pc = pOp->p3 - 1;
61360  }
61361  break;
61362}
61363
61364/* Opcode: And P1 P2 P3 * *
61365**
61366** Take the logical AND of the values in registers P1 and P2 and
61367** write the result into register P3.
61368**
61369** If either P1 or P2 is 0 (false) then the result is 0 even if
61370** the other input is NULL.  A NULL and true or two NULLs give
61371** a NULL output.
61372*/
61373/* Opcode: Or P1 P2 P3 * *
61374**
61375** Take the logical OR of the values in register P1 and P2 and
61376** store the answer in register P3.
61377**
61378** If either P1 or P2 is nonzero (true) then the result is 1 (true)
61379** even if the other input is NULL.  A NULL and false or two NULLs
61380** give a NULL output.
61381*/
61382case OP_And:              /* same as TK_AND, in1, in2, out3 */
61383case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
61384#if 0  /* local variables moved into u.ak */
61385  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
61386  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
61387#endif /* local variables moved into u.ak */
61388
61389  pIn1 = &aMem[pOp->p1];
61390  if( pIn1->flags & MEM_Null ){
61391    u.ak.v1 = 2;
61392  }else{
61393    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
61394  }
61395  pIn2 = &aMem[pOp->p2];
61396  if( pIn2->flags & MEM_Null ){
61397    u.ak.v2 = 2;
61398  }else{
61399    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
61400  }
61401  if( pOp->opcode==OP_And ){
61402    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
61403    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
61404  }else{
61405    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
61406    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
61407  }
61408  pOut = &aMem[pOp->p3];
61409  if( u.ak.v1==2 ){
61410    MemSetTypeFlag(pOut, MEM_Null);
61411  }else{
61412    pOut->u.i = u.ak.v1;
61413    MemSetTypeFlag(pOut, MEM_Int);
61414  }
61415  break;
61416}
61417
61418/* Opcode: Not P1 P2 * * *
61419**
61420** Interpret the value in register P1 as a boolean value.  Store the
61421** boolean complement in register P2.  If the value in register P1 is
61422** NULL, then a NULL is stored in P2.
61423*/
61424case OP_Not: {                /* same as TK_NOT, in1, out2 */
61425  pIn1 = &aMem[pOp->p1];
61426  pOut = &aMem[pOp->p2];
61427  if( pIn1->flags & MEM_Null ){
61428    sqlite3VdbeMemSetNull(pOut);
61429  }else{
61430    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
61431  }
61432  break;
61433}
61434
61435/* Opcode: BitNot P1 P2 * * *
61436**
61437** Interpret the content of register P1 as an integer.  Store the
61438** ones-complement of the P1 value into register P2.  If P1 holds
61439** a NULL then store a NULL in P2.
61440*/
61441case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
61442  pIn1 = &aMem[pOp->p1];
61443  pOut = &aMem[pOp->p2];
61444  if( pIn1->flags & MEM_Null ){
61445    sqlite3VdbeMemSetNull(pOut);
61446  }else{
61447    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
61448  }
61449  break;
61450}
61451
61452/* Opcode: If P1 P2 P3 * *
61453**
61454** Jump to P2 if the value in register P1 is true.  The value is
61455** is considered true if it is numeric and non-zero.  If the value
61456** in P1 is NULL then take the jump if P3 is true.
61457*/
61458/* Opcode: IfNot P1 P2 P3 * *
61459**
61460** Jump to P2 if the value in register P1 is False.  The value is
61461** is considered true if it has a numeric value of zero.  If the value
61462** in P1 is NULL then take the jump if P3 is true.
61463*/
61464case OP_If:                 /* jump, in1 */
61465case OP_IfNot: {            /* jump, in1 */
61466#if 0  /* local variables moved into u.al */
61467  int c;
61468#endif /* local variables moved into u.al */
61469  pIn1 = &aMem[pOp->p1];
61470  if( pIn1->flags & MEM_Null ){
61471    u.al.c = pOp->p3;
61472  }else{
61473#ifdef SQLITE_OMIT_FLOATING_POINT
61474    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
61475#else
61476    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
61477#endif
61478    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
61479  }
61480  if( u.al.c ){
61481    pc = pOp->p2-1;
61482  }
61483  break;
61484}
61485
61486/* Opcode: IsNull P1 P2 * * *
61487**
61488** Jump to P2 if the value in register P1 is NULL.
61489*/
61490case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
61491  pIn1 = &aMem[pOp->p1];
61492  if( (pIn1->flags & MEM_Null)!=0 ){
61493    pc = pOp->p2 - 1;
61494  }
61495  break;
61496}
61497
61498/* Opcode: NotNull P1 P2 * * *
61499**
61500** Jump to P2 if the value in register P1 is not NULL.
61501*/
61502case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
61503  pIn1 = &aMem[pOp->p1];
61504  if( (pIn1->flags & MEM_Null)==0 ){
61505    pc = pOp->p2 - 1;
61506  }
61507  break;
61508}
61509
61510/* Opcode: Column P1 P2 P3 P4 P5
61511**
61512** Interpret the data that cursor P1 points to as a structure built using
61513** the MakeRecord instruction.  (See the MakeRecord opcode for additional
61514** information about the format of the data.)  Extract the P2-th column
61515** from this record.  If there are less that (P2+1)
61516** values in the record, extract a NULL.
61517**
61518** The value extracted is stored in register P3.
61519**
61520** If the column contains fewer than P2 fields, then extract a NULL.  Or,
61521** if the P4 argument is a P4_MEM use the value of the P4 argument as
61522** the result.
61523**
61524** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
61525** then the cache of the cursor is reset prior to extracting the column.
61526** The first OP_Column against a pseudo-table after the value of the content
61527** register has changed should have this bit set.
61528*/
61529case OP_Column: {
61530#if 0  /* local variables moved into u.am */
61531  u32 payloadSize;   /* Number of bytes in the record */
61532  i64 payloadSize64; /* Number of bytes in the record */
61533  int p1;            /* P1 value of the opcode */
61534  int p2;            /* column number to retrieve */
61535  VdbeCursor *pC;    /* The VDBE cursor */
61536  char *zRec;        /* Pointer to complete record-data */
61537  BtCursor *pCrsr;   /* The BTree cursor */
61538  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
61539  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
61540  int nField;        /* number of fields in the record */
61541  int len;           /* The length of the serialized data for the column */
61542  int i;             /* Loop counter */
61543  char *zData;       /* Part of the record being decoded */
61544  Mem *pDest;        /* Where to write the extracted value */
61545  Mem sMem;          /* For storing the record being decoded */
61546  u8 *zIdx;          /* Index into header */
61547  u8 *zEndHdr;       /* Pointer to first byte after the header */
61548  u32 offset;        /* Offset into the data */
61549  u32 szField;       /* Number of bytes in the content of a field */
61550  int szHdr;         /* Size of the header size field at start of record */
61551  int avail;         /* Number of bytes of available data */
61552  Mem *pReg;         /* PseudoTable input register */
61553#endif /* local variables moved into u.am */
61554
61555
61556  u.am.p1 = pOp->p1;
61557  u.am.p2 = pOp->p2;
61558  u.am.pC = 0;
61559  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
61560  assert( u.am.p1<p->nCursor );
61561  assert( pOp->p3>0 && pOp->p3<=p->nMem );
61562  u.am.pDest = &aMem[pOp->p3];
61563  MemSetTypeFlag(u.am.pDest, MEM_Null);
61564  u.am.zRec = 0;
61565
61566  /* This block sets the variable u.am.payloadSize to be the total number of
61567  ** bytes in the record.
61568  **
61569  ** u.am.zRec is set to be the complete text of the record if it is available.
61570  ** The complete record text is always available for pseudo-tables
61571  ** If the record is stored in a cursor, the complete record text
61572  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
61573  ** If the data is unavailable,  u.am.zRec is set to NULL.
61574  **
61575  ** We also compute the number of columns in the record.  For cursors,
61576  ** the number of columns is stored in the VdbeCursor.nField element.
61577  */
61578  u.am.pC = p->apCsr[u.am.p1];
61579  assert( u.am.pC!=0 );
61580#ifndef SQLITE_OMIT_VIRTUALTABLE
61581  assert( u.am.pC->pVtabCursor==0 );
61582#endif
61583  u.am.pCrsr = u.am.pC->pCursor;
61584  if( u.am.pCrsr!=0 ){
61585    /* The record is stored in a B-Tree */
61586    rc = sqlite3VdbeCursorMoveto(u.am.pC);
61587    if( rc ) goto abort_due_to_error;
61588    if( u.am.pC->nullRow ){
61589      u.am.payloadSize = 0;
61590    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
61591      u.am.payloadSize = u.am.pC->payloadSize;
61592      u.am.zRec = (char*)u.am.pC->aRow;
61593    }else if( u.am.pC->isIndex ){
61594      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
61595      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
61596      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
61597      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
61598      ** payload size, so it is impossible for u.am.payloadSize64 to be
61599      ** larger than 32 bits. */
61600      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
61601      u.am.payloadSize = (u32)u.am.payloadSize64;
61602    }else{
61603      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
61604      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
61605      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
61606    }
61607  }else if( u.am.pC->pseudoTableReg>0 ){
61608    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
61609    assert( u.am.pReg->flags & MEM_Blob );
61610    u.am.payloadSize = u.am.pReg->n;
61611    u.am.zRec = u.am.pReg->z;
61612    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
61613    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
61614  }else{
61615    /* Consider the row to be NULL */
61616    u.am.payloadSize = 0;
61617  }
61618
61619  /* If u.am.payloadSize is 0, then just store a NULL */
61620  if( u.am.payloadSize==0 ){
61621    assert( u.am.pDest->flags&MEM_Null );
61622    goto op_column_out;
61623  }
61624  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
61625  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
61626    goto too_big;
61627  }
61628
61629  u.am.nField = u.am.pC->nField;
61630  assert( u.am.p2<u.am.nField );
61631
61632  /* Read and parse the table header.  Store the results of the parse
61633  ** into the record header cache fields of the cursor.
61634  */
61635  u.am.aType = u.am.pC->aType;
61636  if( u.am.pC->cacheStatus==p->cacheCtr ){
61637    u.am.aOffset = u.am.pC->aOffset;
61638  }else{
61639    assert(u.am.aType);
61640    u.am.avail = 0;
61641    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
61642    u.am.pC->payloadSize = u.am.payloadSize;
61643    u.am.pC->cacheStatus = p->cacheCtr;
61644
61645    /* Figure out how many bytes are in the header */
61646    if( u.am.zRec ){
61647      u.am.zData = u.am.zRec;
61648    }else{
61649      if( u.am.pC->isIndex ){
61650        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
61651      }else{
61652        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
61653      }
61654      /* If KeyFetch()/DataFetch() managed to get the entire payload,
61655      ** save the payload in the u.am.pC->aRow cache.  That will save us from
61656      ** having to make additional calls to fetch the content portion of
61657      ** the record.
61658      */
61659      assert( u.am.avail>=0 );
61660      if( u.am.payloadSize <= (u32)u.am.avail ){
61661        u.am.zRec = u.am.zData;
61662        u.am.pC->aRow = (u8*)u.am.zData;
61663      }else{
61664        u.am.pC->aRow = 0;
61665      }
61666    }
61667    /* The following assert is true in all cases accept when
61668    ** the database file has been corrupted externally.
61669    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
61670    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
61671
61672    /* Make sure a corrupt database has not given us an oversize header.
61673    ** Do this now to avoid an oversize memory allocation.
61674    **
61675    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
61676    ** types use so much data space that there can only be 4096 and 32 of
61677    ** them, respectively.  So the maximum header length results from a
61678    ** 3-byte type for each of the maximum of 32768 columns plus three
61679    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
61680    */
61681    if( u.am.offset > 98307 ){
61682      rc = SQLITE_CORRUPT_BKPT;
61683      goto op_column_out;
61684    }
61685
61686    /* Compute in u.am.len the number of bytes of data we need to read in order
61687    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
61688    ** u.am.nField might be significantly less than the true number of columns
61689    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
61690    ** We want to minimize u.am.len in order to limit the size of the memory
61691    ** allocation, especially if a corrupt database file has caused u.am.offset
61692    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
61693    ** still exceed Robson memory allocation limits on some configurations.
61694    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
61695    ** will likely be much smaller since u.am.nField will likely be less than
61696    ** 20 or so.  This insures that Robson memory allocation limits are
61697    ** not exceeded even for corrupt database files.
61698    */
61699    u.am.len = u.am.nField*5 + 3;
61700    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
61701
61702    /* The KeyFetch() or DataFetch() above are fast and will get the entire
61703    ** record header in most cases.  But they will fail to get the complete
61704    ** record header if the record header does not fit on a single page
61705    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
61706    ** acquire the complete header text.
61707    */
61708    if( !u.am.zRec && u.am.avail<u.am.len ){
61709      u.am.sMem.flags = 0;
61710      u.am.sMem.db = 0;
61711      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
61712      if( rc!=SQLITE_OK ){
61713        goto op_column_out;
61714      }
61715      u.am.zData = u.am.sMem.z;
61716    }
61717    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
61718    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
61719
61720    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
61721    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
61722    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
61723    ** of the record to the start of the data for the u.am.i-th column
61724    */
61725    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
61726      if( u.am.zIdx<u.am.zEndHdr ){
61727        u.am.aOffset[u.am.i] = u.am.offset;
61728        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
61729        u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
61730        u.am.offset += u.am.szField;
61731        if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
61732          u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
61733          break;
61734        }
61735      }else{
61736        /* If u.am.i is less that u.am.nField, then there are less fields in this
61737        ** record than SetNumColumns indicated there are columns in the
61738        ** table. Set the u.am.offset for any extra columns not present in
61739        ** the record to 0. This tells code below to store a NULL
61740        ** instead of deserializing a value from the record.
61741        */
61742        u.am.aOffset[u.am.i] = 0;
61743      }
61744    }
61745    sqlite3VdbeMemRelease(&u.am.sMem);
61746    u.am.sMem.flags = MEM_Null;
61747
61748    /* If we have read more header data than was contained in the header,
61749    ** or if the end of the last field appears to be past the end of the
61750    ** record, or if the end of the last field appears to be before the end
61751    ** of the record (when all fields present), then we must be dealing
61752    ** with a corrupt database.
61753    */
61754    if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
61755         || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
61756      rc = SQLITE_CORRUPT_BKPT;
61757      goto op_column_out;
61758    }
61759  }
61760
61761  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
61762  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
61763  ** then there are not enough fields in the record to satisfy the
61764  ** request.  In this case, set the value NULL or to P4 if P4 is
61765  ** a pointer to a Mem object.
61766  */
61767  if( u.am.aOffset[u.am.p2] ){
61768    assert( rc==SQLITE_OK );
61769    if( u.am.zRec ){
61770      sqlite3VdbeMemReleaseExternal(u.am.pDest);
61771      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
61772    }else{
61773      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
61774      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
61775      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
61776      if( rc!=SQLITE_OK ){
61777        goto op_column_out;
61778      }
61779      u.am.zData = u.am.sMem.z;
61780      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
61781    }
61782    u.am.pDest->enc = encoding;
61783  }else{
61784    if( pOp->p4type==P4_MEM ){
61785      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
61786    }else{
61787      assert( u.am.pDest->flags&MEM_Null );
61788    }
61789  }
61790
61791  /* If we dynamically allocated space to hold the data (in the
61792  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
61793  ** dynamically allocated space over to the u.am.pDest structure.
61794  ** This prevents a memory copy.
61795  */
61796  if( u.am.sMem.zMalloc ){
61797    assert( u.am.sMem.z==u.am.sMem.zMalloc );
61798    assert( !(u.am.pDest->flags & MEM_Dyn) );
61799    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
61800    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
61801    u.am.pDest->flags |= MEM_Term;
61802    u.am.pDest->z = u.am.sMem.z;
61803    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
61804  }
61805
61806  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
61807
61808op_column_out:
61809  UPDATE_MAX_BLOBSIZE(u.am.pDest);
61810  REGISTER_TRACE(pOp->p3, u.am.pDest);
61811  break;
61812}
61813
61814/* Opcode: Affinity P1 P2 * P4 *
61815**
61816** Apply affinities to a range of P2 registers starting with P1.
61817**
61818** P4 is a string that is P2 characters long. The nth character of the
61819** string indicates the column affinity that should be used for the nth
61820** memory cell in the range.
61821*/
61822case OP_Affinity: {
61823#if 0  /* local variables moved into u.an */
61824  const char *zAffinity;   /* The affinity to be applied */
61825  char cAff;               /* A single character of affinity */
61826#endif /* local variables moved into u.an */
61827
61828  u.an.zAffinity = pOp->p4.z;
61829  assert( u.an.zAffinity!=0 );
61830  assert( u.an.zAffinity[pOp->p2]==0 );
61831  pIn1 = &aMem[pOp->p1];
61832  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
61833    assert( pIn1 <= &p->aMem[p->nMem] );
61834    ExpandBlob(pIn1);
61835    applyAffinity(pIn1, u.an.cAff, encoding);
61836    pIn1++;
61837  }
61838  break;
61839}
61840
61841/* Opcode: MakeRecord P1 P2 P3 P4 *
61842**
61843** Convert P2 registers beginning with P1 into a single entry
61844** suitable for use as a data record in a database table or as a key
61845** in an index.  The details of the format are irrelevant as long as
61846** the OP_Column opcode can decode the record later.
61847** Refer to source code comments for the details of the record
61848** format.
61849**
61850** P4 may be a string that is P2 characters long.  The nth character of the
61851** string indicates the column affinity that should be used for the nth
61852** field of the index key.
61853**
61854** The mapping from character to affinity is given by the SQLITE_AFF_
61855** macros defined in sqliteInt.h.
61856**
61857** If P4 is NULL then all index fields have the affinity NONE.
61858*/
61859case OP_MakeRecord: {
61860#if 0  /* local variables moved into u.ao */
61861  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
61862  Mem *pRec;             /* The new record */
61863  u64 nData;             /* Number of bytes of data space */
61864  int nHdr;              /* Number of bytes of header space */
61865  i64 nByte;             /* Data space required for this record */
61866  int nZero;             /* Number of zero bytes at the end of the record */
61867  int nVarint;           /* Number of bytes in a varint */
61868  u32 serial_type;       /* Type field */
61869  Mem *pData0;           /* First field to be combined into the record */
61870  Mem *pLast;            /* Last field of the record */
61871  int nField;            /* Number of fields in the record */
61872  char *zAffinity;       /* The affinity string for the record */
61873  int file_format;       /* File format to use for encoding */
61874  int i;                 /* Space used in zNewRecord[] */
61875  int len;               /* Length of a field */
61876#endif /* local variables moved into u.ao */
61877
61878  /* Assuming the record contains N fields, the record format looks
61879  ** like this:
61880  **
61881  ** ------------------------------------------------------------------------
61882  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
61883  ** ------------------------------------------------------------------------
61884  **
61885  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
61886  ** and so froth.
61887  **
61888  ** Each type field is a varint representing the serial type of the
61889  ** corresponding data element (see sqlite3VdbeSerialType()). The
61890  ** hdr-size field is also a varint which is the offset from the beginning
61891  ** of the record to data0.
61892  */
61893  u.ao.nData = 0;         /* Number of bytes of data space */
61894  u.ao.nHdr = 0;          /* Number of bytes of header space */
61895  u.ao.nByte = 0;         /* Data space required for this record */
61896  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
61897  u.ao.nField = pOp->p1;
61898  u.ao.zAffinity = pOp->p4.z;
61899  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
61900  u.ao.pData0 = &aMem[u.ao.nField];
61901  u.ao.nField = pOp->p2;
61902  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
61903  u.ao.file_format = p->minWriteFileFormat;
61904
61905  /* Loop through the elements that will make up the record to figure
61906  ** out how much space is required for the new record.
61907  */
61908  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
61909    if( u.ao.zAffinity ){
61910      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
61911    }
61912    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
61913      sqlite3VdbeMemExpandBlob(u.ao.pRec);
61914    }
61915    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
61916    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
61917    u.ao.nData += u.ao.len;
61918    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
61919    if( u.ao.pRec->flags & MEM_Zero ){
61920      /* Only pure zero-filled BLOBs can be input to this Opcode.
61921      ** We do not allow blobs with a prefix and a zero-filled tail. */
61922      u.ao.nZero += u.ao.pRec->u.nZero;
61923    }else if( u.ao.len ){
61924      u.ao.nZero = 0;
61925    }
61926  }
61927
61928  /* Add the initial header varint and total the size */
61929  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
61930  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
61931    u.ao.nHdr++;
61932  }
61933  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
61934  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
61935    goto too_big;
61936  }
61937
61938  /* Make sure the output register has a buffer large enough to store
61939  ** the new record. The output register (pOp->p3) is not allowed to
61940  ** be one of the input registers (because the following call to
61941  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
61942  */
61943  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
61944  pOut = &aMem[pOp->p3];
61945  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
61946    goto no_mem;
61947  }
61948  u.ao.zNewRecord = (u8 *)pOut->z;
61949
61950  /* Write the record */
61951  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
61952  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
61953    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
61954    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
61955  }
61956  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
61957    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
61958  }
61959  assert( u.ao.i==u.ao.nByte );
61960
61961  assert( pOp->p3>0 && pOp->p3<=p->nMem );
61962  pOut->n = (int)u.ao.nByte;
61963  pOut->flags = MEM_Blob | MEM_Dyn;
61964  pOut->xDel = 0;
61965  if( u.ao.nZero ){
61966    pOut->u.nZero = u.ao.nZero;
61967    pOut->flags |= MEM_Zero;
61968  }
61969  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
61970  REGISTER_TRACE(pOp->p3, pOut);
61971  UPDATE_MAX_BLOBSIZE(pOut);
61972  break;
61973}
61974
61975/* Opcode: Count P1 P2 * * *
61976**
61977** Store the number of entries (an integer value) in the table or index
61978** opened by cursor P1 in register P2
61979*/
61980#ifndef SQLITE_OMIT_BTREECOUNT
61981case OP_Count: {         /* out2-prerelease */
61982#if 0  /* local variables moved into u.ap */
61983  i64 nEntry;
61984  BtCursor *pCrsr;
61985#endif /* local variables moved into u.ap */
61986
61987  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
61988  if( u.ap.pCrsr ){
61989    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
61990  }else{
61991    u.ap.nEntry = 0;
61992  }
61993  pOut->u.i = u.ap.nEntry;
61994  break;
61995}
61996#endif
61997
61998/* Opcode: Savepoint P1 * * P4 *
61999**
62000** Open, release or rollback the savepoint named by parameter P4, depending
62001** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
62002** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
62003*/
62004case OP_Savepoint: {
62005#if 0  /* local variables moved into u.aq */
62006  int p1;                         /* Value of P1 operand */
62007  char *zName;                    /* Name of savepoint */
62008  int nName;
62009  Savepoint *pNew;
62010  Savepoint *pSavepoint;
62011  Savepoint *pTmp;
62012  int iSavepoint;
62013  int ii;
62014#endif /* local variables moved into u.aq */
62015
62016  u.aq.p1 = pOp->p1;
62017  u.aq.zName = pOp->p4.z;
62018
62019  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
62020  ** transaction, then there cannot be any savepoints.
62021  */
62022  assert( db->pSavepoint==0 || db->autoCommit==0 );
62023  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
62024  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
62025  assert( checkSavepointCount(db) );
62026
62027  if( u.aq.p1==SAVEPOINT_BEGIN ){
62028    if( db->writeVdbeCnt>0 ){
62029      /* A new savepoint cannot be created if there are active write
62030      ** statements (i.e. open read/write incremental blob handles).
62031      */
62032      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
62033        "SQL statements in progress");
62034      rc = SQLITE_BUSY;
62035    }else{
62036      u.aq.nName = sqlite3Strlen30(u.aq.zName);
62037
62038      /* Create a new savepoint structure. */
62039      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
62040      if( u.aq.pNew ){
62041        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
62042        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
62043
62044        /* If there is no open transaction, then mark this as a special
62045        ** "transaction savepoint". */
62046        if( db->autoCommit ){
62047          db->autoCommit = 0;
62048          db->isTransactionSavepoint = 1;
62049        }else{
62050          db->nSavepoint++;
62051        }
62052
62053        /* Link the new savepoint into the database handle's list. */
62054        u.aq.pNew->pNext = db->pSavepoint;
62055        db->pSavepoint = u.aq.pNew;
62056        u.aq.pNew->nDeferredCons = db->nDeferredCons;
62057      }
62058    }
62059  }else{
62060    u.aq.iSavepoint = 0;
62061
62062    /* Find the named savepoint. If there is no such savepoint, then an
62063    ** an error is returned to the user.  */
62064    for(
62065      u.aq.pSavepoint = db->pSavepoint;
62066      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
62067      u.aq.pSavepoint = u.aq.pSavepoint->pNext
62068    ){
62069      u.aq.iSavepoint++;
62070    }
62071    if( !u.aq.pSavepoint ){
62072      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
62073      rc = SQLITE_ERROR;
62074    }else if(
62075        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
62076    ){
62077      /* It is not possible to release (commit) a savepoint if there are
62078      ** active write statements. It is not possible to rollback a savepoint
62079      ** if there are any active statements at all.
62080      */
62081      sqlite3SetString(&p->zErrMsg, db,
62082        "cannot %s savepoint - SQL statements in progress",
62083        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
62084      );
62085      rc = SQLITE_BUSY;
62086    }else{
62087
62088      /* Determine whether or not this is a transaction savepoint. If so,
62089      ** and this is a RELEASE command, then the current transaction
62090      ** is committed.
62091      */
62092      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
62093      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
62094        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
62095          goto vdbe_return;
62096        }
62097        db->autoCommit = 1;
62098        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
62099          p->pc = pc;
62100          db->autoCommit = 0;
62101          p->rc = rc = SQLITE_BUSY;
62102          goto vdbe_return;
62103        }
62104        db->isTransactionSavepoint = 0;
62105        rc = p->rc;
62106      }else{
62107        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
62108        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
62109          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
62110          if( rc!=SQLITE_OK ){
62111            goto abort_due_to_error;
62112          }
62113        }
62114        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
62115          sqlite3ExpirePreparedStatements(db);
62116          sqlite3ResetInternalSchema(db, 0);
62117        }
62118      }
62119
62120      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
62121      ** savepoints nested inside of the savepoint being operated on. */
62122      while( db->pSavepoint!=u.aq.pSavepoint ){
62123        u.aq.pTmp = db->pSavepoint;
62124        db->pSavepoint = u.aq.pTmp->pNext;
62125        sqlite3DbFree(db, u.aq.pTmp);
62126        db->nSavepoint--;
62127      }
62128
62129      /* If it is a RELEASE, then destroy the savepoint being operated on
62130      ** too. If it is a ROLLBACK TO, then set the number of deferred
62131      ** constraint violations present in the database to the value stored
62132      ** when the savepoint was created.  */
62133      if( u.aq.p1==SAVEPOINT_RELEASE ){
62134        assert( u.aq.pSavepoint==db->pSavepoint );
62135        db->pSavepoint = u.aq.pSavepoint->pNext;
62136        sqlite3DbFree(db, u.aq.pSavepoint);
62137        if( !isTransaction ){
62138          db->nSavepoint--;
62139        }
62140      }else{
62141        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
62142      }
62143    }
62144  }
62145
62146  break;
62147}
62148
62149/* Opcode: AutoCommit P1 P2 * * *
62150**
62151** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
62152** back any currently active btree transactions. If there are any active
62153** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
62154** there are active writing VMs or active VMs that use shared cache.
62155**
62156** This instruction causes the VM to halt.
62157*/
62158case OP_AutoCommit: {
62159#if 0  /* local variables moved into u.ar */
62160  int desiredAutoCommit;
62161  int iRollback;
62162  int turnOnAC;
62163#endif /* local variables moved into u.ar */
62164
62165  u.ar.desiredAutoCommit = pOp->p1;
62166  u.ar.iRollback = pOp->p2;
62167  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
62168  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
62169  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
62170  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
62171
62172  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
62173    /* If this instruction implements a ROLLBACK and other VMs are
62174    ** still running, and a transaction is active, return an error indicating
62175    ** that the other VMs must complete first.
62176    */
62177    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
62178        "SQL statements in progress");
62179    rc = SQLITE_BUSY;
62180  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
62181    /* If this instruction implements a COMMIT and other VMs are writing
62182    ** return an error indicating that the other VMs must complete first.
62183    */
62184    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
62185        "SQL statements in progress");
62186    rc = SQLITE_BUSY;
62187  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
62188    if( u.ar.iRollback ){
62189      assert( u.ar.desiredAutoCommit==1 );
62190      sqlite3RollbackAll(db);
62191      db->autoCommit = 1;
62192    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
62193      goto vdbe_return;
62194    }else{
62195      db->autoCommit = (u8)u.ar.desiredAutoCommit;
62196      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
62197        p->pc = pc;
62198        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
62199        p->rc = rc = SQLITE_BUSY;
62200        goto vdbe_return;
62201      }
62202    }
62203    assert( db->nStatement==0 );
62204    sqlite3CloseSavepoints(db);
62205    if( p->rc==SQLITE_OK ){
62206      rc = SQLITE_DONE;
62207    }else{
62208      rc = SQLITE_ERROR;
62209    }
62210    goto vdbe_return;
62211  }else{
62212    sqlite3SetString(&p->zErrMsg, db,
62213        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
62214        (u.ar.iRollback)?"cannot rollback - no transaction is active":
62215                   "cannot commit - no transaction is active"));
62216
62217    rc = SQLITE_ERROR;
62218  }
62219  break;
62220}
62221
62222/* Opcode: Transaction P1 P2 * * *
62223**
62224** Begin a transaction.  The transaction ends when a Commit or Rollback
62225** opcode is encountered.  Depending on the ON CONFLICT setting, the
62226** transaction might also be rolled back if an error is encountered.
62227**
62228** P1 is the index of the database file on which the transaction is
62229** started.  Index 0 is the main database file and index 1 is the
62230** file used for temporary tables.  Indices of 2 or more are used for
62231** attached databases.
62232**
62233** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
62234** obtained on the database file when a write-transaction is started.  No
62235** other process can start another write transaction while this transaction is
62236** underway.  Starting a write transaction also creates a rollback journal. A
62237** write transaction must be started before any changes can be made to the
62238** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
62239** on the file.
62240**
62241** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
62242** true (this flag is set if the Vdbe may modify more than one row and may
62243** throw an ABORT exception), a statement transaction may also be opened.
62244** More specifically, a statement transaction is opened iff the database
62245** connection is currently not in autocommit mode, or if there are other
62246** active statements. A statement transaction allows the affects of this
62247** VDBE to be rolled back after an error without having to roll back the
62248** entire transaction. If no error is encountered, the statement transaction
62249** will automatically commit when the VDBE halts.
62250**
62251** If P2 is zero, then a read-lock is obtained on the database file.
62252*/
62253case OP_Transaction: {
62254#if 0  /* local variables moved into u.as */
62255  Btree *pBt;
62256#endif /* local variables moved into u.as */
62257
62258  assert( pOp->p1>=0 && pOp->p1<db->nDb );
62259  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62260  u.as.pBt = db->aDb[pOp->p1].pBt;
62261
62262  if( u.as.pBt ){
62263    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
62264    if( rc==SQLITE_BUSY ){
62265      p->pc = pc;
62266      p->rc = rc = SQLITE_BUSY;
62267      goto vdbe_return;
62268    }
62269    if( rc!=SQLITE_OK ){
62270      goto abort_due_to_error;
62271    }
62272
62273    if( pOp->p2 && p->usesStmtJournal
62274     && (db->autoCommit==0 || db->activeVdbeCnt>1)
62275    ){
62276      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
62277      if( p->iStatement==0 ){
62278        assert( db->nStatement>=0 && db->nSavepoint>=0 );
62279        db->nStatement++;
62280        p->iStatement = db->nSavepoint + db->nStatement;
62281      }
62282      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
62283
62284      /* Store the current value of the database handles deferred constraint
62285      ** counter. If the statement transaction needs to be rolled back,
62286      ** the value of this counter needs to be restored too.  */
62287      p->nStmtDefCons = db->nDeferredCons;
62288    }
62289  }
62290  break;
62291}
62292
62293/* Opcode: ReadCookie P1 P2 P3 * *
62294**
62295** Read cookie number P3 from database P1 and write it into register P2.
62296** P3==1 is the schema version.  P3==2 is the database format.
62297** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
62298** the main database file and P1==1 is the database file used to store
62299** temporary tables.
62300**
62301** There must be a read-lock on the database (either a transaction
62302** must be started or there must be an open cursor) before
62303** executing this instruction.
62304*/
62305case OP_ReadCookie: {               /* out2-prerelease */
62306#if 0  /* local variables moved into u.at */
62307  int iMeta;
62308  int iDb;
62309  int iCookie;
62310#endif /* local variables moved into u.at */
62311
62312  u.at.iDb = pOp->p1;
62313  u.at.iCookie = pOp->p3;
62314  assert( pOp->p3<SQLITE_N_BTREE_META );
62315  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
62316  assert( db->aDb[u.at.iDb].pBt!=0 );
62317  assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
62318
62319  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
62320  pOut->u.i = u.at.iMeta;
62321  break;
62322}
62323
62324/* Opcode: SetCookie P1 P2 P3 * *
62325**
62326** Write the content of register P3 (interpreted as an integer)
62327** into cookie number P2 of database P1.  P2==1 is the schema version.
62328** P2==2 is the database format. P2==3 is the recommended pager cache
62329** size, and so forth.  P1==0 is the main database file and P1==1 is the
62330** database file used to store temporary tables.
62331**
62332** A transaction must be started before executing this opcode.
62333*/
62334case OP_SetCookie: {       /* in3 */
62335#if 0  /* local variables moved into u.au */
62336  Db *pDb;
62337#endif /* local variables moved into u.au */
62338  assert( pOp->p2<SQLITE_N_BTREE_META );
62339  assert( pOp->p1>=0 && pOp->p1<db->nDb );
62340  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62341  u.au.pDb = &db->aDb[pOp->p1];
62342  assert( u.au.pDb->pBt!=0 );
62343  pIn3 = &aMem[pOp->p3];
62344  sqlite3VdbeMemIntegerify(pIn3);
62345  /* See note about index shifting on OP_ReadCookie */
62346  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
62347  if( pOp->p2==BTREE_SCHEMA_VERSION ){
62348    /* When the schema cookie changes, record the new cookie internally */
62349    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
62350    db->flags |= SQLITE_InternChanges;
62351  }else if( pOp->p2==BTREE_FILE_FORMAT ){
62352    /* Record changes in the file format */
62353    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
62354  }
62355  if( pOp->p1==1 ){
62356    /* Invalidate all prepared statements whenever the TEMP database
62357    ** schema is changed.  Ticket #1644 */
62358    sqlite3ExpirePreparedStatements(db);
62359    p->expired = 0;
62360  }
62361  break;
62362}
62363
62364/* Opcode: VerifyCookie P1 P2 *
62365**
62366** Check the value of global database parameter number 0 (the
62367** schema version) and make sure it is equal to P2.
62368** P1 is the database number which is 0 for the main database file
62369** and 1 for the file holding temporary tables and some higher number
62370** for auxiliary databases.
62371**
62372** The cookie changes its value whenever the database schema changes.
62373** This operation is used to detect when that the cookie has changed
62374** and that the current process needs to reread the schema.
62375**
62376** Either a transaction needs to have been started or an OP_Open needs
62377** to be executed (to establish a read lock) before this opcode is
62378** invoked.
62379*/
62380case OP_VerifyCookie: {
62381#if 0  /* local variables moved into u.av */
62382  int iMeta;
62383  Btree *pBt;
62384#endif /* local variables moved into u.av */
62385  assert( pOp->p1>=0 && pOp->p1<db->nDb );
62386  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
62387  u.av.pBt = db->aDb[pOp->p1].pBt;
62388  if( u.av.pBt ){
62389    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
62390  }else{
62391    u.av.iMeta = 0;
62392  }
62393  if( u.av.iMeta!=pOp->p2 ){
62394    sqlite3DbFree(db, p->zErrMsg);
62395    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
62396    /* If the schema-cookie from the database file matches the cookie
62397    ** stored with the in-memory representation of the schema, do
62398    ** not reload the schema from the database file.
62399    **
62400    ** If virtual-tables are in use, this is not just an optimization.
62401    ** Often, v-tables store their data in other SQLite tables, which
62402    ** are queried from within xNext() and other v-table methods using
62403    ** prepared queries. If such a query is out-of-date, we do not want to
62404    ** discard the database schema, as the user code implementing the
62405    ** v-table would have to be ready for the sqlite3_vtab structure itself
62406    ** to be invalidated whenever sqlite3_step() is called from within
62407    ** a v-table method.
62408    */
62409    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
62410      sqlite3ResetInternalSchema(db, pOp->p1);
62411    }
62412
62413    sqlite3ExpirePreparedStatements(db);
62414    rc = SQLITE_SCHEMA;
62415  }
62416  break;
62417}
62418
62419/* Opcode: OpenRead P1 P2 P3 P4 P5
62420**
62421** Open a read-only cursor for the database table whose root page is
62422** P2 in a database file.  The database file is determined by P3.
62423** P3==0 means the main database, P3==1 means the database used for
62424** temporary tables, and P3>1 means used the corresponding attached
62425** database.  Give the new cursor an identifier of P1.  The P1
62426** values need not be contiguous but all P1 values should be small integers.
62427** It is an error for P1 to be negative.
62428**
62429** If P5!=0 then use the content of register P2 as the root page, not
62430** the value of P2 itself.
62431**
62432** There will be a read lock on the database whenever there is an
62433** open cursor.  If the database was unlocked prior to this instruction
62434** then a read lock is acquired as part of this instruction.  A read
62435** lock allows other processes to read the database but prohibits
62436** any other process from modifying the database.  The read lock is
62437** released when all cursors are closed.  If this instruction attempts
62438** to get a read lock but fails, the script terminates with an
62439** SQLITE_BUSY error code.
62440**
62441** The P4 value may be either an integer (P4_INT32) or a pointer to
62442** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
62443** structure, then said structure defines the content and collating
62444** sequence of the index being opened. Otherwise, if P4 is an integer
62445** value, it is set to the number of columns in the table.
62446**
62447** See also OpenWrite.
62448*/
62449/* Opcode: OpenWrite P1 P2 P3 P4 P5
62450**
62451** Open a read/write cursor named P1 on the table or index whose root
62452** page is P2.  Or if P5!=0 use the content of register P2 to find the
62453** root page.
62454**
62455** The P4 value may be either an integer (P4_INT32) or a pointer to
62456** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
62457** structure, then said structure defines the content and collating
62458** sequence of the index being opened. Otherwise, if P4 is an integer
62459** value, it is set to the number of columns in the table, or to the
62460** largest index of any column of the table that is actually used.
62461**
62462** This instruction works just like OpenRead except that it opens the cursor
62463** in read/write mode.  For a given table, there can be one or more read-only
62464** cursors or a single read/write cursor but not both.
62465**
62466** See also OpenRead.
62467*/
62468case OP_OpenRead:
62469case OP_OpenWrite: {
62470#if 0  /* local variables moved into u.aw */
62471  int nField;
62472  KeyInfo *pKeyInfo;
62473  int p2;
62474  int iDb;
62475  int wrFlag;
62476  Btree *pX;
62477  VdbeCursor *pCur;
62478  Db *pDb;
62479#endif /* local variables moved into u.aw */
62480
62481  if( p->expired ){
62482    rc = SQLITE_ABORT;
62483    break;
62484  }
62485
62486  u.aw.nField = 0;
62487  u.aw.pKeyInfo = 0;
62488  u.aw.p2 = pOp->p2;
62489  u.aw.iDb = pOp->p3;
62490  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
62491  assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
62492  u.aw.pDb = &db->aDb[u.aw.iDb];
62493  u.aw.pX = u.aw.pDb->pBt;
62494  assert( u.aw.pX!=0 );
62495  if( pOp->opcode==OP_OpenWrite ){
62496    u.aw.wrFlag = 1;
62497    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
62498      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
62499    }
62500  }else{
62501    u.aw.wrFlag = 0;
62502  }
62503  if( pOp->p5 ){
62504    assert( u.aw.p2>0 );
62505    assert( u.aw.p2<=p->nMem );
62506    pIn2 = &aMem[u.aw.p2];
62507    sqlite3VdbeMemIntegerify(pIn2);
62508    u.aw.p2 = (int)pIn2->u.i;
62509    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
62510    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
62511    ** If there were a failure, the prepared statement would have halted
62512    ** before reaching this instruction. */
62513    if( NEVER(u.aw.p2<2) ) {
62514      rc = SQLITE_CORRUPT_BKPT;
62515      goto abort_due_to_error;
62516    }
62517  }
62518  if( pOp->p4type==P4_KEYINFO ){
62519    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
62520    u.aw.pKeyInfo->enc = ENC(p->db);
62521    u.aw.nField = u.aw.pKeyInfo->nField+1;
62522  }else if( pOp->p4type==P4_INT32 ){
62523    u.aw.nField = pOp->p4.i;
62524  }
62525  assert( pOp->p1>=0 );
62526  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
62527  if( u.aw.pCur==0 ) goto no_mem;
62528  u.aw.pCur->nullRow = 1;
62529  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
62530  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
62531
62532  /* Since it performs no memory allocation or IO, the only values that
62533  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
62534  ** SQLITE_EMPTY is only returned when attempting to open the table
62535  ** rooted at page 1 of a zero-byte database.  */
62536  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
62537  if( rc==SQLITE_EMPTY ){
62538    u.aw.pCur->pCursor = 0;
62539    rc = SQLITE_OK;
62540  }
62541
62542  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
62543  ** SQLite used to check if the root-page flags were sane at this point
62544  ** and report database corruption if they were not, but this check has
62545  ** since moved into the btree layer.  */
62546  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
62547  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
62548  break;
62549}
62550
62551/* Opcode: OpenEphemeral P1 P2 * P4 *
62552**
62553** Open a new cursor P1 to a transient table.
62554** The cursor is always opened read/write even if
62555** the main database is read-only.  The ephemeral
62556** table is deleted automatically when the cursor is closed.
62557**
62558** P2 is the number of columns in the ephemeral table.
62559** The cursor points to a BTree table if P4==0 and to a BTree index
62560** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
62561** that defines the format of keys in the index.
62562**
62563** This opcode was once called OpenTemp.  But that created
62564** confusion because the term "temp table", might refer either
62565** to a TEMP table at the SQL level, or to a table opened by
62566** this opcode.  Then this opcode was call OpenVirtual.  But
62567** that created confusion with the whole virtual-table idea.
62568*/
62569/* Opcode: OpenAutoindex P1 P2 * P4 *
62570**
62571** This opcode works the same as OP_OpenEphemeral.  It has a
62572** different name to distinguish its use.  Tables created using
62573** by this opcode will be used for automatically created transient
62574** indices in joins.
62575*/
62576case OP_OpenAutoindex:
62577case OP_OpenEphemeral: {
62578#if 0  /* local variables moved into u.ax */
62579  VdbeCursor *pCx;
62580#endif /* local variables moved into u.ax */
62581  static const int openFlags =
62582      SQLITE_OPEN_READWRITE |
62583      SQLITE_OPEN_CREATE |
62584      SQLITE_OPEN_EXCLUSIVE |
62585      SQLITE_OPEN_DELETEONCLOSE |
62586      SQLITE_OPEN_TRANSIENT_DB;
62587
62588  assert( pOp->p1>=0 );
62589  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
62590  if( u.ax.pCx==0 ) goto no_mem;
62591  u.ax.pCx->nullRow = 1;
62592  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
62593                           &u.ax.pCx->pBt);
62594  if( rc==SQLITE_OK ){
62595    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
62596  }
62597  if( rc==SQLITE_OK ){
62598    /* If a transient index is required, create it by calling
62599    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
62600    ** opening it. If a transient table is required, just use the
62601    ** automatically created table with root-page 1 (an INTKEY table).
62602    */
62603    if( pOp->p4.pKeyInfo ){
62604      int pgno;
62605      assert( pOp->p4type==P4_KEYINFO );
62606      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
62607      if( rc==SQLITE_OK ){
62608        assert( pgno==MASTER_ROOT+1 );
62609        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
62610                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
62611        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
62612        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
62613      }
62614      u.ax.pCx->isTable = 0;
62615    }else{
62616      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
62617      u.ax.pCx->isTable = 1;
62618    }
62619  }
62620  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
62621  break;
62622}
62623
62624/* Opcode: OpenPseudo P1 P2 P3 * *
62625**
62626** Open a new cursor that points to a fake table that contains a single
62627** row of data.  The content of that one row in the content of memory
62628** register P2.  In other words, cursor P1 becomes an alias for the
62629** MEM_Blob content contained in register P2.
62630**
62631** A pseudo-table created by this opcode is used to hold a single
62632** row output from the sorter so that the row can be decomposed into
62633** individual columns using the OP_Column opcode.  The OP_Column opcode
62634** is the only cursor opcode that works with a pseudo-table.
62635**
62636** P3 is the number of fields in the records that will be stored by
62637** the pseudo-table.
62638*/
62639case OP_OpenPseudo: {
62640#if 0  /* local variables moved into u.ay */
62641  VdbeCursor *pCx;
62642#endif /* local variables moved into u.ay */
62643
62644  assert( pOp->p1>=0 );
62645  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
62646  if( u.ay.pCx==0 ) goto no_mem;
62647  u.ay.pCx->nullRow = 1;
62648  u.ay.pCx->pseudoTableReg = pOp->p2;
62649  u.ay.pCx->isTable = 1;
62650  u.ay.pCx->isIndex = 0;
62651  break;
62652}
62653
62654/* Opcode: Close P1 * * * *
62655**
62656** Close a cursor previously opened as P1.  If P1 is not
62657** currently open, this instruction is a no-op.
62658*/
62659case OP_Close: {
62660  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62661  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
62662  p->apCsr[pOp->p1] = 0;
62663  break;
62664}
62665
62666/* Opcode: SeekGe P1 P2 P3 P4 *
62667**
62668** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
62669** use the value in register P3 as the key.  If cursor P1 refers
62670** to an SQL index, then P3 is the first in an array of P4 registers
62671** that are used as an unpacked index key.
62672**
62673** Reposition cursor P1 so that  it points to the smallest entry that
62674** is greater than or equal to the key value. If there are no records
62675** greater than or equal to the key and P2 is not zero, then jump to P2.
62676**
62677** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
62678*/
62679/* Opcode: SeekGt P1 P2 P3 P4 *
62680**
62681** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
62682** use the value in register P3 as a key. If cursor P1 refers
62683** to an SQL index, then P3 is the first in an array of P4 registers
62684** that are used as an unpacked index key.
62685**
62686** Reposition cursor P1 so that  it points to the smallest entry that
62687** is greater than the key value. If there are no records greater than
62688** the key and P2 is not zero, then jump to P2.
62689**
62690** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
62691*/
62692/* Opcode: SeekLt P1 P2 P3 P4 *
62693**
62694** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
62695** use the value in register P3 as a key. If cursor P1 refers
62696** to an SQL index, then P3 is the first in an array of P4 registers
62697** that are used as an unpacked index key.
62698**
62699** Reposition cursor P1 so that  it points to the largest entry that
62700** is less than the key value. If there are no records less than
62701** the key and P2 is not zero, then jump to P2.
62702**
62703** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
62704*/
62705/* Opcode: SeekLe P1 P2 P3 P4 *
62706**
62707** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
62708** use the value in register P3 as a key. If cursor P1 refers
62709** to an SQL index, then P3 is the first in an array of P4 registers
62710** that are used as an unpacked index key.
62711**
62712** Reposition cursor P1 so that it points to the largest entry that
62713** is less than or equal to the key value. If there are no records
62714** less than or equal to the key and P2 is not zero, then jump to P2.
62715**
62716** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
62717*/
62718case OP_SeekLt:         /* jump, in3 */
62719case OP_SeekLe:         /* jump, in3 */
62720case OP_SeekGe:         /* jump, in3 */
62721case OP_SeekGt: {       /* jump, in3 */
62722#if 0  /* local variables moved into u.az */
62723  int res;
62724  int oc;
62725  VdbeCursor *pC;
62726  UnpackedRecord r;
62727  int nField;
62728  i64 iKey;      /* The rowid we are to seek to */
62729#endif /* local variables moved into u.az */
62730
62731  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62732  assert( pOp->p2!=0 );
62733  u.az.pC = p->apCsr[pOp->p1];
62734  assert( u.az.pC!=0 );
62735  assert( u.az.pC->pseudoTableReg==0 );
62736  assert( OP_SeekLe == OP_SeekLt+1 );
62737  assert( OP_SeekGe == OP_SeekLt+2 );
62738  assert( OP_SeekGt == OP_SeekLt+3 );
62739  if( u.az.pC->pCursor!=0 ){
62740    u.az.oc = pOp->opcode;
62741    u.az.pC->nullRow = 0;
62742    if( u.az.pC->isTable ){
62743      /* The input value in P3 might be of any type: integer, real, string,
62744      ** blob, or NULL.  But it needs to be an integer before we can do
62745      ** the seek, so covert it. */
62746      pIn3 = &aMem[pOp->p3];
62747      applyNumericAffinity(pIn3);
62748      u.az.iKey = sqlite3VdbeIntValue(pIn3);
62749      u.az.pC->rowidIsValid = 0;
62750
62751      /* If the P3 value could not be converted into an integer without
62752      ** loss of information, then special processing is required... */
62753      if( (pIn3->flags & MEM_Int)==0 ){
62754        if( (pIn3->flags & MEM_Real)==0 ){
62755          /* If the P3 value cannot be converted into any kind of a number,
62756          ** then the seek is not possible, so jump to P2 */
62757          pc = pOp->p2 - 1;
62758          break;
62759        }
62760        /* If we reach this point, then the P3 value must be a floating
62761        ** point number. */
62762        assert( (pIn3->flags & MEM_Real)!=0 );
62763
62764        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
62765          /* The P3 value is too large in magnitude to be expressed as an
62766          ** integer. */
62767          u.az.res = 1;
62768          if( pIn3->r<0 ){
62769            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
62770              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
62771              if( rc!=SQLITE_OK ) goto abort_due_to_error;
62772            }
62773          }else{
62774            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
62775              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
62776              if( rc!=SQLITE_OK ) goto abort_due_to_error;
62777            }
62778          }
62779          if( u.az.res ){
62780            pc = pOp->p2 - 1;
62781          }
62782          break;
62783        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
62784          /* Use the ceiling() function to convert real->int */
62785          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
62786        }else{
62787          /* Use the floor() function to convert real->int */
62788          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
62789          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
62790        }
62791      }
62792      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
62793      if( rc!=SQLITE_OK ){
62794        goto abort_due_to_error;
62795      }
62796      if( u.az.res==0 ){
62797        u.az.pC->rowidIsValid = 1;
62798        u.az.pC->lastRowid = u.az.iKey;
62799      }
62800    }else{
62801      u.az.nField = pOp->p4.i;
62802      assert( pOp->p4type==P4_INT32 );
62803      assert( u.az.nField>0 );
62804      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
62805      u.az.r.nField = (u16)u.az.nField;
62806
62807      /* The next line of code computes as follows, only faster:
62808      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
62809      **     u.az.r.flags = UNPACKED_INCRKEY;
62810      **   }else{
62811      **     u.az.r.flags = 0;
62812      **   }
62813      */
62814      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
62815      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
62816      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
62817      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
62818      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
62819
62820      u.az.r.aMem = &aMem[pOp->p3];
62821      ExpandBlob(u.az.r.aMem);
62822      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
62823      if( rc!=SQLITE_OK ){
62824        goto abort_due_to_error;
62825      }
62826      u.az.pC->rowidIsValid = 0;
62827    }
62828    u.az.pC->deferredMoveto = 0;
62829    u.az.pC->cacheStatus = CACHE_STALE;
62830#ifdef SQLITE_TEST
62831    sqlite3_search_count++;
62832#endif
62833    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
62834      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
62835        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
62836        if( rc!=SQLITE_OK ) goto abort_due_to_error;
62837        u.az.pC->rowidIsValid = 0;
62838      }else{
62839        u.az.res = 0;
62840      }
62841    }else{
62842      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
62843      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
62844        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
62845        if( rc!=SQLITE_OK ) goto abort_due_to_error;
62846        u.az.pC->rowidIsValid = 0;
62847      }else{
62848        /* u.az.res might be negative because the table is empty.  Check to
62849        ** see if this is the case.
62850        */
62851        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
62852      }
62853    }
62854    assert( pOp->p2>0 );
62855    if( u.az.res ){
62856      pc = pOp->p2 - 1;
62857    }
62858  }else{
62859    /* This happens when attempting to open the sqlite3_master table
62860    ** for read access returns SQLITE_EMPTY. In this case always
62861    ** take the jump (since there are no records in the table).
62862    */
62863    pc = pOp->p2 - 1;
62864  }
62865  break;
62866}
62867
62868/* Opcode: Seek P1 P2 * * *
62869**
62870** P1 is an open table cursor and P2 is a rowid integer.  Arrange
62871** for P1 to move so that it points to the rowid given by P2.
62872**
62873** This is actually a deferred seek.  Nothing actually happens until
62874** the cursor is used to read a record.  That way, if no reads
62875** occur, no unnecessary I/O happens.
62876*/
62877case OP_Seek: {    /* in2 */
62878#if 0  /* local variables moved into u.ba */
62879  VdbeCursor *pC;
62880#endif /* local variables moved into u.ba */
62881
62882  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62883  u.ba.pC = p->apCsr[pOp->p1];
62884  assert( u.ba.pC!=0 );
62885  if( ALWAYS(u.ba.pC->pCursor!=0) ){
62886    assert( u.ba.pC->isTable );
62887    u.ba.pC->nullRow = 0;
62888    pIn2 = &aMem[pOp->p2];
62889    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
62890    u.ba.pC->rowidIsValid = 0;
62891    u.ba.pC->deferredMoveto = 1;
62892  }
62893  break;
62894}
62895
62896
62897/* Opcode: Found P1 P2 P3 P4 *
62898**
62899** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
62900** P4>0 then register P3 is the first of P4 registers that form an unpacked
62901** record.
62902**
62903** Cursor P1 is on an index btree.  If the record identified by P3 and P4
62904** is a prefix of any entry in P1 then a jump is made to P2 and
62905** P1 is left pointing at the matching entry.
62906*/
62907/* Opcode: NotFound P1 P2 P3 P4 *
62908**
62909** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
62910** P4>0 then register P3 is the first of P4 registers that form an unpacked
62911** record.
62912**
62913** Cursor P1 is on an index btree.  If the record identified by P3 and P4
62914** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
62915** does contain an entry whose prefix matches the P3/P4 record then control
62916** falls through to the next instruction and P1 is left pointing at the
62917** matching entry.
62918**
62919** See also: Found, NotExists, IsUnique
62920*/
62921case OP_NotFound:       /* jump, in3 */
62922case OP_Found: {        /* jump, in3 */
62923#if 0  /* local variables moved into u.bb */
62924  int alreadyExists;
62925  VdbeCursor *pC;
62926  int res;
62927  UnpackedRecord *pIdxKey;
62928  UnpackedRecord r;
62929  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
62930#endif /* local variables moved into u.bb */
62931
62932#ifdef SQLITE_TEST
62933  sqlite3_found_count++;
62934#endif
62935
62936  u.bb.alreadyExists = 0;
62937  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
62938  assert( pOp->p4type==P4_INT32 );
62939  u.bb.pC = p->apCsr[pOp->p1];
62940  assert( u.bb.pC!=0 );
62941  pIn3 = &aMem[pOp->p3];
62942  if( ALWAYS(u.bb.pC->pCursor!=0) ){
62943
62944    assert( u.bb.pC->isTable==0 );
62945    if( pOp->p4.i>0 ){
62946      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
62947      u.bb.r.nField = (u16)pOp->p4.i;
62948      u.bb.r.aMem = pIn3;
62949      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
62950      u.bb.pIdxKey = &u.bb.r;
62951    }else{
62952      assert( pIn3->flags & MEM_Blob );
62953      ExpandBlob(pIn3);
62954      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
62955                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
62956      if( u.bb.pIdxKey==0 ){
62957        goto no_mem;
62958      }
62959      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
62960    }
62961    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
62962    if( pOp->p4.i==0 ){
62963      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
62964    }
62965    if( rc!=SQLITE_OK ){
62966      break;
62967    }
62968    u.bb.alreadyExists = (u.bb.res==0);
62969    u.bb.pC->deferredMoveto = 0;
62970    u.bb.pC->cacheStatus = CACHE_STALE;
62971  }
62972  if( pOp->opcode==OP_Found ){
62973    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
62974  }else{
62975    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
62976  }
62977  break;
62978}
62979
62980/* Opcode: IsUnique P1 P2 P3 P4 *
62981**
62982** Cursor P1 is open on an index b-tree - that is to say, a btree which
62983** no data and where the key are records generated by OP_MakeRecord with
62984** the list field being the integer ROWID of the entry that the index
62985** entry refers to.
62986**
62987** The P3 register contains an integer record number. Call this record
62988** number R. Register P4 is the first in a set of N contiguous registers
62989** that make up an unpacked index key that can be used with cursor P1.
62990** The value of N can be inferred from the cursor. N includes the rowid
62991** value appended to the end of the index record. This rowid value may
62992** or may not be the same as R.
62993**
62994** If any of the N registers beginning with register P4 contains a NULL
62995** value, jump immediately to P2.
62996**
62997** Otherwise, this instruction checks if cursor P1 contains an entry
62998** where the first (N-1) fields match but the rowid value at the end
62999** of the index entry is not R. If there is no such entry, control jumps
63000** to instruction P2. Otherwise, the rowid of the conflicting index
63001** entry is copied to register P3 and control falls through to the next
63002** instruction.
63003**
63004** See also: NotFound, NotExists, Found
63005*/
63006case OP_IsUnique: {        /* jump, in3 */
63007#if 0  /* local variables moved into u.bc */
63008  u16 ii;
63009  VdbeCursor *pCx;
63010  BtCursor *pCrsr;
63011  u16 nField;
63012  Mem *aMx;
63013  UnpackedRecord r;                  /* B-Tree index search key */
63014  i64 R;                             /* Rowid stored in register P3 */
63015#endif /* local variables moved into u.bc */
63016
63017  pIn3 = &aMem[pOp->p3];
63018  u.bc.aMx = &aMem[pOp->p4.i];
63019  /* Assert that the values of parameters P1 and P4 are in range. */
63020  assert( pOp->p4type==P4_INT32 );
63021  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
63022  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63023
63024  /* Find the index cursor. */
63025  u.bc.pCx = p->apCsr[pOp->p1];
63026  assert( u.bc.pCx->deferredMoveto==0 );
63027  u.bc.pCx->seekResult = 0;
63028  u.bc.pCx->cacheStatus = CACHE_STALE;
63029  u.bc.pCrsr = u.bc.pCx->pCursor;
63030
63031  /* If any of the values are NULL, take the jump. */
63032  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
63033  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
63034    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
63035      pc = pOp->p2 - 1;
63036      u.bc.pCrsr = 0;
63037      break;
63038    }
63039  }
63040  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
63041
63042  if( u.bc.pCrsr!=0 ){
63043    /* Populate the index search key. */
63044    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
63045    u.bc.r.nField = u.bc.nField + 1;
63046    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
63047    u.bc.r.aMem = u.bc.aMx;
63048
63049    /* Extract the value of u.bc.R from register P3. */
63050    sqlite3VdbeMemIntegerify(pIn3);
63051    u.bc.R = pIn3->u.i;
63052
63053    /* Search the B-Tree index. If no conflicting record is found, jump
63054    ** to P2. Otherwise, copy the rowid of the conflicting record to
63055    ** register P3 and fall through to the next instruction.  */
63056    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
63057    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
63058      pc = pOp->p2 - 1;
63059    }else{
63060      pIn3->u.i = u.bc.r.rowid;
63061    }
63062  }
63063  break;
63064}
63065
63066/* Opcode: NotExists P1 P2 P3 * *
63067**
63068** Use the content of register P3 as a integer key.  If a record
63069** with that key does not exist in table of P1, then jump to P2.
63070** If the record does exist, then fall thru.  The cursor is left
63071** pointing to the record if it exists.
63072**
63073** The difference between this operation and NotFound is that this
63074** operation assumes the key is an integer and that P1 is a table whereas
63075** NotFound assumes key is a blob constructed from MakeRecord and
63076** P1 is an index.
63077**
63078** See also: Found, NotFound, IsUnique
63079*/
63080case OP_NotExists: {        /* jump, in3 */
63081#if 0  /* local variables moved into u.bd */
63082  VdbeCursor *pC;
63083  BtCursor *pCrsr;
63084  int res;
63085  u64 iKey;
63086#endif /* local variables moved into u.bd */
63087
63088  pIn3 = &aMem[pOp->p3];
63089  assert( pIn3->flags & MEM_Int );
63090  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63091  u.bd.pC = p->apCsr[pOp->p1];
63092  assert( u.bd.pC!=0 );
63093  assert( u.bd.pC->isTable );
63094  assert( u.bd.pC->pseudoTableReg==0 );
63095  u.bd.pCrsr = u.bd.pC->pCursor;
63096  if( u.bd.pCrsr!=0 ){
63097    u.bd.res = 0;
63098    u.bd.iKey = pIn3->u.i;
63099    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
63100    u.bd.pC->lastRowid = pIn3->u.i;
63101    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
63102    u.bd.pC->nullRow = 0;
63103    u.bd.pC->cacheStatus = CACHE_STALE;
63104    u.bd.pC->deferredMoveto = 0;
63105    if( u.bd.res!=0 ){
63106      pc = pOp->p2 - 1;
63107      assert( u.bd.pC->rowidIsValid==0 );
63108    }
63109    u.bd.pC->seekResult = u.bd.res;
63110  }else{
63111    /* This happens when an attempt to open a read cursor on the
63112    ** sqlite_master table returns SQLITE_EMPTY.
63113    */
63114    pc = pOp->p2 - 1;
63115    assert( u.bd.pC->rowidIsValid==0 );
63116    u.bd.pC->seekResult = 0;
63117  }
63118  break;
63119}
63120
63121/* Opcode: Sequence P1 P2 * * *
63122**
63123** Find the next available sequence number for cursor P1.
63124** Write the sequence number into register P2.
63125** The sequence number on the cursor is incremented after this
63126** instruction.
63127*/
63128case OP_Sequence: {           /* out2-prerelease */
63129  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63130  assert( p->apCsr[pOp->p1]!=0 );
63131  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
63132  break;
63133}
63134
63135
63136/* Opcode: NewRowid P1 P2 P3 * *
63137**
63138** Get a new integer record number (a.k.a "rowid") used as the key to a table.
63139** The record number is not previously used as a key in the database
63140** table that cursor P1 points to.  The new record number is written
63141** written to register P2.
63142**
63143** If P3>0 then P3 is a register in the root frame of this VDBE that holds
63144** the largest previously generated record number. No new record numbers are
63145** allowed to be less than this value. When this value reaches its maximum,
63146** a SQLITE_FULL error is generated. The P3 register is updated with the '
63147** generated record number. This P3 mechanism is used to help implement the
63148** AUTOINCREMENT feature.
63149*/
63150case OP_NewRowid: {           /* out2-prerelease */
63151#if 0  /* local variables moved into u.be */
63152  i64 v;                 /* The new rowid */
63153  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
63154  int res;               /* Result of an sqlite3BtreeLast() */
63155  int cnt;               /* Counter to limit the number of searches */
63156  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
63157  VdbeFrame *pFrame;     /* Root frame of VDBE */
63158#endif /* local variables moved into u.be */
63159
63160  u.be.v = 0;
63161  u.be.res = 0;
63162  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63163  u.be.pC = p->apCsr[pOp->p1];
63164  assert( u.be.pC!=0 );
63165  if( NEVER(u.be.pC->pCursor==0) ){
63166    /* The zero initialization above is all that is needed */
63167  }else{
63168    /* The next rowid or record number (different terms for the same
63169    ** thing) is obtained in a two-step algorithm.
63170    **
63171    ** First we attempt to find the largest existing rowid and add one
63172    ** to that.  But if the largest existing rowid is already the maximum
63173    ** positive integer, we have to fall through to the second
63174    ** probabilistic algorithm
63175    **
63176    ** The second algorithm is to select a rowid at random and see if
63177    ** it already exists in the table.  If it does not exist, we have
63178    ** succeeded.  If the random rowid does exist, we select a new one
63179    ** and try again, up to 100 times.
63180    */
63181    assert( u.be.pC->isTable );
63182    u.be.cnt = 0;
63183
63184#ifdef SQLITE_32BIT_ROWID
63185#   define MAX_ROWID 0x7fffffff
63186#else
63187    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
63188    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
63189    ** to provide the constant while making all compilers happy.
63190    */
63191#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
63192#endif
63193
63194    if( !u.be.pC->useRandomRowid ){
63195      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
63196      if( u.be.v==0 ){
63197        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
63198        if( rc!=SQLITE_OK ){
63199          goto abort_due_to_error;
63200        }
63201        if( u.be.res ){
63202          u.be.v = 1;   /* IMP: R-61914-48074 */
63203        }else{
63204          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
63205          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
63206          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
63207          if( u.be.v==MAX_ROWID ){
63208            u.be.pC->useRandomRowid = 1;
63209          }else{
63210            u.be.v++;   /* IMP: R-29538-34987 */
63211          }
63212        }
63213      }
63214
63215#ifndef SQLITE_OMIT_AUTOINCREMENT
63216      if( pOp->p3 ){
63217        /* Assert that P3 is a valid memory cell. */
63218        assert( pOp->p3>0 );
63219        if( p->pFrame ){
63220          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
63221          /* Assert that P3 is a valid memory cell. */
63222          assert( pOp->p3<=u.be.pFrame->nMem );
63223          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
63224        }else{
63225          /* Assert that P3 is a valid memory cell. */
63226          assert( pOp->p3<=p->nMem );
63227          u.be.pMem = &aMem[pOp->p3];
63228        }
63229
63230        REGISTER_TRACE(pOp->p3, u.be.pMem);
63231        sqlite3VdbeMemIntegerify(u.be.pMem);
63232        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
63233        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
63234          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
63235          goto abort_due_to_error;
63236        }
63237        if( u.be.v<u.be.pMem->u.i+1 ){
63238          u.be.v = u.be.pMem->u.i + 1;
63239        }
63240        u.be.pMem->u.i = u.be.v;
63241      }
63242#endif
63243
63244      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
63245    }
63246    if( u.be.pC->useRandomRowid ){
63247      /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
63248      ** largest possible integer (9223372036854775807) then the database
63249      ** engine starts picking candidate ROWIDs at random until it finds one
63250      ** that is not previously used.
63251      */
63252      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
63253                             ** an AUTOINCREMENT table. */
63254      u.be.v = db->lastRowid;
63255      u.be.cnt = 0;
63256      do{
63257        if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
63258          u.be.v++;
63259        }else{
63260          sqlite3_randomness(sizeof(u.be.v), &u.be.v);
63261          if( u.be.cnt<5 ) u.be.v &= 0xffffff;
63262        }
63263        rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
63264        u.be.cnt++;
63265      }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
63266      if( rc==SQLITE_OK && u.be.res==0 ){
63267        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
63268        goto abort_due_to_error;
63269      }
63270    }
63271    u.be.pC->rowidIsValid = 0;
63272    u.be.pC->deferredMoveto = 0;
63273    u.be.pC->cacheStatus = CACHE_STALE;
63274  }
63275  pOut->u.i = u.be.v;
63276  break;
63277}
63278
63279/* Opcode: Insert P1 P2 P3 P4 P5
63280**
63281** Write an entry into the table of cursor P1.  A new entry is
63282** created if it doesn't already exist or the data for an existing
63283** entry is overwritten.  The data is the value MEM_Blob stored in register
63284** number P2. The key is stored in register P3. The key must
63285** be a MEM_Int.
63286**
63287** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
63288** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
63289** then rowid is stored for subsequent return by the
63290** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
63291**
63292** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
63293** the last seek operation (OP_NotExists) was a success, then this
63294** operation will not attempt to find the appropriate row before doing
63295** the insert but will instead overwrite the row that the cursor is
63296** currently pointing to.  Presumably, the prior OP_NotExists opcode
63297** has already positioned the cursor correctly.  This is an optimization
63298** that boosts performance by avoiding redundant seeks.
63299**
63300** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
63301** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
63302** is part of an INSERT operation.  The difference is only important to
63303** the update hook.
63304**
63305** Parameter P4 may point to a string containing the table-name, or
63306** may be NULL. If it is not NULL, then the update-hook
63307** (sqlite3.xUpdateCallback) is invoked following a successful insert.
63308**
63309** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
63310** allocated, then ownership of P2 is transferred to the pseudo-cursor
63311** and register P2 becomes ephemeral.  If the cursor is changed, the
63312** value of register P2 will then change.  Make sure this does not
63313** cause any problems.)
63314**
63315** This instruction only works on tables.  The equivalent instruction
63316** for indices is OP_IdxInsert.
63317*/
63318/* Opcode: InsertInt P1 P2 P3 P4 P5
63319**
63320** This works exactly like OP_Insert except that the key is the
63321** integer value P3, not the value of the integer stored in register P3.
63322*/
63323case OP_Insert:
63324case OP_InsertInt: {
63325#if 0  /* local variables moved into u.bf */
63326  Mem *pData;       /* MEM cell holding data for the record to be inserted */
63327  Mem *pKey;        /* MEM cell holding key  for the record */
63328  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
63329  VdbeCursor *pC;   /* Cursor to table into which insert is written */
63330  int nZero;        /* Number of zero-bytes to append */
63331  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
63332  const char *zDb;  /* database name - used by the update hook */
63333  const char *zTbl; /* Table name - used by the opdate hook */
63334  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63335#endif /* local variables moved into u.bf */
63336
63337  u.bf.pData = &aMem[pOp->p2];
63338  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63339  u.bf.pC = p->apCsr[pOp->p1];
63340  assert( u.bf.pC!=0 );
63341  assert( u.bf.pC->pCursor!=0 );
63342  assert( u.bf.pC->pseudoTableReg==0 );
63343  assert( u.bf.pC->isTable );
63344  REGISTER_TRACE(pOp->p2, u.bf.pData);
63345
63346  if( pOp->opcode==OP_Insert ){
63347    u.bf.pKey = &aMem[pOp->p3];
63348    assert( u.bf.pKey->flags & MEM_Int );
63349    REGISTER_TRACE(pOp->p3, u.bf.pKey);
63350    u.bf.iKey = u.bf.pKey->u.i;
63351  }else{
63352    assert( pOp->opcode==OP_InsertInt );
63353    u.bf.iKey = pOp->p3;
63354  }
63355
63356  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
63357  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
63358  if( u.bf.pData->flags & MEM_Null ){
63359    u.bf.pData->z = 0;
63360    u.bf.pData->n = 0;
63361  }else{
63362    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
63363  }
63364  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
63365  if( u.bf.pData->flags & MEM_Zero ){
63366    u.bf.nZero = u.bf.pData->u.nZero;
63367  }else{
63368    u.bf.nZero = 0;
63369  }
63370  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
63371  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
63372                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
63373                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
63374  );
63375  u.bf.pC->rowidIsValid = 0;
63376  u.bf.pC->deferredMoveto = 0;
63377  u.bf.pC->cacheStatus = CACHE_STALE;
63378
63379  /* Invoke the update-hook if required. */
63380  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
63381    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
63382    u.bf.zTbl = pOp->p4.z;
63383    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
63384    assert( u.bf.pC->isTable );
63385    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
63386    assert( u.bf.pC->iDb>=0 );
63387  }
63388  break;
63389}
63390
63391/* Opcode: Delete P1 P2 * P4 *
63392**
63393** Delete the record at which the P1 cursor is currently pointing.
63394**
63395** The cursor will be left pointing at either the next or the previous
63396** record in the table. If it is left pointing at the next record, then
63397** the next Next instruction will be a no-op.  Hence it is OK to delete
63398** a record from within an Next loop.
63399**
63400** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
63401** incremented (otherwise not).
63402**
63403** P1 must not be pseudo-table.  It has to be a real table with
63404** multiple rows.
63405**
63406** If P4 is not NULL, then it is the name of the table that P1 is
63407** pointing to.  The update hook will be invoked, if it exists.
63408** If P4 is not NULL then the P1 cursor must have been positioned
63409** using OP_NotFound prior to invoking this opcode.
63410*/
63411case OP_Delete: {
63412#if 0  /* local variables moved into u.bg */
63413  i64 iKey;
63414  VdbeCursor *pC;
63415#endif /* local variables moved into u.bg */
63416
63417  u.bg.iKey = 0;
63418  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63419  u.bg.pC = p->apCsr[pOp->p1];
63420  assert( u.bg.pC!=0 );
63421  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
63422
63423  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
63424  ** row being deleted.
63425  */
63426  if( db->xUpdateCallback && pOp->p4.z ){
63427    assert( u.bg.pC->isTable );
63428    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
63429    u.bg.iKey = u.bg.pC->lastRowid;
63430  }
63431
63432  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
63433  ** OP_Column on the same table without any intervening operations that
63434  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
63435  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
63436  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
63437  ** to guard against future changes to the code generator.
63438  **/
63439  assert( u.bg.pC->deferredMoveto==0 );
63440  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
63441  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
63442
63443  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
63444  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
63445  u.bg.pC->cacheStatus = CACHE_STALE;
63446
63447  /* Invoke the update-hook if required. */
63448  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
63449    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
63450    const char *zTbl = pOp->p4.z;
63451    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
63452    assert( u.bg.pC->iDb>=0 );
63453  }
63454  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
63455  break;
63456}
63457/* Opcode: ResetCount * * * * *
63458**
63459** The value of the change counter is copied to the database handle
63460** change counter (returned by subsequent calls to sqlite3_changes()).
63461** Then the VMs internal change counter resets to 0.
63462** This is used by trigger programs.
63463*/
63464case OP_ResetCount: {
63465  sqlite3VdbeSetChanges(db, p->nChange);
63466  p->nChange = 0;
63467  break;
63468}
63469
63470/* Opcode: RowData P1 P2 * * *
63471**
63472** Write into register P2 the complete row data for cursor P1.
63473** There is no interpretation of the data.
63474** It is just copied onto the P2 register exactly as
63475** it is found in the database file.
63476**
63477** If the P1 cursor must be pointing to a valid row (not a NULL row)
63478** of a real table, not a pseudo-table.
63479*/
63480/* Opcode: RowKey P1 P2 * * *
63481**
63482** Write into register P2 the complete row key for cursor P1.
63483** There is no interpretation of the data.
63484** The key is copied onto the P3 register exactly as
63485** it is found in the database file.
63486**
63487** If the P1 cursor must be pointing to a valid row (not a NULL row)
63488** of a real table, not a pseudo-table.
63489*/
63490case OP_RowKey:
63491case OP_RowData: {
63492#if 0  /* local variables moved into u.bh */
63493  VdbeCursor *pC;
63494  BtCursor *pCrsr;
63495  u32 n;
63496  i64 n64;
63497#endif /* local variables moved into u.bh */
63498
63499  pOut = &aMem[pOp->p2];
63500
63501  /* Note that RowKey and RowData are really exactly the same instruction */
63502  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63503  u.bh.pC = p->apCsr[pOp->p1];
63504  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
63505  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
63506  assert( u.bh.pC!=0 );
63507  assert( u.bh.pC->nullRow==0 );
63508  assert( u.bh.pC->pseudoTableReg==0 );
63509  assert( u.bh.pC->pCursor!=0 );
63510  u.bh.pCrsr = u.bh.pC->pCursor;
63511  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
63512
63513  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
63514  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
63515  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
63516  ** a no-op and can never fail.  But we leave it in place as a safety.
63517  */
63518  assert( u.bh.pC->deferredMoveto==0 );
63519  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
63520  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
63521
63522  if( u.bh.pC->isIndex ){
63523    assert( !u.bh.pC->isTable );
63524    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
63525    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
63526    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63527      goto too_big;
63528    }
63529    u.bh.n = (u32)u.bh.n64;
63530  }else{
63531    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
63532    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
63533    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
63534      goto too_big;
63535    }
63536  }
63537  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
63538    goto no_mem;
63539  }
63540  pOut->n = u.bh.n;
63541  MemSetTypeFlag(pOut, MEM_Blob);
63542  if( u.bh.pC->isIndex ){
63543    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
63544  }else{
63545    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
63546  }
63547  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
63548  UPDATE_MAX_BLOBSIZE(pOut);
63549  break;
63550}
63551
63552/* Opcode: Rowid P1 P2 * * *
63553**
63554** Store in register P2 an integer which is the key of the table entry that
63555** P1 is currently point to.
63556**
63557** P1 can be either an ordinary table or a virtual table.  There used to
63558** be a separate OP_VRowid opcode for use with virtual tables, but this
63559** one opcode now works for both table types.
63560*/
63561case OP_Rowid: {                 /* out2-prerelease */
63562#if 0  /* local variables moved into u.bi */
63563  VdbeCursor *pC;
63564  i64 v;
63565  sqlite3_vtab *pVtab;
63566  const sqlite3_module *pModule;
63567#endif /* local variables moved into u.bi */
63568
63569  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63570  u.bi.pC = p->apCsr[pOp->p1];
63571  assert( u.bi.pC!=0 );
63572  assert( u.bi.pC->pseudoTableReg==0 );
63573  if( u.bi.pC->nullRow ){
63574    pOut->flags = MEM_Null;
63575    break;
63576  }else if( u.bi.pC->deferredMoveto ){
63577    u.bi.v = u.bi.pC->movetoTarget;
63578#ifndef SQLITE_OMIT_VIRTUALTABLE
63579  }else if( u.bi.pC->pVtabCursor ){
63580    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
63581    u.bi.pModule = u.bi.pVtab->pModule;
63582    assert( u.bi.pModule->xRowid );
63583    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
63584    importVtabErrMsg(p, u.bi.pVtab);
63585#endif /* SQLITE_OMIT_VIRTUALTABLE */
63586  }else{
63587    assert( u.bi.pC->pCursor!=0 );
63588    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
63589    if( rc ) goto abort_due_to_error;
63590    if( u.bi.pC->rowidIsValid ){
63591      u.bi.v = u.bi.pC->lastRowid;
63592    }else{
63593      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
63594      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
63595    }
63596  }
63597  pOut->u.i = u.bi.v;
63598  break;
63599}
63600
63601/* Opcode: NullRow P1 * * * *
63602**
63603** Move the cursor P1 to a null row.  Any OP_Column operations
63604** that occur while the cursor is on the null row will always
63605** write a NULL.
63606*/
63607case OP_NullRow: {
63608#if 0  /* local variables moved into u.bj */
63609  VdbeCursor *pC;
63610#endif /* local variables moved into u.bj */
63611
63612  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63613  u.bj.pC = p->apCsr[pOp->p1];
63614  assert( u.bj.pC!=0 );
63615  u.bj.pC->nullRow = 1;
63616  u.bj.pC->rowidIsValid = 0;
63617  if( u.bj.pC->pCursor ){
63618    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
63619  }
63620  break;
63621}
63622
63623/* Opcode: Last P1 P2 * * *
63624**
63625** The next use of the Rowid or Column or Next instruction for P1
63626** will refer to the last entry in the database table or index.
63627** If the table or index is empty and P2>0, then jump immediately to P2.
63628** If P2 is 0 or if the table or index is not empty, fall through
63629** to the following instruction.
63630*/
63631case OP_Last: {        /* jump */
63632#if 0  /* local variables moved into u.bk */
63633  VdbeCursor *pC;
63634  BtCursor *pCrsr;
63635  int res;
63636#endif /* local variables moved into u.bk */
63637
63638  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63639  u.bk.pC = p->apCsr[pOp->p1];
63640  assert( u.bk.pC!=0 );
63641  u.bk.pCrsr = u.bk.pC->pCursor;
63642  if( u.bk.pCrsr==0 ){
63643    u.bk.res = 1;
63644  }else{
63645    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
63646  }
63647  u.bk.pC->nullRow = (u8)u.bk.res;
63648  u.bk.pC->deferredMoveto = 0;
63649  u.bk.pC->rowidIsValid = 0;
63650  u.bk.pC->cacheStatus = CACHE_STALE;
63651  if( pOp->p2>0 && u.bk.res ){
63652    pc = pOp->p2 - 1;
63653  }
63654  break;
63655}
63656
63657
63658/* Opcode: Sort P1 P2 * * *
63659**
63660** This opcode does exactly the same thing as OP_Rewind except that
63661** it increments an undocumented global variable used for testing.
63662**
63663** Sorting is accomplished by writing records into a sorting index,
63664** then rewinding that index and playing it back from beginning to
63665** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
63666** rewinding so that the global variable will be incremented and
63667** regression tests can determine whether or not the optimizer is
63668** correctly optimizing out sorts.
63669*/
63670case OP_Sort: {        /* jump */
63671#ifdef SQLITE_TEST
63672  sqlite3_sort_count++;
63673  sqlite3_search_count--;
63674#endif
63675  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
63676  /* Fall through into OP_Rewind */
63677}
63678/* Opcode: Rewind P1 P2 * * *
63679**
63680** The next use of the Rowid or Column or Next instruction for P1
63681** will refer to the first entry in the database table or index.
63682** If the table or index is empty and P2>0, then jump immediately to P2.
63683** If P2 is 0 or if the table or index is not empty, fall through
63684** to the following instruction.
63685*/
63686case OP_Rewind: {        /* jump */
63687#if 0  /* local variables moved into u.bl */
63688  VdbeCursor *pC;
63689  BtCursor *pCrsr;
63690  int res;
63691#endif /* local variables moved into u.bl */
63692
63693  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63694  u.bl.pC = p->apCsr[pOp->p1];
63695  assert( u.bl.pC!=0 );
63696  u.bl.res = 1;
63697  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
63698    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
63699    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
63700    u.bl.pC->deferredMoveto = 0;
63701    u.bl.pC->cacheStatus = CACHE_STALE;
63702    u.bl.pC->rowidIsValid = 0;
63703  }
63704  u.bl.pC->nullRow = (u8)u.bl.res;
63705  assert( pOp->p2>0 && pOp->p2<p->nOp );
63706  if( u.bl.res ){
63707    pc = pOp->p2 - 1;
63708  }
63709  break;
63710}
63711
63712/* Opcode: Next P1 P2 * * P5
63713**
63714** Advance cursor P1 so that it points to the next key/data pair in its
63715** table or index.  If there are no more key/value pairs then fall through
63716** to the following instruction.  But if the cursor advance was successful,
63717** jump immediately to P2.
63718**
63719** The P1 cursor must be for a real table, not a pseudo-table.
63720**
63721** If P5 is positive and the jump is taken, then event counter
63722** number P5-1 in the prepared statement is incremented.
63723**
63724** See also: Prev
63725*/
63726/* Opcode: Prev P1 P2 * * P5
63727**
63728** Back up cursor P1 so that it points to the previous key/data pair in its
63729** table or index.  If there is no previous key/value pairs then fall through
63730** to the following instruction.  But if the cursor backup was successful,
63731** jump immediately to P2.
63732**
63733** The P1 cursor must be for a real table, not a pseudo-table.
63734**
63735** If P5 is positive and the jump is taken, then event counter
63736** number P5-1 in the prepared statement is incremented.
63737*/
63738case OP_Prev:          /* jump */
63739case OP_Next: {        /* jump */
63740#if 0  /* local variables moved into u.bm */
63741  VdbeCursor *pC;
63742  BtCursor *pCrsr;
63743  int res;
63744#endif /* local variables moved into u.bm */
63745
63746  CHECK_FOR_INTERRUPT;
63747  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63748  assert( pOp->p5<=ArraySize(p->aCounter) );
63749  u.bm.pC = p->apCsr[pOp->p1];
63750  if( u.bm.pC==0 ){
63751    break;  /* See ticket #2273 */
63752  }
63753  u.bm.pCrsr = u.bm.pC->pCursor;
63754  if( u.bm.pCrsr==0 ){
63755    u.bm.pC->nullRow = 1;
63756    break;
63757  }
63758  u.bm.res = 1;
63759  assert( u.bm.pC->deferredMoveto==0 );
63760  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
63761                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
63762  u.bm.pC->nullRow = (u8)u.bm.res;
63763  u.bm.pC->cacheStatus = CACHE_STALE;
63764  if( u.bm.res==0 ){
63765    pc = pOp->p2 - 1;
63766    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
63767#ifdef SQLITE_TEST
63768    sqlite3_search_count++;
63769#endif
63770  }
63771  u.bm.pC->rowidIsValid = 0;
63772  break;
63773}
63774
63775/* Opcode: IdxInsert P1 P2 P3 * P5
63776**
63777** Register P2 holds a SQL index key made using the
63778** MakeRecord instructions.  This opcode writes that key
63779** into the index P1.  Data for the entry is nil.
63780**
63781** P3 is a flag that provides a hint to the b-tree layer that this
63782** insert is likely to be an append.
63783**
63784** This instruction only works for indices.  The equivalent instruction
63785** for tables is OP_Insert.
63786*/
63787case OP_IdxInsert: {        /* in2 */
63788#if 0  /* local variables moved into u.bn */
63789  VdbeCursor *pC;
63790  BtCursor *pCrsr;
63791  int nKey;
63792  const char *zKey;
63793#endif /* local variables moved into u.bn */
63794
63795  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63796  u.bn.pC = p->apCsr[pOp->p1];
63797  assert( u.bn.pC!=0 );
63798  pIn2 = &aMem[pOp->p2];
63799  assert( pIn2->flags & MEM_Blob );
63800  u.bn.pCrsr = u.bn.pC->pCursor;
63801  if( ALWAYS(u.bn.pCrsr!=0) ){
63802    assert( u.bn.pC->isTable==0 );
63803    rc = ExpandBlob(pIn2);
63804    if( rc==SQLITE_OK ){
63805      u.bn.nKey = pIn2->n;
63806      u.bn.zKey = pIn2->z;
63807      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
63808          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
63809      );
63810      assert( u.bn.pC->deferredMoveto==0 );
63811      u.bn.pC->cacheStatus = CACHE_STALE;
63812    }
63813  }
63814  break;
63815}
63816
63817/* Opcode: IdxDelete P1 P2 P3 * *
63818**
63819** The content of P3 registers starting at register P2 form
63820** an unpacked index key. This opcode removes that entry from the
63821** index opened by cursor P1.
63822*/
63823case OP_IdxDelete: {
63824#if 0  /* local variables moved into u.bo */
63825  VdbeCursor *pC;
63826  BtCursor *pCrsr;
63827  int res;
63828  UnpackedRecord r;
63829#endif /* local variables moved into u.bo */
63830
63831  assert( pOp->p3>0 );
63832  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
63833  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63834  u.bo.pC = p->apCsr[pOp->p1];
63835  assert( u.bo.pC!=0 );
63836  u.bo.pCrsr = u.bo.pC->pCursor;
63837  if( ALWAYS(u.bo.pCrsr!=0) ){
63838    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
63839    u.bo.r.nField = (u16)pOp->p3;
63840    u.bo.r.flags = 0;
63841    u.bo.r.aMem = &aMem[pOp->p2];
63842    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
63843    if( rc==SQLITE_OK && u.bo.res==0 ){
63844      rc = sqlite3BtreeDelete(u.bo.pCrsr);
63845    }
63846    assert( u.bo.pC->deferredMoveto==0 );
63847    u.bo.pC->cacheStatus = CACHE_STALE;
63848  }
63849  break;
63850}
63851
63852/* Opcode: IdxRowid P1 P2 * * *
63853**
63854** Write into register P2 an integer which is the last entry in the record at
63855** the end of the index key pointed to by cursor P1.  This integer should be
63856** the rowid of the table entry to which this index entry points.
63857**
63858** See also: Rowid, MakeRecord.
63859*/
63860case OP_IdxRowid: {              /* out2-prerelease */
63861#if 0  /* local variables moved into u.bp */
63862  BtCursor *pCrsr;
63863  VdbeCursor *pC;
63864  i64 rowid;
63865#endif /* local variables moved into u.bp */
63866
63867  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63868  u.bp.pC = p->apCsr[pOp->p1];
63869  assert( u.bp.pC!=0 );
63870  u.bp.pCrsr = u.bp.pC->pCursor;
63871  pOut->flags = MEM_Null;
63872  if( ALWAYS(u.bp.pCrsr!=0) ){
63873    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
63874    if( NEVER(rc) ) goto abort_due_to_error;
63875    assert( u.bp.pC->deferredMoveto==0 );
63876    assert( u.bp.pC->isTable==0 );
63877    if( !u.bp.pC->nullRow ){
63878      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
63879      if( rc!=SQLITE_OK ){
63880        goto abort_due_to_error;
63881      }
63882      pOut->u.i = u.bp.rowid;
63883      pOut->flags = MEM_Int;
63884    }
63885  }
63886  break;
63887}
63888
63889/* Opcode: IdxGE P1 P2 P3 P4 P5
63890**
63891** The P4 register values beginning with P3 form an unpacked index
63892** key that omits the ROWID.  Compare this key value against the index
63893** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
63894**
63895** If the P1 index entry is greater than or equal to the key value
63896** then jump to P2.  Otherwise fall through to the next instruction.
63897**
63898** If P5 is non-zero then the key value is increased by an epsilon
63899** prior to the comparison.  This make the opcode work like IdxGT except
63900** that if the key from register P3 is a prefix of the key in the cursor,
63901** the result is false whereas it would be true with IdxGT.
63902*/
63903/* Opcode: IdxLT P1 P2 P3 P4 P5
63904**
63905** The P4 register values beginning with P3 form an unpacked index
63906** key that omits the ROWID.  Compare this key value against the index
63907** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
63908**
63909** If the P1 index entry is less than the key value then jump to P2.
63910** Otherwise fall through to the next instruction.
63911**
63912** If P5 is non-zero then the key value is increased by an epsilon prior
63913** to the comparison.  This makes the opcode work like IdxLE.
63914*/
63915case OP_IdxLT:          /* jump */
63916case OP_IdxGE: {        /* jump */
63917#if 0  /* local variables moved into u.bq */
63918  VdbeCursor *pC;
63919  int res;
63920  UnpackedRecord r;
63921#endif /* local variables moved into u.bq */
63922
63923  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63924  u.bq.pC = p->apCsr[pOp->p1];
63925  assert( u.bq.pC!=0 );
63926  if( ALWAYS(u.bq.pC->pCursor!=0) ){
63927    assert( u.bq.pC->deferredMoveto==0 );
63928    assert( pOp->p5==0 || pOp->p5==1 );
63929    assert( pOp->p4type==P4_INT32 );
63930    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
63931    u.bq.r.nField = (u16)pOp->p4.i;
63932    if( pOp->p5 ){
63933      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
63934    }else{
63935      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
63936    }
63937    u.bq.r.aMem = &aMem[pOp->p3];
63938    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
63939    if( pOp->opcode==OP_IdxLT ){
63940      u.bq.res = -u.bq.res;
63941    }else{
63942      assert( pOp->opcode==OP_IdxGE );
63943      u.bq.res++;
63944    }
63945    if( u.bq.res>0 ){
63946      pc = pOp->p2 - 1 ;
63947    }
63948  }
63949  break;
63950}
63951
63952/* Opcode: Destroy P1 P2 P3 * *
63953**
63954** Delete an entire database table or index whose root page in the database
63955** file is given by P1.
63956**
63957** The table being destroyed is in the main database file if P3==0.  If
63958** P3==1 then the table to be clear is in the auxiliary database file
63959** that is used to store tables create using CREATE TEMPORARY TABLE.
63960**
63961** If AUTOVACUUM is enabled then it is possible that another root page
63962** might be moved into the newly deleted root page in order to keep all
63963** root pages contiguous at the beginning of the database.  The former
63964** value of the root page that moved - its value before the move occurred -
63965** is stored in register P2.  If no page
63966** movement was required (because the table being dropped was already
63967** the last one in the database) then a zero is stored in register P2.
63968** If AUTOVACUUM is disabled then a zero is stored in register P2.
63969**
63970** See also: Clear
63971*/
63972case OP_Destroy: {     /* out2-prerelease */
63973#if 0  /* local variables moved into u.br */
63974  int iMoved;
63975  int iCnt;
63976  Vdbe *pVdbe;
63977  int iDb;
63978#endif /* local variables moved into u.br */
63979#ifndef SQLITE_OMIT_VIRTUALTABLE
63980  u.br.iCnt = 0;
63981  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
63982    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
63983      u.br.iCnt++;
63984    }
63985  }
63986#else
63987  u.br.iCnt = db->activeVdbeCnt;
63988#endif
63989  pOut->flags = MEM_Null;
63990  if( u.br.iCnt>1 ){
63991    rc = SQLITE_LOCKED;
63992    p->errorAction = OE_Abort;
63993  }else{
63994    u.br.iDb = pOp->p3;
63995    assert( u.br.iCnt==1 );
63996    assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
63997    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
63998    pOut->flags = MEM_Int;
63999    pOut->u.i = u.br.iMoved;
64000#ifndef SQLITE_OMIT_AUTOVACUUM
64001    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
64002      sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
64003      resetSchemaOnFault = 1;
64004    }
64005#endif
64006  }
64007  break;
64008}
64009
64010/* Opcode: Clear P1 P2 P3
64011**
64012** Delete all contents of the database table or index whose root page
64013** in the database file is given by P1.  But, unlike Destroy, do not
64014** remove the table or index from the database file.
64015**
64016** The table being clear is in the main database file if P2==0.  If
64017** P2==1 then the table to be clear is in the auxiliary database file
64018** that is used to store tables create using CREATE TEMPORARY TABLE.
64019**
64020** If the P3 value is non-zero, then the table referred to must be an
64021** intkey table (an SQL table, not an index). In this case the row change
64022** count is incremented by the number of rows in the table being cleared.
64023** If P3 is greater than zero, then the value stored in register P3 is
64024** also incremented by the number of rows in the table being cleared.
64025**
64026** See also: Destroy
64027*/
64028case OP_Clear: {
64029#if 0  /* local variables moved into u.bs */
64030  int nChange;
64031#endif /* local variables moved into u.bs */
64032
64033  u.bs.nChange = 0;
64034  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
64035  rc = sqlite3BtreeClearTable(
64036      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
64037  );
64038  if( pOp->p3 ){
64039    p->nChange += u.bs.nChange;
64040    if( pOp->p3>0 ){
64041      aMem[pOp->p3].u.i += u.bs.nChange;
64042    }
64043  }
64044  break;
64045}
64046
64047/* Opcode: CreateTable P1 P2 * * *
64048**
64049** Allocate a new table in the main database file if P1==0 or in the
64050** auxiliary database file if P1==1 or in an attached database if
64051** P1>1.  Write the root page number of the new table into
64052** register P2
64053**
64054** The difference between a table and an index is this:  A table must
64055** have a 4-byte integer key and can have arbitrary data.  An index
64056** has an arbitrary key but no data.
64057**
64058** See also: CreateIndex
64059*/
64060/* Opcode: CreateIndex P1 P2 * * *
64061**
64062** Allocate a new index in the main database file if P1==0 or in the
64063** auxiliary database file if P1==1 or in an attached database if
64064** P1>1.  Write the root page number of the new table into
64065** register P2.
64066**
64067** See documentation on OP_CreateTable for additional information.
64068*/
64069case OP_CreateIndex:            /* out2-prerelease */
64070case OP_CreateTable: {          /* out2-prerelease */
64071#if 0  /* local variables moved into u.bt */
64072  int pgno;
64073  int flags;
64074  Db *pDb;
64075#endif /* local variables moved into u.bt */
64076
64077  u.bt.pgno = 0;
64078  assert( pOp->p1>=0 && pOp->p1<db->nDb );
64079  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64080  u.bt.pDb = &db->aDb[pOp->p1];
64081  assert( u.bt.pDb->pBt!=0 );
64082  if( pOp->opcode==OP_CreateTable ){
64083    /* u.bt.flags = BTREE_INTKEY; */
64084    u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
64085  }else{
64086    u.bt.flags = BTREE_ZERODATA;
64087  }
64088  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
64089  pOut->u.i = u.bt.pgno;
64090  break;
64091}
64092
64093/* Opcode: ParseSchema P1 P2 * P4 *
64094**
64095** Read and parse all entries from the SQLITE_MASTER table of database P1
64096** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
64097** the parsing if P2 is true.  If P2 is false, then this routine is a
64098** no-op if the schema is not currently loaded.  In other words, if P2
64099** is false, the SQLITE_MASTER table is only parsed if the rest of the
64100** schema is already loaded into the symbol table.
64101**
64102** This opcode invokes the parser to create a new virtual machine,
64103** then runs the new virtual machine.  It is thus a re-entrant opcode.
64104*/
64105case OP_ParseSchema: {
64106#if 0  /* local variables moved into u.bu */
64107  int iDb;
64108  const char *zMaster;
64109  char *zSql;
64110  InitData initData;
64111#endif /* local variables moved into u.bu */
64112
64113  u.bu.iDb = pOp->p1;
64114  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
64115
64116  /* If pOp->p2 is 0, then this opcode is being executed to read a
64117  ** single row, for example the row corresponding to a new index
64118  ** created by this VDBE, from the sqlite_master table. It only
64119  ** does this if the corresponding in-memory schema is currently
64120  ** loaded. Otherwise, the new index definition can be loaded along
64121  ** with the rest of the schema when it is required.
64122  **
64123  ** Although the mutex on the BtShared object that corresponds to
64124  ** database u.bu.iDb (the database containing the sqlite_master table
64125  ** read by this instruction) is currently held, it is necessary to
64126  ** obtain the mutexes on all attached databases before checking if
64127  ** the schema of u.bu.iDb is loaded. This is because, at the start of
64128  ** the sqlite3_exec() call below, SQLite will invoke
64129  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
64130  ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
64131  ** this happens, then some other thread may delete the in-memory
64132  ** schema of database u.bu.iDb before the SQL statement runs. The schema
64133  ** will not be reloaded becuase the db->init.busy flag is set. This
64134  ** can result in a "no such table: sqlite_master" or "malformed
64135  ** database schema" error being returned to the user.
64136  */
64137  assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
64138  sqlite3BtreeEnterAll(db);
64139  if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
64140    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
64141    u.bu.initData.db = db;
64142    u.bu.initData.iDb = pOp->p1;
64143    u.bu.initData.pzErrMsg = &p->zErrMsg;
64144    u.bu.zSql = sqlite3MPrintf(db,
64145       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
64146       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
64147    if( u.bu.zSql==0 ){
64148      rc = SQLITE_NOMEM;
64149    }else{
64150      assert( db->init.busy==0 );
64151      db->init.busy = 1;
64152      u.bu.initData.rc = SQLITE_OK;
64153      assert( !db->mallocFailed );
64154      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
64155      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
64156      sqlite3DbFree(db, u.bu.zSql);
64157      db->init.busy = 0;
64158    }
64159  }
64160  sqlite3BtreeLeaveAll(db);
64161  if( rc==SQLITE_NOMEM ){
64162    goto no_mem;
64163  }
64164  break;
64165}
64166
64167#if !defined(SQLITE_OMIT_ANALYZE)
64168/* Opcode: LoadAnalysis P1 * * * *
64169**
64170** Read the sqlite_stat1 table for database P1 and load the content
64171** of that table into the internal index hash table.  This will cause
64172** the analysis to be used when preparing all subsequent queries.
64173*/
64174case OP_LoadAnalysis: {
64175  assert( pOp->p1>=0 && pOp->p1<db->nDb );
64176  rc = sqlite3AnalysisLoad(db, pOp->p1);
64177  break;
64178}
64179#endif /* !defined(SQLITE_OMIT_ANALYZE) */
64180
64181/* Opcode: DropTable P1 * * P4 *
64182**
64183** Remove the internal (in-memory) data structures that describe
64184** the table named P4 in database P1.  This is called after a table
64185** is dropped in order to keep the internal representation of the
64186** schema consistent with what is on disk.
64187*/
64188case OP_DropTable: {
64189  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
64190  break;
64191}
64192
64193/* Opcode: DropIndex P1 * * P4 *
64194**
64195** Remove the internal (in-memory) data structures that describe
64196** the index named P4 in database P1.  This is called after an index
64197** is dropped in order to keep the internal representation of the
64198** schema consistent with what is on disk.
64199*/
64200case OP_DropIndex: {
64201  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
64202  break;
64203}
64204
64205/* Opcode: DropTrigger P1 * * P4 *
64206**
64207** Remove the internal (in-memory) data structures that describe
64208** the trigger named P4 in database P1.  This is called after a trigger
64209** is dropped in order to keep the internal representation of the
64210** schema consistent with what is on disk.
64211*/
64212case OP_DropTrigger: {
64213  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
64214  break;
64215}
64216
64217
64218#ifndef SQLITE_OMIT_INTEGRITY_CHECK
64219/* Opcode: IntegrityCk P1 P2 P3 * P5
64220**
64221** Do an analysis of the currently open database.  Store in
64222** register P1 the text of an error message describing any problems.
64223** If no problems are found, store a NULL in register P1.
64224**
64225** The register P3 contains the maximum number of allowed errors.
64226** At most reg(P3) errors will be reported.
64227** In other words, the analysis stops as soon as reg(P1) errors are
64228** seen.  Reg(P1) is updated with the number of errors remaining.
64229**
64230** The root page numbers of all tables in the database are integer
64231** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
64232** total.
64233**
64234** If P5 is not zero, the check is done on the auxiliary database
64235** file, not the main database file.
64236**
64237** This opcode is used to implement the integrity_check pragma.
64238*/
64239case OP_IntegrityCk: {
64240#if 0  /* local variables moved into u.bv */
64241  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
64242  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
64243  int j;          /* Loop counter */
64244  int nErr;       /* Number of errors reported */
64245  char *z;        /* Text of the error report */
64246  Mem *pnErr;     /* Register keeping track of errors remaining */
64247#endif /* local variables moved into u.bv */
64248
64249  u.bv.nRoot = pOp->p2;
64250  assert( u.bv.nRoot>0 );
64251  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
64252  if( u.bv.aRoot==0 ) goto no_mem;
64253  assert( pOp->p3>0 && pOp->p3<=p->nMem );
64254  u.bv.pnErr = &aMem[pOp->p3];
64255  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
64256  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
64257  pIn1 = &aMem[pOp->p1];
64258  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
64259    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
64260  }
64261  u.bv.aRoot[u.bv.j] = 0;
64262  assert( pOp->p5<db->nDb );
64263  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
64264  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
64265                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
64266  sqlite3DbFree(db, u.bv.aRoot);
64267  u.bv.pnErr->u.i -= u.bv.nErr;
64268  sqlite3VdbeMemSetNull(pIn1);
64269  if( u.bv.nErr==0 ){
64270    assert( u.bv.z==0 );
64271  }else if( u.bv.z==0 ){
64272    goto no_mem;
64273  }else{
64274    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
64275  }
64276  UPDATE_MAX_BLOBSIZE(pIn1);
64277  sqlite3VdbeChangeEncoding(pIn1, encoding);
64278  break;
64279}
64280#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
64281
64282/* Opcode: RowSetAdd P1 P2 * * *
64283**
64284** Insert the integer value held by register P2 into a boolean index
64285** held in register P1.
64286**
64287** An assertion fails if P2 is not an integer.
64288*/
64289case OP_RowSetAdd: {       /* in1, in2 */
64290  pIn1 = &aMem[pOp->p1];
64291  pIn2 = &aMem[pOp->p2];
64292  assert( (pIn2->flags & MEM_Int)!=0 );
64293  if( (pIn1->flags & MEM_RowSet)==0 ){
64294    sqlite3VdbeMemSetRowSet(pIn1);
64295    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
64296  }
64297  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
64298  break;
64299}
64300
64301/* Opcode: RowSetRead P1 P2 P3 * *
64302**
64303** Extract the smallest value from boolean index P1 and put that value into
64304** register P3.  Or, if boolean index P1 is initially empty, leave P3
64305** unchanged and jump to instruction P2.
64306*/
64307case OP_RowSetRead: {       /* jump, in1, out3 */
64308#if 0  /* local variables moved into u.bw */
64309  i64 val;
64310#endif /* local variables moved into u.bw */
64311  CHECK_FOR_INTERRUPT;
64312  pIn1 = &aMem[pOp->p1];
64313  if( (pIn1->flags & MEM_RowSet)==0
64314   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
64315  ){
64316    /* The boolean index is empty */
64317    sqlite3VdbeMemSetNull(pIn1);
64318    pc = pOp->p2 - 1;
64319  }else{
64320    /* A value was pulled from the index */
64321    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
64322  }
64323  break;
64324}
64325
64326/* Opcode: RowSetTest P1 P2 P3 P4
64327**
64328** Register P3 is assumed to hold a 64-bit integer value. If register P1
64329** contains a RowSet object and that RowSet object contains
64330** the value held in P3, jump to register P2. Otherwise, insert the
64331** integer in P3 into the RowSet and continue on to the
64332** next opcode.
64333**
64334** The RowSet object is optimized for the case where successive sets
64335** of integers, where each set contains no duplicates. Each set
64336** of values is identified by a unique P4 value. The first set
64337** must have P4==0, the final set P4=-1.  P4 must be either -1 or
64338** non-negative.  For non-negative values of P4 only the lower 4
64339** bits are significant.
64340**
64341** This allows optimizations: (a) when P4==0 there is no need to test
64342** the rowset object for P3, as it is guaranteed not to contain it,
64343** (b) when P4==-1 there is no need to insert the value, as it will
64344** never be tested for, and (c) when a value that is part of set X is
64345** inserted, there is no need to search to see if the same value was
64346** previously inserted as part of set X (only if it was previously
64347** inserted as part of some other set).
64348*/
64349case OP_RowSetTest: {                     /* jump, in1, in3 */
64350#if 0  /* local variables moved into u.bx */
64351  int iSet;
64352  int exists;
64353#endif /* local variables moved into u.bx */
64354
64355  pIn1 = &aMem[pOp->p1];
64356  pIn3 = &aMem[pOp->p3];
64357  u.bx.iSet = pOp->p4.i;
64358  assert( pIn3->flags&MEM_Int );
64359
64360  /* If there is anything other than a rowset object in memory cell P1,
64361  ** delete it now and initialize P1 with an empty rowset
64362  */
64363  if( (pIn1->flags & MEM_RowSet)==0 ){
64364    sqlite3VdbeMemSetRowSet(pIn1);
64365    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
64366  }
64367
64368  assert( pOp->p4type==P4_INT32 );
64369  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
64370  if( u.bx.iSet ){
64371    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
64372                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
64373                               pIn3->u.i);
64374    if( u.bx.exists ){
64375      pc = pOp->p2 - 1;
64376      break;
64377    }
64378  }
64379  if( u.bx.iSet>=0 ){
64380    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
64381  }
64382  break;
64383}
64384
64385
64386#ifndef SQLITE_OMIT_TRIGGER
64387
64388/* Opcode: Program P1 P2 P3 P4 *
64389**
64390** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
64391**
64392** P1 contains the address of the memory cell that contains the first memory
64393** cell in an array of values used as arguments to the sub-program. P2
64394** contains the address to jump to if the sub-program throws an IGNORE
64395** exception using the RAISE() function. Register P3 contains the address
64396** of a memory cell in this (the parent) VM that is used to allocate the
64397** memory required by the sub-vdbe at runtime.
64398**
64399** P4 is a pointer to the VM containing the trigger program.
64400*/
64401case OP_Program: {        /* jump */
64402#if 0  /* local variables moved into u.by */
64403  int nMem;               /* Number of memory registers for sub-program */
64404  int nByte;              /* Bytes of runtime space required for sub-program */
64405  Mem *pRt;               /* Register to allocate runtime space */
64406  Mem *pMem;              /* Used to iterate through memory cells */
64407  Mem *pEnd;              /* Last memory cell in new array */
64408  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
64409  SubProgram *pProgram;   /* Sub-program to execute */
64410  void *t;                /* Token identifying trigger */
64411#endif /* local variables moved into u.by */
64412
64413  u.by.pProgram = pOp->p4.pProgram;
64414  u.by.pRt = &aMem[pOp->p3];
64415  assert( u.by.pProgram->nOp>0 );
64416
64417  /* If the p5 flag is clear, then recursive invocation of triggers is
64418  ** disabled for backwards compatibility (p5 is set if this sub-program
64419  ** is really a trigger, not a foreign key action, and the flag set
64420  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
64421  **
64422  ** It is recursive invocation of triggers, at the SQL level, that is
64423  ** disabled. In some cases a single trigger may generate more than one
64424  ** SubProgram (if the trigger may be executed with more than one different
64425  ** ON CONFLICT algorithm). SubProgram structures associated with a
64426  ** single trigger all have the same value for the SubProgram.token
64427  ** variable.  */
64428  if( pOp->p5 ){
64429    u.by.t = u.by.pProgram->token;
64430    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
64431    if( u.by.pFrame ) break;
64432  }
64433
64434  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
64435    rc = SQLITE_ERROR;
64436    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
64437    break;
64438  }
64439
64440  /* Register u.by.pRt is used to store the memory required to save the state
64441  ** of the current program, and the memory required at runtime to execute
64442  ** the trigger program. If this trigger has been fired before, then u.by.pRt
64443  ** is already allocated. Otherwise, it must be initialized.  */
64444  if( (u.by.pRt->flags&MEM_Frame)==0 ){
64445    /* SubProgram.nMem is set to the number of memory cells used by the
64446    ** program stored in SubProgram.aOp. As well as these, one memory
64447    ** cell is required for each cursor used by the program. Set local
64448    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
64449    */
64450    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
64451    u.by.nByte = ROUND8(sizeof(VdbeFrame))
64452              + u.by.nMem * sizeof(Mem)
64453              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
64454    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
64455    if( !u.by.pFrame ){
64456      goto no_mem;
64457    }
64458    sqlite3VdbeMemRelease(u.by.pRt);
64459    u.by.pRt->flags = MEM_Frame;
64460    u.by.pRt->u.pFrame = u.by.pFrame;
64461
64462    u.by.pFrame->v = p;
64463    u.by.pFrame->nChildMem = u.by.nMem;
64464    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
64465    u.by.pFrame->pc = pc;
64466    u.by.pFrame->aMem = p->aMem;
64467    u.by.pFrame->nMem = p->nMem;
64468    u.by.pFrame->apCsr = p->apCsr;
64469    u.by.pFrame->nCursor = p->nCursor;
64470    u.by.pFrame->aOp = p->aOp;
64471    u.by.pFrame->nOp = p->nOp;
64472    u.by.pFrame->token = u.by.pProgram->token;
64473
64474    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
64475    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
64476      u.by.pMem->flags = MEM_Null;
64477      u.by.pMem->db = db;
64478    }
64479  }else{
64480    u.by.pFrame = u.by.pRt->u.pFrame;
64481    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
64482    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
64483    assert( pc==u.by.pFrame->pc );
64484  }
64485
64486  p->nFrame++;
64487  u.by.pFrame->pParent = p->pFrame;
64488  u.by.pFrame->lastRowid = db->lastRowid;
64489  u.by.pFrame->nChange = p->nChange;
64490  p->nChange = 0;
64491  p->pFrame = u.by.pFrame;
64492  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
64493  p->nMem = u.by.pFrame->nChildMem;
64494  p->nCursor = (u16)u.by.pFrame->nChildCsr;
64495  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
64496  p->aOp = aOp = u.by.pProgram->aOp;
64497  p->nOp = u.by.pProgram->nOp;
64498  pc = -1;
64499
64500  break;
64501}
64502
64503/* Opcode: Param P1 P2 * * *
64504**
64505** This opcode is only ever present in sub-programs called via the
64506** OP_Program instruction. Copy a value currently stored in a memory
64507** cell of the calling (parent) frame to cell P2 in the current frames
64508** address space. This is used by trigger programs to access the new.*
64509** and old.* values.
64510**
64511** The address of the cell in the parent frame is determined by adding
64512** the value of the P1 argument to the value of the P1 argument to the
64513** calling OP_Program instruction.
64514*/
64515case OP_Param: {           /* out2-prerelease */
64516#if 0  /* local variables moved into u.bz */
64517  VdbeFrame *pFrame;
64518  Mem *pIn;
64519#endif /* local variables moved into u.bz */
64520  u.bz.pFrame = p->pFrame;
64521  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
64522  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
64523  break;
64524}
64525
64526#endif /* #ifndef SQLITE_OMIT_TRIGGER */
64527
64528#ifndef SQLITE_OMIT_FOREIGN_KEY
64529/* Opcode: FkCounter P1 P2 * * *
64530**
64531** Increment a "constraint counter" by P2 (P2 may be negative or positive).
64532** If P1 is non-zero, the database constraint counter is incremented
64533** (deferred foreign key constraints). Otherwise, if P1 is zero, the
64534** statement counter is incremented (immediate foreign key constraints).
64535*/
64536case OP_FkCounter: {
64537  if( pOp->p1 ){
64538    db->nDeferredCons += pOp->p2;
64539  }else{
64540    p->nFkConstraint += pOp->p2;
64541  }
64542  break;
64543}
64544
64545/* Opcode: FkIfZero P1 P2 * * *
64546**
64547** This opcode tests if a foreign key constraint-counter is currently zero.
64548** If so, jump to instruction P2. Otherwise, fall through to the next
64549** instruction.
64550**
64551** If P1 is non-zero, then the jump is taken if the database constraint-counter
64552** is zero (the one that counts deferred constraint violations). If P1 is
64553** zero, the jump is taken if the statement constraint-counter is zero
64554** (immediate foreign key constraint violations).
64555*/
64556case OP_FkIfZero: {         /* jump */
64557  if( pOp->p1 ){
64558    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
64559  }else{
64560    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
64561  }
64562  break;
64563}
64564#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
64565
64566#ifndef SQLITE_OMIT_AUTOINCREMENT
64567/* Opcode: MemMax P1 P2 * * *
64568**
64569** P1 is a register in the root frame of this VM (the root frame is
64570** different from the current frame if this instruction is being executed
64571** within a sub-program). Set the value of register P1 to the maximum of
64572** its current value and the value in register P2.
64573**
64574** This instruction throws an error if the memory cell is not initially
64575** an integer.
64576*/
64577case OP_MemMax: {        /* in2 */
64578#if 0  /* local variables moved into u.ca */
64579  Mem *pIn1;
64580  VdbeFrame *pFrame;
64581#endif /* local variables moved into u.ca */
64582  if( p->pFrame ){
64583    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
64584    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
64585  }else{
64586    u.ca.pIn1 = &aMem[pOp->p1];
64587  }
64588  sqlite3VdbeMemIntegerify(u.ca.pIn1);
64589  pIn2 = &aMem[pOp->p2];
64590  sqlite3VdbeMemIntegerify(pIn2);
64591  if( u.ca.pIn1->u.i<pIn2->u.i){
64592    u.ca.pIn1->u.i = pIn2->u.i;
64593  }
64594  break;
64595}
64596#endif /* SQLITE_OMIT_AUTOINCREMENT */
64597
64598/* Opcode: IfPos P1 P2 * * *
64599**
64600** If the value of register P1 is 1 or greater, jump to P2.
64601**
64602** It is illegal to use this instruction on a register that does
64603** not contain an integer.  An assertion fault will result if you try.
64604*/
64605case OP_IfPos: {        /* jump, in1 */
64606  pIn1 = &aMem[pOp->p1];
64607  assert( pIn1->flags&MEM_Int );
64608  if( pIn1->u.i>0 ){
64609     pc = pOp->p2 - 1;
64610  }
64611  break;
64612}
64613
64614/* Opcode: IfNeg P1 P2 * * *
64615**
64616** If the value of register P1 is less than zero, jump to P2.
64617**
64618** It is illegal to use this instruction on a register that does
64619** not contain an integer.  An assertion fault will result if you try.
64620*/
64621case OP_IfNeg: {        /* jump, in1 */
64622  pIn1 = &aMem[pOp->p1];
64623  assert( pIn1->flags&MEM_Int );
64624  if( pIn1->u.i<0 ){
64625     pc = pOp->p2 - 1;
64626  }
64627  break;
64628}
64629
64630/* Opcode: IfZero P1 P2 P3 * *
64631**
64632** The register P1 must contain an integer.  Add literal P3 to the
64633** value in register P1.  If the result is exactly 0, jump to P2.
64634**
64635** It is illegal to use this instruction on a register that does
64636** not contain an integer.  An assertion fault will result if you try.
64637*/
64638case OP_IfZero: {        /* jump, in1 */
64639  pIn1 = &aMem[pOp->p1];
64640  assert( pIn1->flags&MEM_Int );
64641  pIn1->u.i += pOp->p3;
64642  if( pIn1->u.i==0 ){
64643     pc = pOp->p2 - 1;
64644  }
64645  break;
64646}
64647
64648/* Opcode: AggStep * P2 P3 P4 P5
64649**
64650** Execute the step function for an aggregate.  The
64651** function has P5 arguments.   P4 is a pointer to the FuncDef
64652** structure that specifies the function.  Use register
64653** P3 as the accumulator.
64654**
64655** The P5 arguments are taken from register P2 and its
64656** successors.
64657*/
64658case OP_AggStep: {
64659#if 0  /* local variables moved into u.cb */
64660  int n;
64661  int i;
64662  Mem *pMem;
64663  Mem *pRec;
64664  sqlite3_context ctx;
64665  sqlite3_value **apVal;
64666#endif /* local variables moved into u.cb */
64667
64668  u.cb.n = pOp->p5;
64669  assert( u.cb.n>=0 );
64670  u.cb.pRec = &aMem[pOp->p2];
64671  u.cb.apVal = p->apArg;
64672  assert( u.cb.apVal || u.cb.n==0 );
64673  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
64674    u.cb.apVal[u.cb.i] = u.cb.pRec;
64675    sqlite3VdbeMemStoreType(u.cb.pRec);
64676  }
64677  u.cb.ctx.pFunc = pOp->p4.pFunc;
64678  assert( pOp->p3>0 && pOp->p3<=p->nMem );
64679  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
64680  u.cb.pMem->n++;
64681  u.cb.ctx.s.flags = MEM_Null;
64682  u.cb.ctx.s.z = 0;
64683  u.cb.ctx.s.zMalloc = 0;
64684  u.cb.ctx.s.xDel = 0;
64685  u.cb.ctx.s.db = db;
64686  u.cb.ctx.isError = 0;
64687  u.cb.ctx.pColl = 0;
64688  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
64689    assert( pOp>p->aOp );
64690    assert( pOp[-1].p4type==P4_COLLSEQ );
64691    assert( pOp[-1].opcode==OP_CollSeq );
64692    u.cb.ctx.pColl = pOp[-1].p4.pColl;
64693  }
64694  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
64695  if( u.cb.ctx.isError ){
64696    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
64697    rc = u.cb.ctx.isError;
64698  }
64699  sqlite3VdbeMemRelease(&u.cb.ctx.s);
64700  break;
64701}
64702
64703/* Opcode: AggFinal P1 P2 * P4 *
64704**
64705** Execute the finalizer function for an aggregate.  P1 is
64706** the memory location that is the accumulator for the aggregate.
64707**
64708** P2 is the number of arguments that the step function takes and
64709** P4 is a pointer to the FuncDef for this function.  The P2
64710** argument is not used by this opcode.  It is only there to disambiguate
64711** functions that can take varying numbers of arguments.  The
64712** P4 argument is only needed for the degenerate case where
64713** the step function was not previously called.
64714*/
64715case OP_AggFinal: {
64716#if 0  /* local variables moved into u.cc */
64717  Mem *pMem;
64718#endif /* local variables moved into u.cc */
64719  assert( pOp->p1>0 && pOp->p1<=p->nMem );
64720  u.cc.pMem = &aMem[pOp->p1];
64721  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
64722  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
64723  if( rc ){
64724    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
64725  }
64726  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
64727  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
64728  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
64729    goto too_big;
64730  }
64731  break;
64732}
64733
64734#ifndef SQLITE_OMIT_WAL
64735/* Opcode: Checkpoint P1 * * * *
64736**
64737** Checkpoint database P1. This is a no-op if P1 is not currently in
64738** WAL mode.
64739*/
64740case OP_Checkpoint: {
64741  rc = sqlite3Checkpoint(db, pOp->p1);
64742  break;
64743};
64744#endif
64745
64746#ifndef SQLITE_OMIT_PRAGMA
64747/* Opcode: JournalMode P1 P2 P3 * P5
64748**
64749** Change the journal mode of database P1 to P3. P3 must be one of the
64750** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
64751** modes (delete, truncate, persist, off and memory), this is a simple
64752** operation. No IO is required.
64753**
64754** If changing into or out of WAL mode the procedure is more complicated.
64755**
64756** Write a string containing the final journal-mode to register P2.
64757*/
64758case OP_JournalMode: {    /* out2-prerelease */
64759#if 0  /* local variables moved into u.cd */
64760  Btree *pBt;                     /* Btree to change journal mode of */
64761  Pager *pPager;                  /* Pager associated with pBt */
64762  int eNew;                       /* New journal mode */
64763  int eOld;                       /* The old journal mode */
64764  const char *zFilename;          /* Name of database file for pPager */
64765#endif /* local variables moved into u.cd */
64766
64767  u.cd.eNew = pOp->p3;
64768  assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
64769       || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
64770       || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
64771       || u.cd.eNew==PAGER_JOURNALMODE_OFF
64772       || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
64773       || u.cd.eNew==PAGER_JOURNALMODE_WAL
64774       || u.cd.eNew==PAGER_JOURNALMODE_QUERY
64775  );
64776  assert( pOp->p1>=0 && pOp->p1<db->nDb );
64777
64778  /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
64779  ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
64780  ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
64781  ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
64782  ** is not called when the statement is prepared because it requires the
64783  ** iDb index of the database as a parameter, and the database has not
64784  ** yet been attached so that index is unavailable.  We have to wait
64785  ** until runtime (now) to get the mutex on the newly attached database.
64786  ** No other mutexes are required by the ATTACH command so this is safe
64787  ** to do.
64788  */
64789  assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
64790  if( p->aMutex.nMutex==0 ){
64791    /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
64792    ** database. */
64793    sqlite3VdbeUsesBtree(p, pOp->p1);
64794    sqlite3VdbeMutexArrayEnter(p);
64795  }
64796
64797  u.cd.pBt = db->aDb[pOp->p1].pBt;
64798  u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
64799  u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
64800  if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
64801  if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
64802
64803#ifndef SQLITE_OMIT_WAL
64804  u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
64805
64806  /* Do not allow a transition to journal_mode=WAL for a database
64807  ** in temporary storage or if the VFS does not support shared memory
64808  */
64809  if( u.cd.eNew==PAGER_JOURNALMODE_WAL
64810   && (u.cd.zFilename[0]==0                         /* Temp file */
64811       || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
64812  ){
64813    u.cd.eNew = u.cd.eOld;
64814  }
64815
64816  if( (u.cd.eNew!=u.cd.eOld)
64817   && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
64818  ){
64819    if( !db->autoCommit || db->activeVdbeCnt>1 ){
64820      rc = SQLITE_ERROR;
64821      sqlite3SetString(&p->zErrMsg, db,
64822          "cannot change %s wal mode from within a transaction",
64823          (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
64824      );
64825      break;
64826    }else{
64827
64828      if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
64829        /* If leaving WAL mode, close the log file. If successful, the call
64830        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
64831        ** file. An EXCLUSIVE lock may still be held on the database file
64832        ** after a successful return.
64833        */
64834        rc = sqlite3PagerCloseWal(u.cd.pPager);
64835        if( rc==SQLITE_OK ){
64836          sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
64837        }
64838      }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
64839        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
64840        ** as an intermediate */
64841        sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
64842      }
64843
64844      /* Open a transaction on the database file. Regardless of the journal
64845      ** mode, this transaction always uses a rollback journal.
64846      */
64847      assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
64848      if( rc==SQLITE_OK ){
64849        rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
64850      }
64851    }
64852  }
64853#endif /* ifndef SQLITE_OMIT_WAL */
64854
64855  if( rc ){
64856    u.cd.eNew = u.cd.eOld;
64857  }
64858  u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
64859
64860  pOut = &aMem[pOp->p2];
64861  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
64862  pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
64863  pOut->n = sqlite3Strlen30(pOut->z);
64864  pOut->enc = SQLITE_UTF8;
64865  sqlite3VdbeChangeEncoding(pOut, encoding);
64866  break;
64867};
64868#endif /* SQLITE_OMIT_PRAGMA */
64869
64870#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
64871/* Opcode: Vacuum * * * * *
64872**
64873** Vacuum the entire database.  This opcode will cause other virtual
64874** machines to be created and run.  It may not be called from within
64875** a transaction.
64876*/
64877case OP_Vacuum: {
64878  rc = sqlite3RunVacuum(&p->zErrMsg, db);
64879  break;
64880}
64881#endif
64882
64883#if !defined(SQLITE_OMIT_AUTOVACUUM)
64884/* Opcode: IncrVacuum P1 P2 * * *
64885**
64886** Perform a single step of the incremental vacuum procedure on
64887** the P1 database. If the vacuum has finished, jump to instruction
64888** P2. Otherwise, fall through to the next instruction.
64889*/
64890case OP_IncrVacuum: {        /* jump */
64891#if 0  /* local variables moved into u.ce */
64892  Btree *pBt;
64893#endif /* local variables moved into u.ce */
64894
64895  assert( pOp->p1>=0 && pOp->p1<db->nDb );
64896  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64897  u.ce.pBt = db->aDb[pOp->p1].pBt;
64898  rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
64899  if( rc==SQLITE_DONE ){
64900    pc = pOp->p2 - 1;
64901    rc = SQLITE_OK;
64902  }
64903  break;
64904}
64905#endif
64906
64907/* Opcode: Expire P1 * * * *
64908**
64909** Cause precompiled statements to become expired. An expired statement
64910** fails with an error code of SQLITE_SCHEMA if it is ever executed
64911** (via sqlite3_step()).
64912**
64913** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
64914** then only the currently executing statement is affected.
64915*/
64916case OP_Expire: {
64917  if( !pOp->p1 ){
64918    sqlite3ExpirePreparedStatements(db);
64919  }else{
64920    p->expired = 1;
64921  }
64922  break;
64923}
64924
64925#ifndef SQLITE_OMIT_SHARED_CACHE
64926/* Opcode: TableLock P1 P2 P3 P4 *
64927**
64928** Obtain a lock on a particular table. This instruction is only used when
64929** the shared-cache feature is enabled.
64930**
64931** P1 is the index of the database in sqlite3.aDb[] of the database
64932** on which the lock is acquired.  A readlock is obtained if P3==0 or
64933** a write lock if P3==1.
64934**
64935** P2 contains the root-page of the table to lock.
64936**
64937** P4 contains a pointer to the name of the table being locked. This is only
64938** used to generate an error message if the lock cannot be obtained.
64939*/
64940case OP_TableLock: {
64941  u8 isWriteLock = (u8)pOp->p3;
64942  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
64943    int p1 = pOp->p1;
64944    assert( p1>=0 && p1<db->nDb );
64945    assert( (p->btreeMask & (1<<p1))!=0 );
64946    assert( isWriteLock==0 || isWriteLock==1 );
64947    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
64948    if( (rc&0xFF)==SQLITE_LOCKED ){
64949      const char *z = pOp->p4.z;
64950      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
64951    }
64952  }
64953  break;
64954}
64955#endif /* SQLITE_OMIT_SHARED_CACHE */
64956
64957#ifndef SQLITE_OMIT_VIRTUALTABLE
64958/* Opcode: VBegin * * * P4 *
64959**
64960** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
64961** xBegin method for that table.
64962**
64963** Also, whether or not P4 is set, check that this is not being called from
64964** within a callback to a virtual table xSync() method. If it is, the error
64965** code will be set to SQLITE_LOCKED.
64966*/
64967case OP_VBegin: {
64968#if 0  /* local variables moved into u.cf */
64969  VTable *pVTab;
64970#endif /* local variables moved into u.cf */
64971  u.cf.pVTab = pOp->p4.pVtab;
64972  rc = sqlite3VtabBegin(db, u.cf.pVTab);
64973  if( u.cf.pVTab ) importVtabErrMsg(p, u.cf.pVTab->pVtab);
64974  break;
64975}
64976#endif /* SQLITE_OMIT_VIRTUALTABLE */
64977
64978#ifndef SQLITE_OMIT_VIRTUALTABLE
64979/* Opcode: VCreate P1 * * P4 *
64980**
64981** P4 is the name of a virtual table in database P1. Call the xCreate method
64982** for that table.
64983*/
64984case OP_VCreate: {
64985  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
64986  break;
64987}
64988#endif /* SQLITE_OMIT_VIRTUALTABLE */
64989
64990#ifndef SQLITE_OMIT_VIRTUALTABLE
64991/* Opcode: VDestroy P1 * * P4 *
64992**
64993** P4 is the name of a virtual table in database P1.  Call the xDestroy method
64994** of that table.
64995*/
64996case OP_VDestroy: {
64997  p->inVtabMethod = 2;
64998  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
64999  p->inVtabMethod = 0;
65000  break;
65001}
65002#endif /* SQLITE_OMIT_VIRTUALTABLE */
65003
65004#ifndef SQLITE_OMIT_VIRTUALTABLE
65005/* Opcode: VOpen P1 * * P4 *
65006**
65007** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65008** P1 is a cursor number.  This opcode opens a cursor to the virtual
65009** table and stores that cursor in P1.
65010*/
65011case OP_VOpen: {
65012#if 0  /* local variables moved into u.cg */
65013  VdbeCursor *pCur;
65014  sqlite3_vtab_cursor *pVtabCursor;
65015  sqlite3_vtab *pVtab;
65016  sqlite3_module *pModule;
65017#endif /* local variables moved into u.cg */
65018
65019  u.cg.pCur = 0;
65020  u.cg.pVtabCursor = 0;
65021  u.cg.pVtab = pOp->p4.pVtab->pVtab;
65022  u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
65023  assert(u.cg.pVtab && u.cg.pModule);
65024  rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
65025  importVtabErrMsg(p, u.cg.pVtab);
65026  if( SQLITE_OK==rc ){
65027    /* Initialize sqlite3_vtab_cursor base class */
65028    u.cg.pVtabCursor->pVtab = u.cg.pVtab;
65029
65030    /* Initialise vdbe cursor object */
65031    u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
65032    if( u.cg.pCur ){
65033      u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
65034      u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
65035    }else{
65036      db->mallocFailed = 1;
65037      u.cg.pModule->xClose(u.cg.pVtabCursor);
65038    }
65039  }
65040  break;
65041}
65042#endif /* SQLITE_OMIT_VIRTUALTABLE */
65043
65044#ifndef SQLITE_OMIT_VIRTUALTABLE
65045/* Opcode: VFilter P1 P2 P3 P4 *
65046**
65047** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
65048** the filtered result set is empty.
65049**
65050** P4 is either NULL or a string that was generated by the xBestIndex
65051** method of the module.  The interpretation of the P4 string is left
65052** to the module implementation.
65053**
65054** This opcode invokes the xFilter method on the virtual table specified
65055** by P1.  The integer query plan parameter to xFilter is stored in register
65056** P3. Register P3+1 stores the argc parameter to be passed to the
65057** xFilter method. Registers P3+2..P3+1+argc are the argc
65058** additional parameters which are passed to
65059** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
65060**
65061** A jump is made to P2 if the result set after filtering would be empty.
65062*/
65063case OP_VFilter: {   /* jump */
65064#if 0  /* local variables moved into u.ch */
65065  int nArg;
65066  int iQuery;
65067  const sqlite3_module *pModule;
65068  Mem *pQuery;
65069  Mem *pArgc;
65070  sqlite3_vtab_cursor *pVtabCursor;
65071  sqlite3_vtab *pVtab;
65072  VdbeCursor *pCur;
65073  int res;
65074  int i;
65075  Mem **apArg;
65076#endif /* local variables moved into u.ch */
65077
65078  u.ch.pQuery = &aMem[pOp->p3];
65079  u.ch.pArgc = &u.ch.pQuery[1];
65080  u.ch.pCur = p->apCsr[pOp->p1];
65081  REGISTER_TRACE(pOp->p3, u.ch.pQuery);
65082  assert( u.ch.pCur->pVtabCursor );
65083  u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
65084  u.ch.pVtab = u.ch.pVtabCursor->pVtab;
65085  u.ch.pModule = u.ch.pVtab->pModule;
65086
65087  /* Grab the index number and argc parameters */
65088  assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
65089  u.ch.nArg = (int)u.ch.pArgc->u.i;
65090  u.ch.iQuery = (int)u.ch.pQuery->u.i;
65091
65092  /* Invoke the xFilter method */
65093  {
65094    u.ch.res = 0;
65095    u.ch.apArg = p->apArg;
65096    for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
65097      u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
65098      sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
65099    }
65100
65101    p->inVtabMethod = 1;
65102    rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
65103    p->inVtabMethod = 0;
65104    importVtabErrMsg(p, u.ch.pVtab);
65105    if( rc==SQLITE_OK ){
65106      u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
65107    }
65108
65109    if( u.ch.res ){
65110      pc = pOp->p2 - 1;
65111    }
65112  }
65113  u.ch.pCur->nullRow = 0;
65114
65115  break;
65116}
65117#endif /* SQLITE_OMIT_VIRTUALTABLE */
65118
65119#ifndef SQLITE_OMIT_VIRTUALTABLE
65120/* Opcode: VColumn P1 P2 P3 * *
65121**
65122** Store the value of the P2-th column of
65123** the row of the virtual-table that the
65124** P1 cursor is pointing to into register P3.
65125*/
65126case OP_VColumn: {
65127#if 0  /* local variables moved into u.ci */
65128  sqlite3_vtab *pVtab;
65129  const sqlite3_module *pModule;
65130  Mem *pDest;
65131  sqlite3_context sContext;
65132#endif /* local variables moved into u.ci */
65133
65134  VdbeCursor *pCur = p->apCsr[pOp->p1];
65135  assert( pCur->pVtabCursor );
65136  assert( pOp->p3>0 && pOp->p3<=p->nMem );
65137  u.ci.pDest = &aMem[pOp->p3];
65138  if( pCur->nullRow ){
65139    sqlite3VdbeMemSetNull(u.ci.pDest);
65140    break;
65141  }
65142  u.ci.pVtab = pCur->pVtabCursor->pVtab;
65143  u.ci.pModule = u.ci.pVtab->pModule;
65144  assert( u.ci.pModule->xColumn );
65145  memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
65146
65147  /* The output cell may already have a buffer allocated. Move
65148  ** the current contents to u.ci.sContext.s so in case the user-function
65149  ** can use the already allocated buffer instead of allocating a
65150  ** new one.
65151  */
65152  sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
65153  MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
65154
65155  rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
65156  importVtabErrMsg(p, u.ci.pVtab);
65157  if( u.ci.sContext.isError ){
65158    rc = u.ci.sContext.isError;
65159  }
65160
65161  /* Copy the result of the function to the P3 register. We
65162  ** do this regardless of whether or not an error occurred to ensure any
65163  ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
65164  */
65165  sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
65166  sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
65167  REGISTER_TRACE(pOp->p3, u.ci.pDest);
65168  UPDATE_MAX_BLOBSIZE(u.ci.pDest);
65169
65170  if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
65171    goto too_big;
65172  }
65173  break;
65174}
65175#endif /* SQLITE_OMIT_VIRTUALTABLE */
65176
65177#ifndef SQLITE_OMIT_VIRTUALTABLE
65178/* Opcode: VNext P1 P2 * * *
65179**
65180** Advance virtual table P1 to the next row in its result set and
65181** jump to instruction P2.  Or, if the virtual table has reached
65182** the end of its result set, then fall through to the next instruction.
65183*/
65184case OP_VNext: {   /* jump */
65185#if 0  /* local variables moved into u.cj */
65186  sqlite3_vtab *pVtab;
65187  const sqlite3_module *pModule;
65188  int res;
65189  VdbeCursor *pCur;
65190#endif /* local variables moved into u.cj */
65191
65192  u.cj.res = 0;
65193  u.cj.pCur = p->apCsr[pOp->p1];
65194  assert( u.cj.pCur->pVtabCursor );
65195  if( u.cj.pCur->nullRow ){
65196    break;
65197  }
65198  u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
65199  u.cj.pModule = u.cj.pVtab->pModule;
65200  assert( u.cj.pModule->xNext );
65201
65202  /* Invoke the xNext() method of the module. There is no way for the
65203  ** underlying implementation to return an error if one occurs during
65204  ** xNext(). Instead, if an error occurs, true is returned (indicating that
65205  ** data is available) and the error code returned when xColumn or
65206  ** some other method is next invoked on the save virtual table cursor.
65207  */
65208  p->inVtabMethod = 1;
65209  rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
65210  p->inVtabMethod = 0;
65211  importVtabErrMsg(p, u.cj.pVtab);
65212  if( rc==SQLITE_OK ){
65213    u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
65214  }
65215
65216  if( !u.cj.res ){
65217    /* If there is data, jump to P2 */
65218    pc = pOp->p2 - 1;
65219  }
65220  break;
65221}
65222#endif /* SQLITE_OMIT_VIRTUALTABLE */
65223
65224#ifndef SQLITE_OMIT_VIRTUALTABLE
65225/* Opcode: VRename P1 * * P4 *
65226**
65227** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65228** This opcode invokes the corresponding xRename method. The value
65229** in register P1 is passed as the zName argument to the xRename method.
65230*/
65231case OP_VRename: {
65232#if 0  /* local variables moved into u.ck */
65233  sqlite3_vtab *pVtab;
65234  Mem *pName;
65235#endif /* local variables moved into u.ck */
65236
65237  u.ck.pVtab = pOp->p4.pVtab->pVtab;
65238  u.ck.pName = &aMem[pOp->p1];
65239  assert( u.ck.pVtab->pModule->xRename );
65240  REGISTER_TRACE(pOp->p1, u.ck.pName);
65241  assert( u.ck.pName->flags & MEM_Str );
65242  rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
65243  importVtabErrMsg(p, u.ck.pVtab);
65244
65245  break;
65246}
65247#endif
65248
65249#ifndef SQLITE_OMIT_VIRTUALTABLE
65250/* Opcode: VUpdate P1 P2 P3 P4 *
65251**
65252** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65253** This opcode invokes the corresponding xUpdate method. P2 values
65254** are contiguous memory cells starting at P3 to pass to the xUpdate
65255** invocation. The value in register (P3+P2-1) corresponds to the
65256** p2th element of the argv array passed to xUpdate.
65257**
65258** The xUpdate method will do a DELETE or an INSERT or both.
65259** The argv[0] element (which corresponds to memory cell P3)
65260** is the rowid of a row to delete.  If argv[0] is NULL then no
65261** deletion occurs.  The argv[1] element is the rowid of the new
65262** row.  This can be NULL to have the virtual table select the new
65263** rowid for itself.  The subsequent elements in the array are
65264** the values of columns in the new row.
65265**
65266** If P2==1 then no insert is performed.  argv[0] is the rowid of
65267** a row to delete.
65268**
65269** P1 is a boolean flag. If it is set to true and the xUpdate call
65270** is successful, then the value returned by sqlite3_last_insert_rowid()
65271** is set to the value of the rowid for the row just inserted.
65272*/
65273case OP_VUpdate: {
65274#if 0  /* local variables moved into u.cl */
65275  sqlite3_vtab *pVtab;
65276  sqlite3_module *pModule;
65277  int nArg;
65278  int i;
65279  sqlite_int64 rowid;
65280  Mem **apArg;
65281  Mem *pX;
65282#endif /* local variables moved into u.cl */
65283
65284  u.cl.pVtab = pOp->p4.pVtab->pVtab;
65285  u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
65286  u.cl.nArg = pOp->p2;
65287  assert( pOp->p4type==P4_VTAB );
65288  if( ALWAYS(u.cl.pModule->xUpdate) ){
65289    u.cl.apArg = p->apArg;
65290    u.cl.pX = &aMem[pOp->p3];
65291    for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
65292      sqlite3VdbeMemStoreType(u.cl.pX);
65293      u.cl.apArg[u.cl.i] = u.cl.pX;
65294      u.cl.pX++;
65295    }
65296    rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
65297    importVtabErrMsg(p, u.cl.pVtab);
65298    if( rc==SQLITE_OK && pOp->p1 ){
65299      assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
65300      db->lastRowid = u.cl.rowid;
65301    }
65302    p->nChange++;
65303  }
65304  break;
65305}
65306#endif /* SQLITE_OMIT_VIRTUALTABLE */
65307
65308#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
65309/* Opcode: Pagecount P1 P2 * * *
65310**
65311** Write the current number of pages in database P1 to memory cell P2.
65312*/
65313case OP_Pagecount: {            /* out2-prerelease */
65314  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
65315  break;
65316}
65317#endif
65318
65319#ifndef SQLITE_OMIT_TRACE
65320/* Opcode: Trace * * * P4 *
65321**
65322** If tracing is enabled (by the sqlite3_trace()) interface, then
65323** the UTF-8 string contained in P4 is emitted on the trace callback.
65324*/
65325case OP_Trace: {
65326#if 0  /* local variables moved into u.cm */
65327  char *zTrace;
65328#endif /* local variables moved into u.cm */
65329
65330  u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
65331  if( u.cm.zTrace ){
65332    if( db->xTrace ){
65333      char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
65334      db->xTrace(db->pTraceArg, z);
65335      sqlite3DbFree(db, z);
65336    }
65337#ifdef SQLITE_DEBUG
65338    if( (db->flags & SQLITE_SqlTrace)!=0 ){
65339      sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
65340    }
65341#endif /* SQLITE_DEBUG */
65342  }
65343  break;
65344}
65345#endif
65346
65347
65348/* Opcode: Noop * * * * *
65349**
65350** Do nothing.  This instruction is often useful as a jump
65351** destination.
65352*/
65353/*
65354** The magic Explain opcode are only inserted when explain==2 (which
65355** is to say when the EXPLAIN QUERY PLAN syntax is used.)
65356** This opcode records information from the optimizer.  It is the
65357** the same as a no-op.  This opcodesnever appears in a real VM program.
65358*/
65359default: {          /* This is really OP_Noop and OP_Explain */
65360  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
65361  break;
65362}
65363
65364/*****************************************************************************
65365** The cases of the switch statement above this line should all be indented
65366** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
65367** readability.  From this point on down, the normal indentation rules are
65368** restored.
65369*****************************************************************************/
65370    }
65371
65372#ifdef VDBE_PROFILE
65373    {
65374      u64 elapsed = sqlite3Hwtime() - start;
65375      pOp->cycles += elapsed;
65376      pOp->cnt++;
65377#if 0
65378        fprintf(stdout, "%10llu ", elapsed);
65379        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
65380#endif
65381    }
65382#endif
65383
65384    /* The following code adds nothing to the actual functionality
65385    ** of the program.  It is only here for testing and debugging.
65386    ** On the other hand, it does burn CPU cycles every time through
65387    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
65388    */
65389#ifndef NDEBUG
65390    assert( pc>=-1 && pc<p->nOp );
65391
65392#ifdef SQLITE_DEBUG
65393    if( p->trace ){
65394      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
65395      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
65396        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
65397      }
65398      if( pOp->opflags & OPFLG_OUT3 ){
65399        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
65400      }
65401    }
65402#endif  /* SQLITE_DEBUG */
65403#endif  /* NDEBUG */
65404  }  /* The end of the for(;;) loop the loops through opcodes */
65405
65406  /* If we reach this point, it means that execution is finished with
65407  ** an error of some kind.
65408  */
65409vdbe_error_halt:
65410  assert( rc );
65411  p->rc = rc;
65412  testcase( sqlite3GlobalConfig.xLog!=0 );
65413  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
65414                   pc, p->zSql, p->zErrMsg);
65415  sqlite3VdbeHalt(p);
65416  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
65417  rc = SQLITE_ERROR;
65418  if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
65419
65420  /* This is the only way out of this procedure.  We have to
65421  ** release the mutexes on btrees that were acquired at the
65422  ** top. */
65423vdbe_return:
65424  sqlite3BtreeMutexArrayLeave(&p->aMutex);
65425  return rc;
65426
65427  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
65428  ** is encountered.
65429  */
65430too_big:
65431  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
65432  rc = SQLITE_TOOBIG;
65433  goto vdbe_error_halt;
65434
65435  /* Jump to here if a malloc() fails.
65436  */
65437no_mem:
65438  db->mallocFailed = 1;
65439  sqlite3SetString(&p->zErrMsg, db, "out of memory");
65440  rc = SQLITE_NOMEM;
65441  goto vdbe_error_halt;
65442
65443  /* Jump to here for any other kind of fatal error.  The "rc" variable
65444  ** should hold the error number.
65445  */
65446abort_due_to_error:
65447  assert( p->zErrMsg==0 );
65448  if( db->mallocFailed ) rc = SQLITE_NOMEM;
65449  if( rc!=SQLITE_IOERR_NOMEM ){
65450    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
65451  }
65452  goto vdbe_error_halt;
65453
65454  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
65455  ** flag.
65456  */
65457abort_due_to_interrupt:
65458  assert( db->u1.isInterrupted );
65459  rc = SQLITE_INTERRUPT;
65460  p->rc = rc;
65461  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
65462  goto vdbe_error_halt;
65463}
65464
65465/************** End of vdbe.c ************************************************/
65466/************** Begin file vdbeblob.c ****************************************/
65467/*
65468** 2007 May 1
65469**
65470** The author disclaims copyright to this source code.  In place of
65471** a legal notice, here is a blessing:
65472**
65473**    May you do good and not evil.
65474**    May you find forgiveness for yourself and forgive others.
65475**    May you share freely, never taking more than you give.
65476**
65477*************************************************************************
65478**
65479** This file contains code used to implement incremental BLOB I/O.
65480*/
65481
65482
65483#ifndef SQLITE_OMIT_INCRBLOB
65484
65485/*
65486** Valid sqlite3_blob* handles point to Incrblob structures.
65487*/
65488typedef struct Incrblob Incrblob;
65489struct Incrblob {
65490  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
65491  int nByte;              /* Size of open blob, in bytes */
65492  int iOffset;            /* Byte offset of blob in cursor data */
65493  BtCursor *pCsr;         /* Cursor pointing at blob row */
65494  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
65495  sqlite3 *db;            /* The associated database */
65496};
65497
65498/*
65499** Open a blob handle.
65500*/
65501SQLITE_API int sqlite3_blob_open(
65502  sqlite3* db,            /* The database connection */
65503  const char *zDb,        /* The attached database containing the blob */
65504  const char *zTable,     /* The table containing the blob */
65505  const char *zColumn,    /* The column containing the blob */
65506  sqlite_int64 iRow,      /* The row containing the glob */
65507  int flags,              /* True -> read/write access, false -> read-only */
65508  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
65509){
65510  int nAttempt = 0;
65511  int iCol;               /* Index of zColumn in row-record */
65512
65513  /* This VDBE program seeks a btree cursor to the identified
65514  ** db/table/row entry. The reason for using a vdbe program instead
65515  ** of writing code to use the b-tree layer directly is that the
65516  ** vdbe program will take advantage of the various transaction,
65517  ** locking and error handling infrastructure built into the vdbe.
65518  **
65519  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
65520  ** Code external to the Vdbe then "borrows" the b-tree cursor and
65521  ** uses it to implement the blob_read(), blob_write() and
65522  ** blob_bytes() functions.
65523  **
65524  ** The sqlite3_blob_close() function finalizes the vdbe program,
65525  ** which closes the b-tree cursor and (possibly) commits the
65526  ** transaction.
65527  */
65528  static const VdbeOpList openBlob[] = {
65529    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
65530    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
65531    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
65532
65533    /* One of the following two instructions is replaced by an OP_Noop. */
65534    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
65535    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
65536
65537    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
65538    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
65539    {OP_Column, 0, 0, 1},          /* 7  */
65540    {OP_ResultRow, 1, 0, 0},       /* 8  */
65541    {OP_Close, 0, 0, 0},           /* 9  */
65542    {OP_Halt, 0, 0, 0},            /* 10 */
65543  };
65544
65545  Vdbe *v = 0;
65546  int rc = SQLITE_OK;
65547  char *zErr = 0;
65548  Table *pTab;
65549  Parse *pParse;
65550
65551  *ppBlob = 0;
65552  sqlite3_mutex_enter(db->mutex);
65553  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
65554  if( pParse==0 ){
65555    rc = SQLITE_NOMEM;
65556    goto blob_open_out;
65557  }
65558  do {
65559    memset(pParse, 0, sizeof(Parse));
65560    pParse->db = db;
65561
65562    sqlite3BtreeEnterAll(db);
65563    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
65564    if( pTab && IsVirtual(pTab) ){
65565      pTab = 0;
65566      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
65567    }
65568#ifndef SQLITE_OMIT_VIEW
65569    if( pTab && pTab->pSelect ){
65570      pTab = 0;
65571      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
65572    }
65573#endif
65574    if( !pTab ){
65575      if( pParse->zErrMsg ){
65576        sqlite3DbFree(db, zErr);
65577        zErr = pParse->zErrMsg;
65578        pParse->zErrMsg = 0;
65579      }
65580      rc = SQLITE_ERROR;
65581      sqlite3BtreeLeaveAll(db);
65582      goto blob_open_out;
65583    }
65584
65585    /* Now search pTab for the exact column. */
65586    for(iCol=0; iCol < pTab->nCol; iCol++) {
65587      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
65588        break;
65589      }
65590    }
65591    if( iCol==pTab->nCol ){
65592      sqlite3DbFree(db, zErr);
65593      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
65594      rc = SQLITE_ERROR;
65595      sqlite3BtreeLeaveAll(db);
65596      goto blob_open_out;
65597    }
65598
65599    /* If the value is being opened for writing, check that the
65600    ** column is not indexed, and that it is not part of a foreign key.
65601    ** It is against the rules to open a column to which either of these
65602    ** descriptions applies for writing.  */
65603    if( flags ){
65604      const char *zFault = 0;
65605      Index *pIdx;
65606#ifndef SQLITE_OMIT_FOREIGN_KEY
65607      if( db->flags&SQLITE_ForeignKeys ){
65608        /* Check that the column is not part of an FK child key definition. It
65609        ** is not necessary to check if it is part of a parent key, as parent
65610        ** key columns must be indexed. The check below will pick up this
65611        ** case.  */
65612        FKey *pFKey;
65613        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
65614          int j;
65615          for(j=0; j<pFKey->nCol; j++){
65616            if( pFKey->aCol[j].iFrom==iCol ){
65617              zFault = "foreign key";
65618            }
65619          }
65620        }
65621      }
65622#endif
65623      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65624        int j;
65625        for(j=0; j<pIdx->nColumn; j++){
65626          if( pIdx->aiColumn[j]==iCol ){
65627            zFault = "indexed";
65628          }
65629        }
65630      }
65631      if( zFault ){
65632        sqlite3DbFree(db, zErr);
65633        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
65634        rc = SQLITE_ERROR;
65635        sqlite3BtreeLeaveAll(db);
65636        goto blob_open_out;
65637      }
65638    }
65639
65640    v = sqlite3VdbeCreate(db);
65641    if( v ){
65642      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65643      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
65644      flags = !!flags;                 /* flags = (flags ? 1 : 0); */
65645
65646      /* Configure the OP_Transaction */
65647      sqlite3VdbeChangeP1(v, 0, iDb);
65648      sqlite3VdbeChangeP2(v, 0, flags);
65649
65650      /* Configure the OP_VerifyCookie */
65651      sqlite3VdbeChangeP1(v, 1, iDb);
65652      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
65653
65654      /* Make sure a mutex is held on the table to be accessed */
65655      sqlite3VdbeUsesBtree(v, iDb);
65656
65657      /* Configure the OP_TableLock instruction */
65658#ifdef SQLITE_OMIT_SHARED_CACHE
65659      sqlite3VdbeChangeToNoop(v, 2, 1);
65660#else
65661      sqlite3VdbeChangeP1(v, 2, iDb);
65662      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
65663      sqlite3VdbeChangeP3(v, 2, flags);
65664      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
65665#endif
65666
65667      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
65668      ** parameter of the other to pTab->tnum.  */
65669      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
65670      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
65671      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
65672
65673      /* Configure the number of columns. Configure the cursor to
65674      ** think that the table has one more column than it really
65675      ** does. An OP_Column to retrieve this imaginary column will
65676      ** always return an SQL NULL. This is useful because it means
65677      ** we can invoke OP_Column to fill in the vdbe cursors type
65678      ** and offset cache without causing any IO.
65679      */
65680      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
65681      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
65682      if( !db->mallocFailed ){
65683        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
65684      }
65685    }
65686
65687    sqlite3BtreeLeaveAll(db);
65688    if( db->mallocFailed ){
65689      goto blob_open_out;
65690    }
65691
65692    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
65693    rc = sqlite3_step((sqlite3_stmt *)v);
65694    if( rc!=SQLITE_ROW ){
65695      nAttempt++;
65696      rc = sqlite3_finalize((sqlite3_stmt *)v);
65697      sqlite3DbFree(db, zErr);
65698      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
65699      v = 0;
65700    }
65701  } while( nAttempt<5 && rc==SQLITE_SCHEMA );
65702
65703  if( rc==SQLITE_ROW ){
65704    /* The row-record has been opened successfully. Check that the
65705    ** column in question contains text or a blob. If it contains
65706    ** text, it is up to the caller to get the encoding right.
65707    */
65708    Incrblob *pBlob;
65709    u32 type = v->apCsr[0]->aType[iCol];
65710
65711    if( type<12 ){
65712      sqlite3DbFree(db, zErr);
65713      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
65714          type==0?"null": type==7?"real": "integer"
65715      );
65716      rc = SQLITE_ERROR;
65717      goto blob_open_out;
65718    }
65719    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
65720    if( db->mallocFailed ){
65721      sqlite3DbFree(db, pBlob);
65722      goto blob_open_out;
65723    }
65724    pBlob->flags = flags;
65725    pBlob->pCsr =  v->apCsr[0]->pCursor;
65726    sqlite3BtreeEnterCursor(pBlob->pCsr);
65727    sqlite3BtreeCacheOverflow(pBlob->pCsr);
65728    sqlite3BtreeLeaveCursor(pBlob->pCsr);
65729    pBlob->pStmt = (sqlite3_stmt *)v;
65730    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
65731    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
65732    pBlob->db = db;
65733    *ppBlob = (sqlite3_blob *)pBlob;
65734    rc = SQLITE_OK;
65735  }else if( rc==SQLITE_OK ){
65736    sqlite3DbFree(db, zErr);
65737    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
65738    rc = SQLITE_ERROR;
65739  }
65740
65741blob_open_out:
65742  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
65743    sqlite3VdbeFinalize(v);
65744  }
65745  sqlite3Error(db, rc, zErr);
65746  sqlite3DbFree(db, zErr);
65747  sqlite3StackFree(db, pParse);
65748  rc = sqlite3ApiExit(db, rc);
65749  sqlite3_mutex_leave(db->mutex);
65750  return rc;
65751}
65752
65753/*
65754** Close a blob handle that was previously created using
65755** sqlite3_blob_open().
65756*/
65757SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
65758  Incrblob *p = (Incrblob *)pBlob;
65759  int rc;
65760  sqlite3 *db;
65761
65762  if( p ){
65763    db = p->db;
65764    sqlite3_mutex_enter(db->mutex);
65765    rc = sqlite3_finalize(p->pStmt);
65766    sqlite3DbFree(db, p);
65767    sqlite3_mutex_leave(db->mutex);
65768  }else{
65769    rc = SQLITE_OK;
65770  }
65771  return rc;
65772}
65773
65774/*
65775** Perform a read or write operation on a blob
65776*/
65777static int blobReadWrite(
65778  sqlite3_blob *pBlob,
65779  void *z,
65780  int n,
65781  int iOffset,
65782  int (*xCall)(BtCursor*, u32, u32, void*)
65783){
65784  int rc;
65785  Incrblob *p = (Incrblob *)pBlob;
65786  Vdbe *v;
65787  sqlite3 *db;
65788
65789  if( p==0 ) return SQLITE_MISUSE_BKPT;
65790  db = p->db;
65791  sqlite3_mutex_enter(db->mutex);
65792  v = (Vdbe*)p->pStmt;
65793
65794  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
65795    /* Request is out of range. Return a transient error. */
65796    rc = SQLITE_ERROR;
65797    sqlite3Error(db, SQLITE_ERROR, 0);
65798  } else if( v==0 ){
65799    /* If there is no statement handle, then the blob-handle has
65800    ** already been invalidated. Return SQLITE_ABORT in this case.
65801    */
65802    rc = SQLITE_ABORT;
65803  }else{
65804    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
65805    ** returned, clean-up the statement handle.
65806    */
65807    assert( db == v->db );
65808    sqlite3BtreeEnterCursor(p->pCsr);
65809    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
65810    sqlite3BtreeLeaveCursor(p->pCsr);
65811    if( rc==SQLITE_ABORT ){
65812      sqlite3VdbeFinalize(v);
65813      p->pStmt = 0;
65814    }else{
65815      db->errCode = rc;
65816      v->rc = rc;
65817    }
65818  }
65819  rc = sqlite3ApiExit(db, rc);
65820  sqlite3_mutex_leave(db->mutex);
65821  return rc;
65822}
65823
65824/*
65825** Read data from a blob handle.
65826*/
65827SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
65828  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
65829}
65830
65831/*
65832** Write data to a blob handle.
65833*/
65834SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
65835  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
65836}
65837
65838/*
65839** Query a blob handle for the size of the data.
65840**
65841** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
65842** so no mutex is required for access.
65843*/
65844SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
65845  Incrblob *p = (Incrblob *)pBlob;
65846  return p ? p->nByte : 0;
65847}
65848
65849#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
65850
65851/************** End of vdbeblob.c ********************************************/
65852/************** Begin file journal.c *****************************************/
65853/*
65854** 2007 August 22
65855**
65856** The author disclaims copyright to this source code.  In place of
65857** a legal notice, here is a blessing:
65858**
65859**    May you do good and not evil.
65860**    May you find forgiveness for yourself and forgive others.
65861**    May you share freely, never taking more than you give.
65862**
65863*************************************************************************
65864**
65865** This file implements a special kind of sqlite3_file object used
65866** by SQLite to create journal files if the atomic-write optimization
65867** is enabled.
65868**
65869** The distinctive characteristic of this sqlite3_file is that the
65870** actual on disk file is created lazily. When the file is created,
65871** the caller specifies a buffer size for an in-memory buffer to
65872** be used to service read() and write() requests. The actual file
65873** on disk is not created or populated until either:
65874**
65875**   1) The in-memory representation grows too large for the allocated
65876**      buffer, or
65877**   2) The sqlite3JournalCreate() function is called.
65878*/
65879#ifdef SQLITE_ENABLE_ATOMIC_WRITE
65880
65881
65882/*
65883** A JournalFile object is a subclass of sqlite3_file used by
65884** as an open file handle for journal files.
65885*/
65886struct JournalFile {
65887  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
65888  int nBuf;                       /* Size of zBuf[] in bytes */
65889  char *zBuf;                     /* Space to buffer journal writes */
65890  int iSize;                      /* Amount of zBuf[] currently used */
65891  int flags;                      /* xOpen flags */
65892  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
65893  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
65894  const char *zJournal;           /* Name of the journal file */
65895};
65896typedef struct JournalFile JournalFile;
65897
65898/*
65899** If it does not already exists, create and populate the on-disk file
65900** for JournalFile p.
65901*/
65902static int createFile(JournalFile *p){
65903  int rc = SQLITE_OK;
65904  if( !p->pReal ){
65905    sqlite3_file *pReal = (sqlite3_file *)&p[1];
65906    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
65907    if( rc==SQLITE_OK ){
65908      p->pReal = pReal;
65909      if( p->iSize>0 ){
65910        assert(p->iSize<=p->nBuf);
65911        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
65912      }
65913    }
65914  }
65915  return rc;
65916}
65917
65918/*
65919** Close the file.
65920*/
65921static int jrnlClose(sqlite3_file *pJfd){
65922  JournalFile *p = (JournalFile *)pJfd;
65923  if( p->pReal ){
65924    sqlite3OsClose(p->pReal);
65925  }
65926  sqlite3_free(p->zBuf);
65927  return SQLITE_OK;
65928}
65929
65930/*
65931** Read data from the file.
65932*/
65933static int jrnlRead(
65934  sqlite3_file *pJfd,    /* The journal file from which to read */
65935  void *zBuf,            /* Put the results here */
65936  int iAmt,              /* Number of bytes to read */
65937  sqlite_int64 iOfst     /* Begin reading at this offset */
65938){
65939  int rc = SQLITE_OK;
65940  JournalFile *p = (JournalFile *)pJfd;
65941  if( p->pReal ){
65942    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
65943  }else if( (iAmt+iOfst)>p->iSize ){
65944    rc = SQLITE_IOERR_SHORT_READ;
65945  }else{
65946    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
65947  }
65948  return rc;
65949}
65950
65951/*
65952** Write data to the file.
65953*/
65954static int jrnlWrite(
65955  sqlite3_file *pJfd,    /* The journal file into which to write */
65956  const void *zBuf,      /* Take data to be written from here */
65957  int iAmt,              /* Number of bytes to write */
65958  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
65959){
65960  int rc = SQLITE_OK;
65961  JournalFile *p = (JournalFile *)pJfd;
65962  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
65963    rc = createFile(p);
65964  }
65965  if( rc==SQLITE_OK ){
65966    if( p->pReal ){
65967      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
65968    }else{
65969      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
65970      if( p->iSize<(iOfst+iAmt) ){
65971        p->iSize = (iOfst+iAmt);
65972      }
65973    }
65974  }
65975  return rc;
65976}
65977
65978/*
65979** Truncate the file.
65980*/
65981static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
65982  int rc = SQLITE_OK;
65983  JournalFile *p = (JournalFile *)pJfd;
65984  if( p->pReal ){
65985    rc = sqlite3OsTruncate(p->pReal, size);
65986  }else if( size<p->iSize ){
65987    p->iSize = size;
65988  }
65989  return rc;
65990}
65991
65992/*
65993** Sync the file.
65994*/
65995static int jrnlSync(sqlite3_file *pJfd, int flags){
65996  int rc;
65997  JournalFile *p = (JournalFile *)pJfd;
65998  if( p->pReal ){
65999    rc = sqlite3OsSync(p->pReal, flags);
66000  }else{
66001    rc = SQLITE_OK;
66002  }
66003  return rc;
66004}
66005
66006/*
66007** Query the size of the file in bytes.
66008*/
66009static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
66010  int rc = SQLITE_OK;
66011  JournalFile *p = (JournalFile *)pJfd;
66012  if( p->pReal ){
66013    rc = sqlite3OsFileSize(p->pReal, pSize);
66014  }else{
66015    *pSize = (sqlite_int64) p->iSize;
66016  }
66017  return rc;
66018}
66019
66020/*
66021** Table of methods for JournalFile sqlite3_file object.
66022*/
66023static struct sqlite3_io_methods JournalFileMethods = {
66024  1,             /* iVersion */
66025  jrnlClose,     /* xClose */
66026  jrnlRead,      /* xRead */
66027  jrnlWrite,     /* xWrite */
66028  jrnlTruncate,  /* xTruncate */
66029  jrnlSync,      /* xSync */
66030  jrnlFileSize,  /* xFileSize */
66031  0,             /* xLock */
66032  0,             /* xUnlock */
66033  0,             /* xCheckReservedLock */
66034  0,             /* xFileControl */
66035  0,             /* xSectorSize */
66036  0,             /* xDeviceCharacteristics */
66037  0,             /* xShmMap */
66038  0,             /* xShmLock */
66039  0,             /* xShmBarrier */
66040  0              /* xShmUnmap */
66041};
66042
66043/*
66044** Open a journal file.
66045*/
66046SQLITE_PRIVATE int sqlite3JournalOpen(
66047  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
66048  const char *zName,         /* Name of the journal file */
66049  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
66050  int flags,                 /* Opening flags */
66051  int nBuf                   /* Bytes buffered before opening the file */
66052){
66053  JournalFile *p = (JournalFile *)pJfd;
66054  memset(p, 0, sqlite3JournalSize(pVfs));
66055  if( nBuf>0 ){
66056    p->zBuf = sqlite3MallocZero(nBuf);
66057    if( !p->zBuf ){
66058      return SQLITE_NOMEM;
66059    }
66060  }else{
66061    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
66062  }
66063  p->pMethod = &JournalFileMethods;
66064  p->nBuf = nBuf;
66065  p->flags = flags;
66066  p->zJournal = zName;
66067  p->pVfs = pVfs;
66068  return SQLITE_OK;
66069}
66070
66071/*
66072** If the argument p points to a JournalFile structure, and the underlying
66073** file has not yet been created, create it now.
66074*/
66075SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
66076  if( p->pMethods!=&JournalFileMethods ){
66077    return SQLITE_OK;
66078  }
66079  return createFile((JournalFile *)p);
66080}
66081
66082/*
66083** Return the number of bytes required to store a JournalFile that uses vfs
66084** pVfs to create the underlying on-disk files.
66085*/
66086SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
66087  return (pVfs->szOsFile+sizeof(JournalFile));
66088}
66089#endif
66090
66091/************** End of journal.c *********************************************/
66092/************** Begin file memjournal.c **************************************/
66093/*
66094** 2008 October 7
66095**
66096** The author disclaims copyright to this source code.  In place of
66097** a legal notice, here is a blessing:
66098**
66099**    May you do good and not evil.
66100**    May you find forgiveness for yourself and forgive others.
66101**    May you share freely, never taking more than you give.
66102**
66103*************************************************************************
66104**
66105** This file contains code use to implement an in-memory rollback journal.
66106** The in-memory rollback journal is used to journal transactions for
66107** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
66108*/
66109
66110/* Forward references to internal structures */
66111typedef struct MemJournal MemJournal;
66112typedef struct FilePoint FilePoint;
66113typedef struct FileChunk FileChunk;
66114
66115/* Space to hold the rollback journal is allocated in increments of
66116** this many bytes.
66117**
66118** The size chosen is a little less than a power of two.  That way,
66119** the FileChunk object will have a size that almost exactly fills
66120** a power-of-two allocation.  This mimimizes wasted space in power-of-two
66121** memory allocators.
66122*/
66123#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
66124
66125/* Macro to find the minimum of two numeric values.
66126*/
66127#ifndef MIN
66128# define MIN(x,y) ((x)<(y)?(x):(y))
66129#endif
66130
66131/*
66132** The rollback journal is composed of a linked list of these structures.
66133*/
66134struct FileChunk {
66135  FileChunk *pNext;               /* Next chunk in the journal */
66136  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
66137};
66138
66139/*
66140** An instance of this object serves as a cursor into the rollback journal.
66141** The cursor can be either for reading or writing.
66142*/
66143struct FilePoint {
66144  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
66145  FileChunk *pChunk;              /* Specific chunk into which cursor points */
66146};
66147
66148/*
66149** This subclass is a subclass of sqlite3_file.  Each open memory-journal
66150** is an instance of this class.
66151*/
66152struct MemJournal {
66153  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
66154  FileChunk *pFirst;              /* Head of in-memory chunk-list */
66155  FilePoint endpoint;             /* Pointer to the end of the file */
66156  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
66157};
66158
66159/*
66160** Read data from the in-memory journal file.  This is the implementation
66161** of the sqlite3_vfs.xRead method.
66162*/
66163static int memjrnlRead(
66164  sqlite3_file *pJfd,    /* The journal file from which to read */
66165  void *zBuf,            /* Put the results here */
66166  int iAmt,              /* Number of bytes to read */
66167  sqlite_int64 iOfst     /* Begin reading at this offset */
66168){
66169  MemJournal *p = (MemJournal *)pJfd;
66170  u8 *zOut = zBuf;
66171  int nRead = iAmt;
66172  int iChunkOffset;
66173  FileChunk *pChunk;
66174
66175  /* SQLite never tries to read past the end of a rollback journal file */
66176  assert( iOfst+iAmt<=p->endpoint.iOffset );
66177
66178  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
66179    sqlite3_int64 iOff = 0;
66180    for(pChunk=p->pFirst;
66181        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
66182        pChunk=pChunk->pNext
66183    ){
66184      iOff += JOURNAL_CHUNKSIZE;
66185    }
66186  }else{
66187    pChunk = p->readpoint.pChunk;
66188  }
66189
66190  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
66191  do {
66192    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
66193    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
66194    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
66195    zOut += nCopy;
66196    nRead -= iSpace;
66197    iChunkOffset = 0;
66198  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
66199  p->readpoint.iOffset = iOfst+iAmt;
66200  p->readpoint.pChunk = pChunk;
66201
66202  return SQLITE_OK;
66203}
66204
66205/*
66206** Write data to the file.
66207*/
66208static int memjrnlWrite(
66209  sqlite3_file *pJfd,    /* The journal file into which to write */
66210  const void *zBuf,      /* Take data to be written from here */
66211  int iAmt,              /* Number of bytes to write */
66212  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
66213){
66214  MemJournal *p = (MemJournal *)pJfd;
66215  int nWrite = iAmt;
66216  u8 *zWrite = (u8 *)zBuf;
66217
66218  /* An in-memory journal file should only ever be appended to. Random
66219  ** access writes are not required by sqlite.
66220  */
66221  assert( iOfst==p->endpoint.iOffset );
66222  UNUSED_PARAMETER(iOfst);
66223
66224  while( nWrite>0 ){
66225    FileChunk *pChunk = p->endpoint.pChunk;
66226    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
66227    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
66228
66229    if( iChunkOffset==0 ){
66230      /* New chunk is required to extend the file. */
66231      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
66232      if( !pNew ){
66233        return SQLITE_IOERR_NOMEM;
66234      }
66235      pNew->pNext = 0;
66236      if( pChunk ){
66237        assert( p->pFirst );
66238        pChunk->pNext = pNew;
66239      }else{
66240        assert( !p->pFirst );
66241        p->pFirst = pNew;
66242      }
66243      p->endpoint.pChunk = pNew;
66244    }
66245
66246    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
66247    zWrite += iSpace;
66248    nWrite -= iSpace;
66249    p->endpoint.iOffset += iSpace;
66250  }
66251
66252  return SQLITE_OK;
66253}
66254
66255/*
66256** Truncate the file.
66257*/
66258static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
66259  MemJournal *p = (MemJournal *)pJfd;
66260  FileChunk *pChunk;
66261  assert(size==0);
66262  UNUSED_PARAMETER(size);
66263  pChunk = p->pFirst;
66264  while( pChunk ){
66265    FileChunk *pTmp = pChunk;
66266    pChunk = pChunk->pNext;
66267    sqlite3_free(pTmp);
66268  }
66269  sqlite3MemJournalOpen(pJfd);
66270  return SQLITE_OK;
66271}
66272
66273/*
66274** Close the file.
66275*/
66276static int memjrnlClose(sqlite3_file *pJfd){
66277  memjrnlTruncate(pJfd, 0);
66278  return SQLITE_OK;
66279}
66280
66281
66282/*
66283** Sync the file.
66284**
66285** Syncing an in-memory journal is a no-op.  And, in fact, this routine
66286** is never called in a working implementation.  This implementation
66287** exists purely as a contingency, in case some malfunction in some other
66288** part of SQLite causes Sync to be called by mistake.
66289*/
66290static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
66291  UNUSED_PARAMETER2(NotUsed, NotUsed2);
66292  return SQLITE_OK;
66293}
66294
66295/*
66296** Query the size of the file in bytes.
66297*/
66298static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
66299  MemJournal *p = (MemJournal *)pJfd;
66300  *pSize = (sqlite_int64) p->endpoint.iOffset;
66301  return SQLITE_OK;
66302}
66303
66304/*
66305** Table of methods for MemJournal sqlite3_file object.
66306*/
66307static const struct sqlite3_io_methods MemJournalMethods = {
66308  1,                /* iVersion */
66309  memjrnlClose,     /* xClose */
66310  memjrnlRead,      /* xRead */
66311  memjrnlWrite,     /* xWrite */
66312  memjrnlTruncate,  /* xTruncate */
66313  memjrnlSync,      /* xSync */
66314  memjrnlFileSize,  /* xFileSize */
66315  0,                /* xLock */
66316  0,                /* xUnlock */
66317  0,                /* xCheckReservedLock */
66318  0,                /* xFileControl */
66319  0,                /* xSectorSize */
66320  0,                /* xDeviceCharacteristics */
66321  0,                /* xShmMap */
66322  0,                /* xShmLock */
66323  0,                /* xShmBarrier */
66324  0                 /* xShmUnlock */
66325};
66326
66327/*
66328** Open a journal file.
66329*/
66330SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
66331  MemJournal *p = (MemJournal *)pJfd;
66332  assert( EIGHT_BYTE_ALIGNMENT(p) );
66333  memset(p, 0, sqlite3MemJournalSize());
66334  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
66335}
66336
66337/*
66338** Return true if the file-handle passed as an argument is
66339** an in-memory journal
66340*/
66341SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
66342  return pJfd->pMethods==&MemJournalMethods;
66343}
66344
66345/*
66346** Return the number of bytes required to store a MemJournal that uses vfs
66347** pVfs to create the underlying on-disk files.
66348*/
66349SQLITE_PRIVATE int sqlite3MemJournalSize(void){
66350  return sizeof(MemJournal);
66351}
66352
66353/************** End of memjournal.c ******************************************/
66354/************** Begin file walker.c ******************************************/
66355/*
66356** 2008 August 16
66357**
66358** The author disclaims copyright to this source code.  In place of
66359** a legal notice, here is a blessing:
66360**
66361**    May you do good and not evil.
66362**    May you find forgiveness for yourself and forgive others.
66363**    May you share freely, never taking more than you give.
66364**
66365*************************************************************************
66366** This file contains routines used for walking the parser tree for
66367** an SQL statement.
66368*/
66369
66370
66371/*
66372** Walk an expression tree.  Invoke the callback once for each node
66373** of the expression, while decending.  (In other words, the callback
66374** is invoked before visiting children.)
66375**
66376** The return value from the callback should be one of the WRC_*
66377** constants to specify how to proceed with the walk.
66378**
66379**    WRC_Continue      Continue descending down the tree.
66380**
66381**    WRC_Prune         Do not descend into child nodes.  But allow
66382**                      the walk to continue with sibling nodes.
66383**
66384**    WRC_Abort         Do no more callbacks.  Unwind the stack and
66385**                      return the top-level walk call.
66386**
66387** The return value from this routine is WRC_Abort to abandon the tree walk
66388** and WRC_Continue to continue.
66389*/
66390SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
66391  int rc;
66392  if( pExpr==0 ) return WRC_Continue;
66393  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
66394  testcase( ExprHasProperty(pExpr, EP_Reduced) );
66395  rc = pWalker->xExprCallback(pWalker, pExpr);
66396  if( rc==WRC_Continue
66397              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
66398    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
66399    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
66400    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66401      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
66402    }else{
66403      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
66404    }
66405  }
66406  return rc & WRC_Abort;
66407}
66408
66409/*
66410** Call sqlite3WalkExpr() for every expression in list p or until
66411** an abort request is seen.
66412*/
66413SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
66414  int i;
66415  struct ExprList_item *pItem;
66416  if( p ){
66417    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
66418      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
66419    }
66420  }
66421  return WRC_Continue;
66422}
66423
66424/*
66425** Walk all expressions associated with SELECT statement p.  Do
66426** not invoke the SELECT callback on p, but do (of course) invoke
66427** any expr callbacks and SELECT callbacks that come from subqueries.
66428** Return WRC_Abort or WRC_Continue.
66429*/
66430SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
66431  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
66432  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
66433  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
66434  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
66435  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
66436  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
66437  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
66438  return WRC_Continue;
66439}
66440
66441/*
66442** Walk the parse trees associated with all subqueries in the
66443** FROM clause of SELECT statement p.  Do not invoke the select
66444** callback on p, but do invoke it on each FROM clause subquery
66445** and on any subqueries further down in the tree.  Return
66446** WRC_Abort or WRC_Continue;
66447*/
66448SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
66449  SrcList *pSrc;
66450  int i;
66451  struct SrcList_item *pItem;
66452
66453  pSrc = p->pSrc;
66454  if( ALWAYS(pSrc) ){
66455    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
66456      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
66457        return WRC_Abort;
66458      }
66459    }
66460  }
66461  return WRC_Continue;
66462}
66463
66464/*
66465** Call sqlite3WalkExpr() for every expression in Select statement p.
66466** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
66467** on the compound select chain, p->pPrior.
66468**
66469** Return WRC_Continue under normal conditions.  Return WRC_Abort if
66470** there is an abort request.
66471**
66472** If the Walker does not have an xSelectCallback() then this routine
66473** is a no-op returning WRC_Continue.
66474*/
66475SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
66476  int rc;
66477  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
66478  rc = WRC_Continue;
66479  while( p  ){
66480    rc = pWalker->xSelectCallback(pWalker, p);
66481    if( rc ) break;
66482    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
66483    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
66484    p = p->pPrior;
66485  }
66486  return rc & WRC_Abort;
66487}
66488
66489/************** End of walker.c **********************************************/
66490/************** Begin file resolve.c *****************************************/
66491/*
66492** 2008 August 18
66493**
66494** The author disclaims copyright to this source code.  In place of
66495** a legal notice, here is a blessing:
66496**
66497**    May you do good and not evil.
66498**    May you find forgiveness for yourself and forgive others.
66499**    May you share freely, never taking more than you give.
66500**
66501*************************************************************************
66502**
66503** This file contains routines used for walking the parser tree and
66504** resolve all identifiers by associating them with a particular
66505** table and column.
66506*/
66507
66508/*
66509** Turn the pExpr expression into an alias for the iCol-th column of the
66510** result set in pEList.
66511**
66512** If the result set column is a simple column reference, then this routine
66513** makes an exact copy.  But for any other kind of expression, this
66514** routine make a copy of the result set column as the argument to the
66515** TK_AS operator.  The TK_AS operator causes the expression to be
66516** evaluated just once and then reused for each alias.
66517**
66518** The reason for suppressing the TK_AS term when the expression is a simple
66519** column reference is so that the column reference will be recognized as
66520** usable by indices within the WHERE clause processing logic.
66521**
66522** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
66523** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
66524**
66525**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
66526**
66527** Is equivalent to:
66528**
66529**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
66530**
66531** The result of random()%5 in the GROUP BY clause is probably different
66532** from the result in the result-set.  We might fix this someday.  Or
66533** then again, we might not...
66534*/
66535static void resolveAlias(
66536  Parse *pParse,         /* Parsing context */
66537  ExprList *pEList,      /* A result set */
66538  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
66539  Expr *pExpr,           /* Transform this into an alias to the result set */
66540  const char *zType      /* "GROUP" or "ORDER" or "" */
66541){
66542  Expr *pOrig;           /* The iCol-th column of the result set */
66543  Expr *pDup;            /* Copy of pOrig */
66544  sqlite3 *db;           /* The database connection */
66545
66546  assert( iCol>=0 && iCol<pEList->nExpr );
66547  pOrig = pEList->a[iCol].pExpr;
66548  assert( pOrig!=0 );
66549  assert( pOrig->flags & EP_Resolved );
66550  db = pParse->db;
66551  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
66552    pDup = sqlite3ExprDup(db, pOrig, 0);
66553    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
66554    if( pDup==0 ) return;
66555    if( pEList->a[iCol].iAlias==0 ){
66556      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
66557    }
66558    pDup->iTable = pEList->a[iCol].iAlias;
66559  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
66560    pDup = sqlite3ExprDup(db, pOrig, 0);
66561    if( pDup==0 ) return;
66562  }else{
66563    char *zToken = pOrig->u.zToken;
66564    assert( zToken!=0 );
66565    pOrig->u.zToken = 0;
66566    pDup = sqlite3ExprDup(db, pOrig, 0);
66567    pOrig->u.zToken = zToken;
66568    if( pDup==0 ) return;
66569    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
66570    pDup->flags2 |= EP2_MallocedToken;
66571    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
66572  }
66573  if( pExpr->flags & EP_ExpCollate ){
66574    pDup->pColl = pExpr->pColl;
66575    pDup->flags |= EP_ExpCollate;
66576  }
66577
66578  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
66579  ** prevents ExprDelete() from deleting the Expr structure itself,
66580  ** allowing it to be repopulated by the memcpy() on the following line.
66581  */
66582  ExprSetProperty(pExpr, EP_Static);
66583  sqlite3ExprDelete(db, pExpr);
66584  memcpy(pExpr, pDup, sizeof(*pExpr));
66585  sqlite3DbFree(db, pDup);
66586}
66587
66588/*
66589** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
66590** that name in the set of source tables in pSrcList and make the pExpr
66591** expression node refer back to that source column.  The following changes
66592** are made to pExpr:
66593**
66594**    pExpr->iDb           Set the index in db->aDb[] of the database X
66595**                         (even if X is implied).
66596**    pExpr->iTable        Set to the cursor number for the table obtained
66597**                         from pSrcList.
66598**    pExpr->pTab          Points to the Table structure of X.Y (even if
66599**                         X and/or Y are implied.)
66600**    pExpr->iColumn       Set to the column number within the table.
66601**    pExpr->op            Set to TK_COLUMN.
66602**    pExpr->pLeft         Any expression this points to is deleted
66603**    pExpr->pRight        Any expression this points to is deleted.
66604**
66605** The zDb variable is the name of the database (the "X").  This value may be
66606** NULL meaning that name is of the form Y.Z or Z.  Any available database
66607** can be used.  The zTable variable is the name of the table (the "Y").  This
66608** value can be NULL if zDb is also NULL.  If zTable is NULL it
66609** means that the form of the name is Z and that columns from any table
66610** can be used.
66611**
66612** If the name cannot be resolved unambiguously, leave an error message
66613** in pParse and return WRC_Abort.  Return WRC_Prune on success.
66614*/
66615static int lookupName(
66616  Parse *pParse,       /* The parsing context */
66617  const char *zDb,     /* Name of the database containing table, or NULL */
66618  const char *zTab,    /* Name of table containing column, or NULL */
66619  const char *zCol,    /* Name of the column. */
66620  NameContext *pNC,    /* The name context used to resolve the name */
66621  Expr *pExpr          /* Make this EXPR node point to the selected column */
66622){
66623  int i, j;            /* Loop counters */
66624  int cnt = 0;                      /* Number of matching column names */
66625  int cntTab = 0;                   /* Number of matching table names */
66626  sqlite3 *db = pParse->db;         /* The database connection */
66627  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
66628  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
66629  NameContext *pTopNC = pNC;        /* First namecontext in the list */
66630  Schema *pSchema = 0;              /* Schema of the expression */
66631  int isTrigger = 0;
66632
66633  assert( pNC );     /* the name context cannot be NULL. */
66634  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
66635  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
66636
66637  /* Initialize the node to no-match */
66638  pExpr->iTable = -1;
66639  pExpr->pTab = 0;
66640  ExprSetIrreducible(pExpr);
66641
66642  /* Start at the inner-most context and move outward until a match is found */
66643  while( pNC && cnt==0 ){
66644    ExprList *pEList;
66645    SrcList *pSrcList = pNC->pSrcList;
66646
66647    if( pSrcList ){
66648      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
66649        Table *pTab;
66650        int iDb;
66651        Column *pCol;
66652
66653        pTab = pItem->pTab;
66654        assert( pTab!=0 && pTab->zName!=0 );
66655        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
66656        assert( pTab->nCol>0 );
66657        if( zTab ){
66658          if( pItem->zAlias ){
66659            char *zTabName = pItem->zAlias;
66660            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
66661          }else{
66662            char *zTabName = pTab->zName;
66663            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
66664              continue;
66665            }
66666            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
66667              continue;
66668            }
66669          }
66670        }
66671        if( 0==(cntTab++) ){
66672          pExpr->iTable = pItem->iCursor;
66673          pExpr->pTab = pTab;
66674          pSchema = pTab->pSchema;
66675          pMatch = pItem;
66676        }
66677        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
66678          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
66679            IdList *pUsing;
66680            cnt++;
66681            pExpr->iTable = pItem->iCursor;
66682            pExpr->pTab = pTab;
66683            pMatch = pItem;
66684            pSchema = pTab->pSchema;
66685            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
66686            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
66687            if( i<pSrcList->nSrc-1 ){
66688              if( pItem[1].jointype & JT_NATURAL ){
66689                /* If this match occurred in the left table of a natural join,
66690                ** then skip the right table to avoid a duplicate match */
66691                pItem++;
66692                i++;
66693              }else if( (pUsing = pItem[1].pUsing)!=0 ){
66694                /* If this match occurs on a column that is in the USING clause
66695                ** of a join, skip the search of the right table of the join
66696                ** to avoid a duplicate match there. */
66697                int k;
66698                for(k=0; k<pUsing->nId; k++){
66699                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
66700                    pItem++;
66701                    i++;
66702                    break;
66703                  }
66704                }
66705              }
66706            }
66707            break;
66708          }
66709        }
66710      }
66711    }
66712
66713#ifndef SQLITE_OMIT_TRIGGER
66714    /* If we have not already resolved the name, then maybe
66715    ** it is a new.* or old.* trigger argument reference
66716    */
66717    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
66718      int op = pParse->eTriggerOp;
66719      Table *pTab = 0;
66720      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
66721      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
66722        pExpr->iTable = 1;
66723        pTab = pParse->pTriggerTab;
66724      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
66725        pExpr->iTable = 0;
66726        pTab = pParse->pTriggerTab;
66727      }
66728
66729      if( pTab ){
66730        int iCol;
66731        pSchema = pTab->pSchema;
66732        cntTab++;
66733        for(iCol=0; iCol<pTab->nCol; iCol++){
66734          Column *pCol = &pTab->aCol[iCol];
66735          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
66736            if( iCol==pTab->iPKey ){
66737              iCol = -1;
66738            }
66739            break;
66740          }
66741        }
66742        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
66743          iCol = -1;        /* IMP: R-44911-55124 */
66744        }
66745        if( iCol<pTab->nCol ){
66746          cnt++;
66747          if( iCol<0 ){
66748            pExpr->affinity = SQLITE_AFF_INTEGER;
66749          }else if( pExpr->iTable==0 ){
66750            testcase( iCol==31 );
66751            testcase( iCol==32 );
66752            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
66753          }else{
66754            testcase( iCol==31 );
66755            testcase( iCol==32 );
66756            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
66757          }
66758          pExpr->iColumn = (i16)iCol;
66759          pExpr->pTab = pTab;
66760          isTrigger = 1;
66761        }
66762      }
66763    }
66764#endif /* !defined(SQLITE_OMIT_TRIGGER) */
66765
66766    /*
66767    ** Perhaps the name is a reference to the ROWID
66768    */
66769    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
66770      cnt = 1;
66771      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
66772      pExpr->affinity = SQLITE_AFF_INTEGER;
66773    }
66774
66775    /*
66776    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
66777    ** might refer to an result-set alias.  This happens, for example, when
66778    ** we are resolving names in the WHERE clause of the following command:
66779    **
66780    **     SELECT a+b AS x FROM table WHERE x<10;
66781    **
66782    ** In cases like this, replace pExpr with a copy of the expression that
66783    ** forms the result set entry ("a+b" in the example) and return immediately.
66784    ** Note that the expression in the result set should have already been
66785    ** resolved by the time the WHERE clause is resolved.
66786    */
66787    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
66788      for(j=0; j<pEList->nExpr; j++){
66789        char *zAs = pEList->a[j].zName;
66790        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
66791          Expr *pOrig;
66792          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
66793          assert( pExpr->x.pList==0 );
66794          assert( pExpr->x.pSelect==0 );
66795          pOrig = pEList->a[j].pExpr;
66796          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
66797            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
66798            return WRC_Abort;
66799          }
66800          resolveAlias(pParse, pEList, j, pExpr, "");
66801          cnt = 1;
66802          pMatch = 0;
66803          assert( zTab==0 && zDb==0 );
66804          goto lookupname_end;
66805        }
66806      }
66807    }
66808
66809    /* Advance to the next name context.  The loop will exit when either
66810    ** we have a match (cnt>0) or when we run out of name contexts.
66811    */
66812    if( cnt==0 ){
66813      pNC = pNC->pNext;
66814    }
66815  }
66816
66817  /*
66818  ** If X and Y are NULL (in other words if only the column name Z is
66819  ** supplied) and the value of Z is enclosed in double-quotes, then
66820  ** Z is a string literal if it doesn't match any column names.  In that
66821  ** case, we need to return right away and not make any changes to
66822  ** pExpr.
66823  **
66824  ** Because no reference was made to outer contexts, the pNC->nRef
66825  ** fields are not changed in any context.
66826  */
66827  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
66828    pExpr->op = TK_STRING;
66829    pExpr->pTab = 0;
66830    return WRC_Prune;
66831  }
66832
66833  /*
66834  ** cnt==0 means there was not match.  cnt>1 means there were two or
66835  ** more matches.  Either way, we have an error.
66836  */
66837  if( cnt!=1 ){
66838    const char *zErr;
66839    zErr = cnt==0 ? "no such column" : "ambiguous column name";
66840    if( zDb ){
66841      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
66842    }else if( zTab ){
66843      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
66844    }else{
66845      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
66846    }
66847    pParse->checkSchema = 1;
66848    pTopNC->nErr++;
66849  }
66850
66851  /* If a column from a table in pSrcList is referenced, then record
66852  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
66853  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
66854  ** column number is greater than the number of bits in the bitmask
66855  ** then set the high-order bit of the bitmask.
66856  */
66857  if( pExpr->iColumn>=0 && pMatch!=0 ){
66858    int n = pExpr->iColumn;
66859    testcase( n==BMS-1 );
66860    if( n>=BMS ){
66861      n = BMS-1;
66862    }
66863    assert( pMatch->iCursor==pExpr->iTable );
66864    pMatch->colUsed |= ((Bitmask)1)<<n;
66865  }
66866
66867  /* Clean up and return
66868  */
66869  sqlite3ExprDelete(db, pExpr->pLeft);
66870  pExpr->pLeft = 0;
66871  sqlite3ExprDelete(db, pExpr->pRight);
66872  pExpr->pRight = 0;
66873  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
66874lookupname_end:
66875  if( cnt==1 ){
66876    assert( pNC!=0 );
66877    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
66878    /* Increment the nRef value on all name contexts from TopNC up to
66879    ** the point where the name matched. */
66880    for(;;){
66881      assert( pTopNC!=0 );
66882      pTopNC->nRef++;
66883      if( pTopNC==pNC ) break;
66884      pTopNC = pTopNC->pNext;
66885    }
66886    return WRC_Prune;
66887  } else {
66888    return WRC_Abort;
66889  }
66890}
66891
66892/*
66893** Allocate and return a pointer to an expression to load the column iCol
66894** from datasource iSrc in SrcList pSrc.
66895*/
66896SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
66897  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
66898  if( p ){
66899    struct SrcList_item *pItem = &pSrc->a[iSrc];
66900    p->pTab = pItem->pTab;
66901    p->iTable = pItem->iCursor;
66902    if( p->pTab->iPKey==iCol ){
66903      p->iColumn = -1;
66904    }else{
66905      p->iColumn = (ynVar)iCol;
66906      testcase( iCol==BMS );
66907      testcase( iCol==BMS-1 );
66908      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
66909    }
66910    ExprSetProperty(p, EP_Resolved);
66911  }
66912  return p;
66913}
66914
66915/*
66916** This routine is callback for sqlite3WalkExpr().
66917**
66918** Resolve symbolic names into TK_COLUMN operators for the current
66919** node in the expression tree.  Return 0 to continue the search down
66920** the tree or 2 to abort the tree walk.
66921**
66922** This routine also does error checking and name resolution for
66923** function names.  The operator for aggregate functions is changed
66924** to TK_AGG_FUNCTION.
66925*/
66926static int resolveExprStep(Walker *pWalker, Expr *pExpr){
66927  NameContext *pNC;
66928  Parse *pParse;
66929
66930  pNC = pWalker->u.pNC;
66931  assert( pNC!=0 );
66932  pParse = pNC->pParse;
66933  assert( pParse==pWalker->pParse );
66934
66935  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
66936  ExprSetProperty(pExpr, EP_Resolved);
66937#ifndef NDEBUG
66938  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
66939    SrcList *pSrcList = pNC->pSrcList;
66940    int i;
66941    for(i=0; i<pNC->pSrcList->nSrc; i++){
66942      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
66943    }
66944  }
66945#endif
66946  switch( pExpr->op ){
66947
66948#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
66949    /* The special operator TK_ROW means use the rowid for the first
66950    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
66951    ** clause processing on UPDATE and DELETE statements.
66952    */
66953    case TK_ROW: {
66954      SrcList *pSrcList = pNC->pSrcList;
66955      struct SrcList_item *pItem;
66956      assert( pSrcList && pSrcList->nSrc==1 );
66957      pItem = pSrcList->a;
66958      pExpr->op = TK_COLUMN;
66959      pExpr->pTab = pItem->pTab;
66960      pExpr->iTable = pItem->iCursor;
66961      pExpr->iColumn = -1;
66962      pExpr->affinity = SQLITE_AFF_INTEGER;
66963      break;
66964    }
66965#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
66966
66967    /* A lone identifier is the name of a column.
66968    */
66969    case TK_ID: {
66970      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
66971    }
66972
66973    /* A table name and column name:     ID.ID
66974    ** Or a database, table and column:  ID.ID.ID
66975    */
66976    case TK_DOT: {
66977      const char *zColumn;
66978      const char *zTable;
66979      const char *zDb;
66980      Expr *pRight;
66981
66982      /* if( pSrcList==0 ) break; */
66983      pRight = pExpr->pRight;
66984      if( pRight->op==TK_ID ){
66985        zDb = 0;
66986        zTable = pExpr->pLeft->u.zToken;
66987        zColumn = pRight->u.zToken;
66988      }else{
66989        assert( pRight->op==TK_DOT );
66990        zDb = pExpr->pLeft->u.zToken;
66991        zTable = pRight->pLeft->u.zToken;
66992        zColumn = pRight->pRight->u.zToken;
66993      }
66994      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
66995    }
66996
66997    /* Resolve function names
66998    */
66999    case TK_CONST_FUNC:
67000    case TK_FUNCTION: {
67001      ExprList *pList = pExpr->x.pList;    /* The argument list */
67002      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
67003      int no_such_func = 0;       /* True if no such function exists */
67004      int wrong_num_args = 0;     /* True if wrong number of arguments */
67005      int is_agg = 0;             /* True if is an aggregate function */
67006      int auth;                   /* Authorization to use the function */
67007      int nId;                    /* Number of characters in function name */
67008      const char *zId;            /* The function name. */
67009      FuncDef *pDef;              /* Information about the function */
67010      u8 enc = ENC(pParse->db);   /* The database encoding */
67011
67012      testcase( pExpr->op==TK_CONST_FUNC );
67013      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
67014      zId = pExpr->u.zToken;
67015      nId = sqlite3Strlen30(zId);
67016      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
67017      if( pDef==0 ){
67018        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
67019        if( pDef==0 ){
67020          no_such_func = 1;
67021        }else{
67022          wrong_num_args = 1;
67023        }
67024      }else{
67025        is_agg = pDef->xFunc==0;
67026      }
67027#ifndef SQLITE_OMIT_AUTHORIZATION
67028      if( pDef ){
67029        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
67030        if( auth!=SQLITE_OK ){
67031          if( auth==SQLITE_DENY ){
67032            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
67033                                    pDef->zName);
67034            pNC->nErr++;
67035          }
67036          pExpr->op = TK_NULL;
67037          return WRC_Prune;
67038        }
67039      }
67040#endif
67041      if( is_agg && !pNC->allowAgg ){
67042        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
67043        pNC->nErr++;
67044        is_agg = 0;
67045      }else if( no_such_func ){
67046        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
67047        pNC->nErr++;
67048      }else if( wrong_num_args ){
67049        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
67050             nId, zId);
67051        pNC->nErr++;
67052      }
67053      if( is_agg ){
67054        pExpr->op = TK_AGG_FUNCTION;
67055        pNC->hasAgg = 1;
67056      }
67057      if( is_agg ) pNC->allowAgg = 0;
67058      sqlite3WalkExprList(pWalker, pList);
67059      if( is_agg ) pNC->allowAgg = 1;
67060      /* FIX ME:  Compute pExpr->affinity based on the expected return
67061      ** type of the function
67062      */
67063      return WRC_Prune;
67064    }
67065#ifndef SQLITE_OMIT_SUBQUERY
67066    case TK_SELECT:
67067    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
67068#endif
67069    case TK_IN: {
67070      testcase( pExpr->op==TK_IN );
67071      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
67072        int nRef = pNC->nRef;
67073#ifndef SQLITE_OMIT_CHECK
67074        if( pNC->isCheck ){
67075          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
67076        }
67077#endif
67078        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
67079        assert( pNC->nRef>=nRef );
67080        if( nRef!=pNC->nRef ){
67081          ExprSetProperty(pExpr, EP_VarSelect);
67082        }
67083      }
67084      break;
67085    }
67086#ifndef SQLITE_OMIT_CHECK
67087    case TK_VARIABLE: {
67088      if( pNC->isCheck ){
67089        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
67090      }
67091      break;
67092    }
67093#endif
67094  }
67095  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
67096}
67097
67098/*
67099** pEList is a list of expressions which are really the result set of the
67100** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
67101** This routine checks to see if pE is a simple identifier which corresponds
67102** to the AS-name of one of the terms of the expression list.  If it is,
67103** this routine return an integer between 1 and N where N is the number of
67104** elements in pEList, corresponding to the matching entry.  If there is
67105** no match, or if pE is not a simple identifier, then this routine
67106** return 0.
67107**
67108** pEList has been resolved.  pE has not.
67109*/
67110static int resolveAsName(
67111  Parse *pParse,     /* Parsing context for error messages */
67112  ExprList *pEList,  /* List of expressions to scan */
67113  Expr *pE           /* Expression we are trying to match */
67114){
67115  int i;             /* Loop counter */
67116
67117  UNUSED_PARAMETER(pParse);
67118
67119  if( pE->op==TK_ID ){
67120    char *zCol = pE->u.zToken;
67121    for(i=0; i<pEList->nExpr; i++){
67122      char *zAs = pEList->a[i].zName;
67123      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
67124        return i+1;
67125      }
67126    }
67127  }
67128  return 0;
67129}
67130
67131/*
67132** pE is a pointer to an expression which is a single term in the
67133** ORDER BY of a compound SELECT.  The expression has not been
67134** name resolved.
67135**
67136** At the point this routine is called, we already know that the
67137** ORDER BY term is not an integer index into the result set.  That
67138** case is handled by the calling routine.
67139**
67140** Attempt to match pE against result set columns in the left-most
67141** SELECT statement.  Return the index i of the matching column,
67142** as an indication to the caller that it should sort by the i-th column.
67143** The left-most column is 1.  In other words, the value returned is the
67144** same integer value that would be used in the SQL statement to indicate
67145** the column.
67146**
67147** If there is no match, return 0.  Return -1 if an error occurs.
67148*/
67149static int resolveOrderByTermToExprList(
67150  Parse *pParse,     /* Parsing context for error messages */
67151  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
67152  Expr *pE           /* The specific ORDER BY term */
67153){
67154  int i;             /* Loop counter */
67155  ExprList *pEList;  /* The columns of the result set */
67156  NameContext nc;    /* Name context for resolving pE */
67157  sqlite3 *db;       /* Database connection */
67158  int rc;            /* Return code from subprocedures */
67159  u8 savedSuppErr;   /* Saved value of db->suppressErr */
67160
67161  assert( sqlite3ExprIsInteger(pE, &i)==0 );
67162  pEList = pSelect->pEList;
67163
67164  /* Resolve all names in the ORDER BY term expression
67165  */
67166  memset(&nc, 0, sizeof(nc));
67167  nc.pParse = pParse;
67168  nc.pSrcList = pSelect->pSrc;
67169  nc.pEList = pEList;
67170  nc.allowAgg = 1;
67171  nc.nErr = 0;
67172  db = pParse->db;
67173  savedSuppErr = db->suppressErr;
67174  db->suppressErr = 1;
67175  rc = sqlite3ResolveExprNames(&nc, pE);
67176  db->suppressErr = savedSuppErr;
67177  if( rc ) return 0;
67178
67179  /* Try to match the ORDER BY expression against an expression
67180  ** in the result set.  Return an 1-based index of the matching
67181  ** result-set entry.
67182  */
67183  for(i=0; i<pEList->nExpr; i++){
67184    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
67185      return i+1;
67186    }
67187  }
67188
67189  /* If no match, return 0. */
67190  return 0;
67191}
67192
67193/*
67194** Generate an ORDER BY or GROUP BY term out-of-range error.
67195*/
67196static void resolveOutOfRangeError(
67197  Parse *pParse,         /* The error context into which to write the error */
67198  const char *zType,     /* "ORDER" or "GROUP" */
67199  int i,                 /* The index (1-based) of the term out of range */
67200  int mx                 /* Largest permissible value of i */
67201){
67202  sqlite3ErrorMsg(pParse,
67203    "%r %s BY term out of range - should be "
67204    "between 1 and %d", i, zType, mx);
67205}
67206
67207/*
67208** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
67209** each term of the ORDER BY clause is a constant integer between 1
67210** and N where N is the number of columns in the compound SELECT.
67211**
67212** ORDER BY terms that are already an integer between 1 and N are
67213** unmodified.  ORDER BY terms that are integers outside the range of
67214** 1 through N generate an error.  ORDER BY terms that are expressions
67215** are matched against result set expressions of compound SELECT
67216** beginning with the left-most SELECT and working toward the right.
67217** At the first match, the ORDER BY expression is transformed into
67218** the integer column number.
67219**
67220** Return the number of errors seen.
67221*/
67222static int resolveCompoundOrderBy(
67223  Parse *pParse,        /* Parsing context.  Leave error messages here */
67224  Select *pSelect       /* The SELECT statement containing the ORDER BY */
67225){
67226  int i;
67227  ExprList *pOrderBy;
67228  ExprList *pEList;
67229  sqlite3 *db;
67230  int moreToDo = 1;
67231
67232  pOrderBy = pSelect->pOrderBy;
67233  if( pOrderBy==0 ) return 0;
67234  db = pParse->db;
67235#if SQLITE_MAX_COLUMN
67236  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67237    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
67238    return 1;
67239  }
67240#endif
67241  for(i=0; i<pOrderBy->nExpr; i++){
67242    pOrderBy->a[i].done = 0;
67243  }
67244  pSelect->pNext = 0;
67245  while( pSelect->pPrior ){
67246    pSelect->pPrior->pNext = pSelect;
67247    pSelect = pSelect->pPrior;
67248  }
67249  while( pSelect && moreToDo ){
67250    struct ExprList_item *pItem;
67251    moreToDo = 0;
67252    pEList = pSelect->pEList;
67253    assert( pEList!=0 );
67254    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
67255      int iCol = -1;
67256      Expr *pE, *pDup;
67257      if( pItem->done ) continue;
67258      pE = pItem->pExpr;
67259      if( sqlite3ExprIsInteger(pE, &iCol) ){
67260        if( iCol<=0 || iCol>pEList->nExpr ){
67261          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
67262          return 1;
67263        }
67264      }else{
67265        iCol = resolveAsName(pParse, pEList, pE);
67266        if( iCol==0 ){
67267          pDup = sqlite3ExprDup(db, pE, 0);
67268          if( !db->mallocFailed ){
67269            assert(pDup);
67270            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
67271          }
67272          sqlite3ExprDelete(db, pDup);
67273        }
67274      }
67275      if( iCol>0 ){
67276        CollSeq *pColl = pE->pColl;
67277        int flags = pE->flags & EP_ExpCollate;
67278        sqlite3ExprDelete(db, pE);
67279        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
67280        if( pE==0 ) return 1;
67281        pE->pColl = pColl;
67282        pE->flags |= EP_IntValue | flags;
67283        pE->u.iValue = iCol;
67284        pItem->iCol = (u16)iCol;
67285        pItem->done = 1;
67286      }else{
67287        moreToDo = 1;
67288      }
67289    }
67290    pSelect = pSelect->pNext;
67291  }
67292  for(i=0; i<pOrderBy->nExpr; i++){
67293    if( pOrderBy->a[i].done==0 ){
67294      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
67295            "column in the result set", i+1);
67296      return 1;
67297    }
67298  }
67299  return 0;
67300}
67301
67302/*
67303** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
67304** the SELECT statement pSelect.  If any term is reference to a
67305** result set expression (as determined by the ExprList.a.iCol field)
67306** then convert that term into a copy of the corresponding result set
67307** column.
67308**
67309** If any errors are detected, add an error message to pParse and
67310** return non-zero.  Return zero if no errors are seen.
67311*/
67312SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
67313  Parse *pParse,        /* Parsing context.  Leave error messages here */
67314  Select *pSelect,      /* The SELECT statement containing the clause */
67315  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
67316  const char *zType     /* "ORDER" or "GROUP" */
67317){
67318  int i;
67319  sqlite3 *db = pParse->db;
67320  ExprList *pEList;
67321  struct ExprList_item *pItem;
67322
67323  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
67324#if SQLITE_MAX_COLUMN
67325  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67326    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
67327    return 1;
67328  }
67329#endif
67330  pEList = pSelect->pEList;
67331  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
67332  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
67333    if( pItem->iCol ){
67334      if( pItem->iCol>pEList->nExpr ){
67335        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
67336        return 1;
67337      }
67338      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
67339    }
67340  }
67341  return 0;
67342}
67343
67344/*
67345** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
67346** The Name context of the SELECT statement is pNC.  zType is either
67347** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
67348**
67349** This routine resolves each term of the clause into an expression.
67350** If the order-by term is an integer I between 1 and N (where N is the
67351** number of columns in the result set of the SELECT) then the expression
67352** in the resolution is a copy of the I-th result-set expression.  If
67353** the order-by term is an identify that corresponds to the AS-name of
67354** a result-set expression, then the term resolves to a copy of the
67355** result-set expression.  Otherwise, the expression is resolved in
67356** the usual way - using sqlite3ResolveExprNames().
67357**
67358** This routine returns the number of errors.  If errors occur, then
67359** an appropriate error message might be left in pParse.  (OOM errors
67360** excepted.)
67361*/
67362static int resolveOrderGroupBy(
67363  NameContext *pNC,     /* The name context of the SELECT statement */
67364  Select *pSelect,      /* The SELECT statement holding pOrderBy */
67365  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
67366  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
67367){
67368  int i;                         /* Loop counter */
67369  int iCol;                      /* Column number */
67370  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
67371  Parse *pParse;                 /* Parsing context */
67372  int nResult;                   /* Number of terms in the result set */
67373
67374  if( pOrderBy==0 ) return 0;
67375  nResult = pSelect->pEList->nExpr;
67376  pParse = pNC->pParse;
67377  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
67378    Expr *pE = pItem->pExpr;
67379    iCol = resolveAsName(pParse, pSelect->pEList, pE);
67380    if( iCol>0 ){
67381      /* If an AS-name match is found, mark this ORDER BY column as being
67382      ** a copy of the iCol-th result-set column.  The subsequent call to
67383      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
67384      ** copy of the iCol-th result-set expression. */
67385      pItem->iCol = (u16)iCol;
67386      continue;
67387    }
67388    if( sqlite3ExprIsInteger(pE, &iCol) ){
67389      /* The ORDER BY term is an integer constant.  Again, set the column
67390      ** number so that sqlite3ResolveOrderGroupBy() will convert the
67391      ** order-by term to a copy of the result-set expression */
67392      if( iCol<1 ){
67393        resolveOutOfRangeError(pParse, zType, i+1, nResult);
67394        return 1;
67395      }
67396      pItem->iCol = (u16)iCol;
67397      continue;
67398    }
67399
67400    /* Otherwise, treat the ORDER BY term as an ordinary expression */
67401    pItem->iCol = 0;
67402    if( sqlite3ResolveExprNames(pNC, pE) ){
67403      return 1;
67404    }
67405  }
67406  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
67407}
67408
67409/*
67410** Resolve names in the SELECT statement p and all of its descendents.
67411*/
67412static int resolveSelectStep(Walker *pWalker, Select *p){
67413  NameContext *pOuterNC;  /* Context that contains this SELECT */
67414  NameContext sNC;        /* Name context of this SELECT */
67415  int isCompound;         /* True if p is a compound select */
67416  int nCompound;          /* Number of compound terms processed so far */
67417  Parse *pParse;          /* Parsing context */
67418  ExprList *pEList;       /* Result set expression list */
67419  int i;                  /* Loop counter */
67420  ExprList *pGroupBy;     /* The GROUP BY clause */
67421  Select *pLeftmost;      /* Left-most of SELECT of a compound */
67422  sqlite3 *db;            /* Database connection */
67423
67424
67425  assert( p!=0 );
67426  if( p->selFlags & SF_Resolved ){
67427    return WRC_Prune;
67428  }
67429  pOuterNC = pWalker->u.pNC;
67430  pParse = pWalker->pParse;
67431  db = pParse->db;
67432
67433  /* Normally sqlite3SelectExpand() will be called first and will have
67434  ** already expanded this SELECT.  However, if this is a subquery within
67435  ** an expression, sqlite3ResolveExprNames() will be called without a
67436  ** prior call to sqlite3SelectExpand().  When that happens, let
67437  ** sqlite3SelectPrep() do all of the processing for this SELECT.
67438  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
67439  ** this routine in the correct order.
67440  */
67441  if( (p->selFlags & SF_Expanded)==0 ){
67442    sqlite3SelectPrep(pParse, p, pOuterNC);
67443    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
67444  }
67445
67446  isCompound = p->pPrior!=0;
67447  nCompound = 0;
67448  pLeftmost = p;
67449  while( p ){
67450    assert( (p->selFlags & SF_Expanded)!=0 );
67451    assert( (p->selFlags & SF_Resolved)==0 );
67452    p->selFlags |= SF_Resolved;
67453
67454    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
67455    ** are not allowed to refer to any names, so pass an empty NameContext.
67456    */
67457    memset(&sNC, 0, sizeof(sNC));
67458    sNC.pParse = pParse;
67459    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
67460        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
67461      return WRC_Abort;
67462    }
67463
67464    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
67465    ** resolve the result-set expression list.
67466    */
67467    sNC.allowAgg = 1;
67468    sNC.pSrcList = p->pSrc;
67469    sNC.pNext = pOuterNC;
67470
67471    /* Resolve names in the result set. */
67472    pEList = p->pEList;
67473    assert( pEList!=0 );
67474    for(i=0; i<pEList->nExpr; i++){
67475      Expr *pX = pEList->a[i].pExpr;
67476      if( sqlite3ResolveExprNames(&sNC, pX) ){
67477        return WRC_Abort;
67478      }
67479    }
67480
67481    /* Recursively resolve names in all subqueries
67482    */
67483    for(i=0; i<p->pSrc->nSrc; i++){
67484      struct SrcList_item *pItem = &p->pSrc->a[i];
67485      if( pItem->pSelect ){
67486        const char *zSavedContext = pParse->zAuthContext;
67487        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
67488        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
67489        pParse->zAuthContext = zSavedContext;
67490        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
67491      }
67492    }
67493
67494    /* If there are no aggregate functions in the result-set, and no GROUP BY
67495    ** expression, do not allow aggregates in any of the other expressions.
67496    */
67497    assert( (p->selFlags & SF_Aggregate)==0 );
67498    pGroupBy = p->pGroupBy;
67499    if( pGroupBy || sNC.hasAgg ){
67500      p->selFlags |= SF_Aggregate;
67501    }else{
67502      sNC.allowAgg = 0;
67503    }
67504
67505    /* If a HAVING clause is present, then there must be a GROUP BY clause.
67506    */
67507    if( p->pHaving && !pGroupBy ){
67508      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
67509      return WRC_Abort;
67510    }
67511
67512    /* Add the expression list to the name-context before parsing the
67513    ** other expressions in the SELECT statement. This is so that
67514    ** expressions in the WHERE clause (etc.) can refer to expressions by
67515    ** aliases in the result set.
67516    **
67517    ** Minor point: If this is the case, then the expression will be
67518    ** re-evaluated for each reference to it.
67519    */
67520    sNC.pEList = p->pEList;
67521    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
67522       sqlite3ResolveExprNames(&sNC, p->pHaving)
67523    ){
67524      return WRC_Abort;
67525    }
67526
67527    /* The ORDER BY and GROUP BY clauses may not refer to terms in
67528    ** outer queries
67529    */
67530    sNC.pNext = 0;
67531    sNC.allowAgg = 1;
67532
67533    /* Process the ORDER BY clause for singleton SELECT statements.
67534    ** The ORDER BY clause for compounds SELECT statements is handled
67535    ** below, after all of the result-sets for all of the elements of
67536    ** the compound have been resolved.
67537    */
67538    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
67539      return WRC_Abort;
67540    }
67541    if( db->mallocFailed ){
67542      return WRC_Abort;
67543    }
67544
67545    /* Resolve the GROUP BY clause.  At the same time, make sure
67546    ** the GROUP BY clause does not contain aggregate functions.
67547    */
67548    if( pGroupBy ){
67549      struct ExprList_item *pItem;
67550
67551      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
67552        return WRC_Abort;
67553      }
67554      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
67555        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
67556          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
67557              "the GROUP BY clause");
67558          return WRC_Abort;
67559        }
67560      }
67561    }
67562
67563    /* Advance to the next term of the compound
67564    */
67565    p = p->pPrior;
67566    nCompound++;
67567  }
67568
67569  /* Resolve the ORDER BY on a compound SELECT after all terms of
67570  ** the compound have been resolved.
67571  */
67572  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
67573    return WRC_Abort;
67574  }
67575
67576  return WRC_Prune;
67577}
67578
67579/*
67580** This routine walks an expression tree and resolves references to
67581** table columns and result-set columns.  At the same time, do error
67582** checking on function usage and set a flag if any aggregate functions
67583** are seen.
67584**
67585** To resolve table columns references we look for nodes (or subtrees) of the
67586** form X.Y.Z or Y.Z or just Z where
67587**
67588**      X:   The name of a database.  Ex:  "main" or "temp" or
67589**           the symbolic name assigned to an ATTACH-ed database.
67590**
67591**      Y:   The name of a table in a FROM clause.  Or in a trigger
67592**           one of the special names "old" or "new".
67593**
67594**      Z:   The name of a column in table Y.
67595**
67596** The node at the root of the subtree is modified as follows:
67597**
67598**    Expr.op        Changed to TK_COLUMN
67599**    Expr.pTab      Points to the Table object for X.Y
67600**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
67601**    Expr.iTable    The VDBE cursor number for X.Y
67602**
67603**
67604** To resolve result-set references, look for expression nodes of the
67605** form Z (with no X and Y prefix) where the Z matches the right-hand
67606** size of an AS clause in the result-set of a SELECT.  The Z expression
67607** is replaced by a copy of the left-hand side of the result-set expression.
67608** Table-name and function resolution occurs on the substituted expression
67609** tree.  For example, in:
67610**
67611**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
67612**
67613** The "x" term of the order by is replaced by "a+b" to render:
67614**
67615**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
67616**
67617** Function calls are checked to make sure that the function is
67618** defined and that the correct number of arguments are specified.
67619** If the function is an aggregate function, then the pNC->hasAgg is
67620** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
67621** If an expression contains aggregate functions then the EP_Agg
67622** property on the expression is set.
67623**
67624** An error message is left in pParse if anything is amiss.  The number
67625** if errors is returned.
67626*/
67627SQLITE_PRIVATE int sqlite3ResolveExprNames(
67628  NameContext *pNC,       /* Namespace to resolve expressions in. */
67629  Expr *pExpr             /* The expression to be analyzed. */
67630){
67631  int savedHasAgg;
67632  Walker w;
67633
67634  if( pExpr==0 ) return 0;
67635#if SQLITE_MAX_EXPR_DEPTH>0
67636  {
67637    Parse *pParse = pNC->pParse;
67638    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
67639      return 1;
67640    }
67641    pParse->nHeight += pExpr->nHeight;
67642  }
67643#endif
67644  savedHasAgg = pNC->hasAgg;
67645  pNC->hasAgg = 0;
67646  w.xExprCallback = resolveExprStep;
67647  w.xSelectCallback = resolveSelectStep;
67648  w.pParse = pNC->pParse;
67649  w.u.pNC = pNC;
67650  sqlite3WalkExpr(&w, pExpr);
67651#if SQLITE_MAX_EXPR_DEPTH>0
67652  pNC->pParse->nHeight -= pExpr->nHeight;
67653#endif
67654  if( pNC->nErr>0 || w.pParse->nErr>0 ){
67655    ExprSetProperty(pExpr, EP_Error);
67656  }
67657  if( pNC->hasAgg ){
67658    ExprSetProperty(pExpr, EP_Agg);
67659  }else if( savedHasAgg ){
67660    pNC->hasAgg = 1;
67661  }
67662  return ExprHasProperty(pExpr, EP_Error);
67663}
67664
67665
67666/*
67667** Resolve all names in all expressions of a SELECT and in all
67668** decendents of the SELECT, including compounds off of p->pPrior,
67669** subqueries in expressions, and subqueries used as FROM clause
67670** terms.
67671**
67672** See sqlite3ResolveExprNames() for a description of the kinds of
67673** transformations that occur.
67674**
67675** All SELECT statements should have been expanded using
67676** sqlite3SelectExpand() prior to invoking this routine.
67677*/
67678SQLITE_PRIVATE void sqlite3ResolveSelectNames(
67679  Parse *pParse,         /* The parser context */
67680  Select *p,             /* The SELECT statement being coded. */
67681  NameContext *pOuterNC  /* Name context for parent SELECT statement */
67682){
67683  Walker w;
67684
67685  assert( p!=0 );
67686  w.xExprCallback = resolveExprStep;
67687  w.xSelectCallback = resolveSelectStep;
67688  w.pParse = pParse;
67689  w.u.pNC = pOuterNC;
67690  sqlite3WalkSelect(&w, p);
67691}
67692
67693/************** End of resolve.c *********************************************/
67694/************** Begin file expr.c ********************************************/
67695/*
67696** 2001 September 15
67697**
67698** The author disclaims copyright to this source code.  In place of
67699** a legal notice, here is a blessing:
67700**
67701**    May you do good and not evil.
67702**    May you find forgiveness for yourself and forgive others.
67703**    May you share freely, never taking more than you give.
67704**
67705*************************************************************************
67706** This file contains routines used for analyzing expressions and
67707** for generating VDBE code that evaluates expressions in SQLite.
67708*/
67709
67710/*
67711** Return the 'affinity' of the expression pExpr if any.
67712**
67713** If pExpr is a column, a reference to a column via an 'AS' alias,
67714** or a sub-select with a column as the return value, then the
67715** affinity of that column is returned. Otherwise, 0x00 is returned,
67716** indicating no affinity for the expression.
67717**
67718** i.e. the WHERE clause expresssions in the following statements all
67719** have an affinity:
67720**
67721** CREATE TABLE t1(a);
67722** SELECT * FROM t1 WHERE a;
67723** SELECT a AS b FROM t1 WHERE b;
67724** SELECT * FROM t1 WHERE (select a from t1);
67725*/
67726SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
67727  int op = pExpr->op;
67728  if( op==TK_SELECT ){
67729    assert( pExpr->flags&EP_xIsSelect );
67730    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
67731  }
67732#ifndef SQLITE_OMIT_CAST
67733  if( op==TK_CAST ){
67734    assert( !ExprHasProperty(pExpr, EP_IntValue) );
67735    return sqlite3AffinityType(pExpr->u.zToken);
67736  }
67737#endif
67738  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
67739   && pExpr->pTab!=0
67740  ){
67741    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
67742    ** a TK_COLUMN but was previously evaluated and cached in a register */
67743    int j = pExpr->iColumn;
67744    if( j<0 ) return SQLITE_AFF_INTEGER;
67745    assert( pExpr->pTab && j<pExpr->pTab->nCol );
67746    return pExpr->pTab->aCol[j].affinity;
67747  }
67748  return pExpr->affinity;
67749}
67750
67751/*
67752** Set the explicit collating sequence for an expression to the
67753** collating sequence supplied in the second argument.
67754*/
67755SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
67756  if( pExpr && pColl ){
67757    pExpr->pColl = pColl;
67758    pExpr->flags |= EP_ExpCollate;
67759  }
67760  return pExpr;
67761}
67762
67763/*
67764** Set the collating sequence for expression pExpr to be the collating
67765** sequence named by pToken.   Return a pointer to the revised expression.
67766** The collating sequence is marked as "explicit" using the EP_ExpCollate
67767** flag.  An explicit collating sequence will override implicit
67768** collating sequences.
67769*/
67770SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
67771  char *zColl = 0;            /* Dequoted name of collation sequence */
67772  CollSeq *pColl;
67773  sqlite3 *db = pParse->db;
67774  zColl = sqlite3NameFromToken(db, pCollName);
67775  pColl = sqlite3LocateCollSeq(pParse, zColl);
67776  sqlite3ExprSetColl(pExpr, pColl);
67777  sqlite3DbFree(db, zColl);
67778  return pExpr;
67779}
67780
67781/*
67782** Return the default collation sequence for the expression pExpr. If
67783** there is no default collation type, return 0.
67784*/
67785SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
67786  CollSeq *pColl = 0;
67787  Expr *p = pExpr;
67788  while( ALWAYS(p) ){
67789    int op;
67790    pColl = p->pColl;
67791    if( pColl ) break;
67792    op = p->op;
67793    if( p->pTab!=0 && (
67794        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
67795    )){
67796      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
67797      ** a TK_COLUMN but was previously evaluated and cached in a register */
67798      const char *zColl;
67799      int j = p->iColumn;
67800      if( j>=0 ){
67801        sqlite3 *db = pParse->db;
67802        zColl = p->pTab->aCol[j].zColl;
67803        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
67804        pExpr->pColl = pColl;
67805      }
67806      break;
67807    }
67808    if( op!=TK_CAST && op!=TK_UPLUS ){
67809      break;
67810    }
67811    p = p->pLeft;
67812  }
67813  if( sqlite3CheckCollSeq(pParse, pColl) ){
67814    pColl = 0;
67815  }
67816  return pColl;
67817}
67818
67819/*
67820** pExpr is an operand of a comparison operator.  aff2 is the
67821** type affinity of the other operand.  This routine returns the
67822** type affinity that should be used for the comparison operator.
67823*/
67824SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
67825  char aff1 = sqlite3ExprAffinity(pExpr);
67826  if( aff1 && aff2 ){
67827    /* Both sides of the comparison are columns. If one has numeric
67828    ** affinity, use that. Otherwise use no affinity.
67829    */
67830    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
67831      return SQLITE_AFF_NUMERIC;
67832    }else{
67833      return SQLITE_AFF_NONE;
67834    }
67835  }else if( !aff1 && !aff2 ){
67836    /* Neither side of the comparison is a column.  Compare the
67837    ** results directly.
67838    */
67839    return SQLITE_AFF_NONE;
67840  }else{
67841    /* One side is a column, the other is not. Use the columns affinity. */
67842    assert( aff1==0 || aff2==0 );
67843    return (aff1 + aff2);
67844  }
67845}
67846
67847/*
67848** pExpr is a comparison operator.  Return the type affinity that should
67849** be applied to both operands prior to doing the comparison.
67850*/
67851static char comparisonAffinity(Expr *pExpr){
67852  char aff;
67853  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
67854          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
67855          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
67856  assert( pExpr->pLeft );
67857  aff = sqlite3ExprAffinity(pExpr->pLeft);
67858  if( pExpr->pRight ){
67859    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
67860  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
67861    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
67862  }else if( !aff ){
67863    aff = SQLITE_AFF_NONE;
67864  }
67865  return aff;
67866}
67867
67868/*
67869** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
67870** idx_affinity is the affinity of an indexed column. Return true
67871** if the index with affinity idx_affinity may be used to implement
67872** the comparison in pExpr.
67873*/
67874SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
67875  char aff = comparisonAffinity(pExpr);
67876  switch( aff ){
67877    case SQLITE_AFF_NONE:
67878      return 1;
67879    case SQLITE_AFF_TEXT:
67880      return idx_affinity==SQLITE_AFF_TEXT;
67881    default:
67882      return sqlite3IsNumericAffinity(idx_affinity);
67883  }
67884}
67885
67886/*
67887** Return the P5 value that should be used for a binary comparison
67888** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
67889*/
67890static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
67891  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
67892  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
67893  return aff;
67894}
67895
67896/*
67897** Return a pointer to the collation sequence that should be used by
67898** a binary comparison operator comparing pLeft and pRight.
67899**
67900** If the left hand expression has a collating sequence type, then it is
67901** used. Otherwise the collation sequence for the right hand expression
67902** is used, or the default (BINARY) if neither expression has a collating
67903** type.
67904**
67905** Argument pRight (but not pLeft) may be a null pointer. In this case,
67906** it is not considered.
67907*/
67908SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
67909  Parse *pParse,
67910  Expr *pLeft,
67911  Expr *pRight
67912){
67913  CollSeq *pColl;
67914  assert( pLeft );
67915  if( pLeft->flags & EP_ExpCollate ){
67916    assert( pLeft->pColl );
67917    pColl = pLeft->pColl;
67918  }else if( pRight && pRight->flags & EP_ExpCollate ){
67919    assert( pRight->pColl );
67920    pColl = pRight->pColl;
67921  }else{
67922    pColl = sqlite3ExprCollSeq(pParse, pLeft);
67923    if( !pColl ){
67924      pColl = sqlite3ExprCollSeq(pParse, pRight);
67925    }
67926  }
67927  return pColl;
67928}
67929
67930/*
67931** Generate code for a comparison operator.
67932*/
67933static int codeCompare(
67934  Parse *pParse,    /* The parsing (and code generating) context */
67935  Expr *pLeft,      /* The left operand */
67936  Expr *pRight,     /* The right operand */
67937  int opcode,       /* The comparison opcode */
67938  int in1, int in2, /* Register holding operands */
67939  int dest,         /* Jump here if true.  */
67940  int jumpIfNull    /* If true, jump if either operand is NULL */
67941){
67942  int p5;
67943  int addr;
67944  CollSeq *p4;
67945
67946  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
67947  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
67948  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
67949                           (void*)p4, P4_COLLSEQ);
67950  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
67951  return addr;
67952}
67953
67954#if SQLITE_MAX_EXPR_DEPTH>0
67955/*
67956** Check that argument nHeight is less than or equal to the maximum
67957** expression depth allowed. If it is not, leave an error message in
67958** pParse.
67959*/
67960SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
67961  int rc = SQLITE_OK;
67962  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
67963  if( nHeight>mxHeight ){
67964    sqlite3ErrorMsg(pParse,
67965       "Expression tree is too large (maximum depth %d)", mxHeight
67966    );
67967    rc = SQLITE_ERROR;
67968  }
67969  return rc;
67970}
67971
67972/* The following three functions, heightOfExpr(), heightOfExprList()
67973** and heightOfSelect(), are used to determine the maximum height
67974** of any expression tree referenced by the structure passed as the
67975** first argument.
67976**
67977** If this maximum height is greater than the current value pointed
67978** to by pnHeight, the second parameter, then set *pnHeight to that
67979** value.
67980*/
67981static void heightOfExpr(Expr *p, int *pnHeight){
67982  if( p ){
67983    if( p->nHeight>*pnHeight ){
67984      *pnHeight = p->nHeight;
67985    }
67986  }
67987}
67988static void heightOfExprList(ExprList *p, int *pnHeight){
67989  if( p ){
67990    int i;
67991    for(i=0; i<p->nExpr; i++){
67992      heightOfExpr(p->a[i].pExpr, pnHeight);
67993    }
67994  }
67995}
67996static void heightOfSelect(Select *p, int *pnHeight){
67997  if( p ){
67998    heightOfExpr(p->pWhere, pnHeight);
67999    heightOfExpr(p->pHaving, pnHeight);
68000    heightOfExpr(p->pLimit, pnHeight);
68001    heightOfExpr(p->pOffset, pnHeight);
68002    heightOfExprList(p->pEList, pnHeight);
68003    heightOfExprList(p->pGroupBy, pnHeight);
68004    heightOfExprList(p->pOrderBy, pnHeight);
68005    heightOfSelect(p->pPrior, pnHeight);
68006  }
68007}
68008
68009/*
68010** Set the Expr.nHeight variable in the structure passed as an
68011** argument. An expression with no children, Expr.pList or
68012** Expr.pSelect member has a height of 1. Any other expression
68013** has a height equal to the maximum height of any other
68014** referenced Expr plus one.
68015*/
68016static void exprSetHeight(Expr *p){
68017  int nHeight = 0;
68018  heightOfExpr(p->pLeft, &nHeight);
68019  heightOfExpr(p->pRight, &nHeight);
68020  if( ExprHasProperty(p, EP_xIsSelect) ){
68021    heightOfSelect(p->x.pSelect, &nHeight);
68022  }else{
68023    heightOfExprList(p->x.pList, &nHeight);
68024  }
68025  p->nHeight = nHeight + 1;
68026}
68027
68028/*
68029** Set the Expr.nHeight variable using the exprSetHeight() function. If
68030** the height is greater than the maximum allowed expression depth,
68031** leave an error in pParse.
68032*/
68033SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
68034  exprSetHeight(p);
68035  sqlite3ExprCheckHeight(pParse, p->nHeight);
68036}
68037
68038/*
68039** Return the maximum height of any expression tree referenced
68040** by the select statement passed as an argument.
68041*/
68042SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
68043  int nHeight = 0;
68044  heightOfSelect(p, &nHeight);
68045  return nHeight;
68046}
68047#else
68048  #define exprSetHeight(y)
68049#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
68050
68051/*
68052** This routine is the core allocator for Expr nodes.
68053**
68054** Construct a new expression node and return a pointer to it.  Memory
68055** for this node and for the pToken argument is a single allocation
68056** obtained from sqlite3DbMalloc().  The calling function
68057** is responsible for making sure the node eventually gets freed.
68058**
68059** If dequote is true, then the token (if it exists) is dequoted.
68060** If dequote is false, no dequoting is performance.  The deQuote
68061** parameter is ignored if pToken is NULL or if the token does not
68062** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
68063** then the EP_DblQuoted flag is set on the expression node.
68064**
68065** Special case:  If op==TK_INTEGER and pToken points to a string that
68066** can be translated into a 32-bit integer, then the token is not
68067** stored in u.zToken.  Instead, the integer values is written
68068** into u.iValue and the EP_IntValue flag is set.  No extra storage
68069** is allocated to hold the integer text and the dequote flag is ignored.
68070*/
68071SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
68072  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
68073  int op,                 /* Expression opcode */
68074  const Token *pToken,    /* Token argument.  Might be NULL */
68075  int dequote             /* True to dequote */
68076){
68077  Expr *pNew;
68078  int nExtra = 0;
68079  int iValue = 0;
68080
68081  if( pToken ){
68082    if( op!=TK_INTEGER || pToken->z==0
68083          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
68084      nExtra = pToken->n+1;
68085    }
68086  }
68087  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
68088  if( pNew ){
68089    pNew->op = (u8)op;
68090    pNew->iAgg = -1;
68091    if( pToken ){
68092      if( nExtra==0 ){
68093        pNew->flags |= EP_IntValue;
68094        pNew->u.iValue = iValue;
68095      }else{
68096        int c;
68097        pNew->u.zToken = (char*)&pNew[1];
68098        memcpy(pNew->u.zToken, pToken->z, pToken->n);
68099        pNew->u.zToken[pToken->n] = 0;
68100        if( dequote && nExtra>=3
68101             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
68102          sqlite3Dequote(pNew->u.zToken);
68103          if( c=='"' ) pNew->flags |= EP_DblQuoted;
68104        }
68105      }
68106    }
68107#if SQLITE_MAX_EXPR_DEPTH>0
68108    pNew->nHeight = 1;
68109#endif
68110  }
68111  return pNew;
68112}
68113
68114/*
68115** Allocate a new expression node from a zero-terminated token that has
68116** already been dequoted.
68117*/
68118SQLITE_PRIVATE Expr *sqlite3Expr(
68119  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
68120  int op,                 /* Expression opcode */
68121  const char *zToken      /* Token argument.  Might be NULL */
68122){
68123  Token x;
68124  x.z = zToken;
68125  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
68126  return sqlite3ExprAlloc(db, op, &x, 0);
68127}
68128
68129/*
68130** Attach subtrees pLeft and pRight to the Expr node pRoot.
68131**
68132** If pRoot==NULL that means that a memory allocation error has occurred.
68133** In that case, delete the subtrees pLeft and pRight.
68134*/
68135SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
68136  sqlite3 *db,
68137  Expr *pRoot,
68138  Expr *pLeft,
68139  Expr *pRight
68140){
68141  if( pRoot==0 ){
68142    assert( db->mallocFailed );
68143    sqlite3ExprDelete(db, pLeft);
68144    sqlite3ExprDelete(db, pRight);
68145  }else{
68146    if( pRight ){
68147      pRoot->pRight = pRight;
68148      if( pRight->flags & EP_ExpCollate ){
68149        pRoot->flags |= EP_ExpCollate;
68150        pRoot->pColl = pRight->pColl;
68151      }
68152    }
68153    if( pLeft ){
68154      pRoot->pLeft = pLeft;
68155      if( pLeft->flags & EP_ExpCollate ){
68156        pRoot->flags |= EP_ExpCollate;
68157        pRoot->pColl = pLeft->pColl;
68158      }
68159    }
68160    exprSetHeight(pRoot);
68161  }
68162}
68163
68164/*
68165** Allocate a Expr node which joins as many as two subtrees.
68166**
68167** One or both of the subtrees can be NULL.  Return a pointer to the new
68168** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
68169** free the subtrees and return NULL.
68170*/
68171SQLITE_PRIVATE Expr *sqlite3PExpr(
68172  Parse *pParse,          /* Parsing context */
68173  int op,                 /* Expression opcode */
68174  Expr *pLeft,            /* Left operand */
68175  Expr *pRight,           /* Right operand */
68176  const Token *pToken     /* Argument token */
68177){
68178  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
68179  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
68180  return p;
68181}
68182
68183/*
68184** Join two expressions using an AND operator.  If either expression is
68185** NULL, then just return the other expression.
68186*/
68187SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
68188  if( pLeft==0 ){
68189    return pRight;
68190  }else if( pRight==0 ){
68191    return pLeft;
68192  }else{
68193    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
68194    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
68195    return pNew;
68196  }
68197}
68198
68199/*
68200** Construct a new expression node for a function with multiple
68201** arguments.
68202*/
68203SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
68204  Expr *pNew;
68205  sqlite3 *db = pParse->db;
68206  assert( pToken );
68207  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
68208  if( pNew==0 ){
68209    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
68210    return 0;
68211  }
68212  pNew->x.pList = pList;
68213  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
68214  sqlite3ExprSetHeight(pParse, pNew);
68215  return pNew;
68216}
68217
68218/*
68219** Assign a variable number to an expression that encodes a wildcard
68220** in the original SQL statement.
68221**
68222** Wildcards consisting of a single "?" are assigned the next sequential
68223** variable number.
68224**
68225** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
68226** sure "nnn" is not too be to avoid a denial of service attack when
68227** the SQL statement comes from an external source.
68228**
68229** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
68230** as the previous instance of the same wildcard.  Or if this is the first
68231** instance of the wildcard, the next sequenial variable number is
68232** assigned.
68233*/
68234SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
68235  sqlite3 *db = pParse->db;
68236  const char *z;
68237
68238  if( pExpr==0 ) return;
68239  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
68240  z = pExpr->u.zToken;
68241  assert( z!=0 );
68242  assert( z[0]!=0 );
68243  if( z[1]==0 ){
68244    /* Wildcard of the form "?".  Assign the next variable number */
68245    assert( z[0]=='?' );
68246    pExpr->iColumn = (ynVar)(++pParse->nVar);
68247  }else if( z[0]=='?' ){
68248    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
68249    ** use it as the variable number */
68250    i64 i;
68251    int bOk = sqlite3Atoi64(&z[1], &i);
68252    pExpr->iColumn = (ynVar)i;
68253    testcase( i==0 );
68254    testcase( i==1 );
68255    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
68256    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
68257    if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
68258      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
68259          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
68260    }
68261    if( i>pParse->nVar ){
68262      pParse->nVar = (int)i;
68263    }
68264  }else{
68265    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
68266    ** number as the prior appearance of the same name, or if the name
68267    ** has never appeared before, reuse the same variable number
68268    */
68269    int i;
68270    u32 n;
68271    n = sqlite3Strlen30(z);
68272    for(i=0; i<pParse->nVarExpr; i++){
68273      Expr *pE = pParse->apVarExpr[i];
68274      assert( pE!=0 );
68275      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
68276        pExpr->iColumn = pE->iColumn;
68277        break;
68278      }
68279    }
68280    if( i>=pParse->nVarExpr ){
68281      pExpr->iColumn = (ynVar)(++pParse->nVar);
68282      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
68283        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
68284        pParse->apVarExpr =
68285            sqlite3DbReallocOrFree(
68286              db,
68287              pParse->apVarExpr,
68288              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
68289            );
68290      }
68291      if( !db->mallocFailed ){
68292        assert( pParse->apVarExpr!=0 );
68293        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
68294      }
68295    }
68296  }
68297  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
68298    sqlite3ErrorMsg(pParse, "too many SQL variables");
68299  }
68300}
68301
68302/*
68303** Recursively delete an expression tree.
68304*/
68305SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
68306  if( p==0 ) return;
68307  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
68308    sqlite3ExprDelete(db, p->pLeft);
68309    sqlite3ExprDelete(db, p->pRight);
68310    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
68311      sqlite3DbFree(db, p->u.zToken);
68312    }
68313    if( ExprHasProperty(p, EP_xIsSelect) ){
68314      sqlite3SelectDelete(db, p->x.pSelect);
68315    }else{
68316      sqlite3ExprListDelete(db, p->x.pList);
68317    }
68318  }
68319  if( !ExprHasProperty(p, EP_Static) ){
68320    sqlite3DbFree(db, p);
68321  }
68322}
68323
68324/*
68325** Return the number of bytes allocated for the expression structure
68326** passed as the first argument. This is always one of EXPR_FULLSIZE,
68327** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
68328*/
68329static int exprStructSize(Expr *p){
68330  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
68331  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
68332  return EXPR_FULLSIZE;
68333}
68334
68335/*
68336** The dupedExpr*Size() routines each return the number of bytes required
68337** to store a copy of an expression or expression tree.  They differ in
68338** how much of the tree is measured.
68339**
68340**     dupedExprStructSize()     Size of only the Expr structure
68341**     dupedExprNodeSize()       Size of Expr + space for token
68342**     dupedExprSize()           Expr + token + subtree components
68343**
68344***************************************************************************
68345**
68346** The dupedExprStructSize() function returns two values OR-ed together:
68347** (1) the space required for a copy of the Expr structure only and
68348** (2) the EP_xxx flags that indicate what the structure size should be.
68349** The return values is always one of:
68350**
68351**      EXPR_FULLSIZE
68352**      EXPR_REDUCEDSIZE   | EP_Reduced
68353**      EXPR_TOKENONLYSIZE | EP_TokenOnly
68354**
68355** The size of the structure can be found by masking the return value
68356** of this routine with 0xfff.  The flags can be found by masking the
68357** return value with EP_Reduced|EP_TokenOnly.
68358**
68359** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
68360** (unreduced) Expr objects as they or originally constructed by the parser.
68361** During expression analysis, extra information is computed and moved into
68362** later parts of teh Expr object and that extra information might get chopped
68363** off if the expression is reduced.  Note also that it does not work to
68364** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
68365** to reduce a pristine expression tree from the parser.  The implementation
68366** of dupedExprStructSize() contain multiple assert() statements that attempt
68367** to enforce this constraint.
68368*/
68369static int dupedExprStructSize(Expr *p, int flags){
68370  int nSize;
68371  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
68372  if( 0==(flags&EXPRDUP_REDUCE) ){
68373    nSize = EXPR_FULLSIZE;
68374  }else{
68375    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
68376    assert( !ExprHasProperty(p, EP_FromJoin) );
68377    assert( (p->flags2 & EP2_MallocedToken)==0 );
68378    assert( (p->flags2 & EP2_Irreducible)==0 );
68379    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
68380      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
68381    }else{
68382      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
68383    }
68384  }
68385  return nSize;
68386}
68387
68388/*
68389** This function returns the space in bytes required to store the copy
68390** of the Expr structure and a copy of the Expr.u.zToken string (if that
68391** string is defined.)
68392*/
68393static int dupedExprNodeSize(Expr *p, int flags){
68394  int nByte = dupedExprStructSize(p, flags) & 0xfff;
68395  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
68396    nByte += sqlite3Strlen30(p->u.zToken)+1;
68397  }
68398  return ROUND8(nByte);
68399}
68400
68401/*
68402** Return the number of bytes required to create a duplicate of the
68403** expression passed as the first argument. The second argument is a
68404** mask containing EXPRDUP_XXX flags.
68405**
68406** The value returned includes space to create a copy of the Expr struct
68407** itself and the buffer referred to by Expr.u.zToken, if any.
68408**
68409** If the EXPRDUP_REDUCE flag is set, then the return value includes
68410** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
68411** and Expr.pRight variables (but not for any structures pointed to or
68412** descended from the Expr.x.pList or Expr.x.pSelect variables).
68413*/
68414static int dupedExprSize(Expr *p, int flags){
68415  int nByte = 0;
68416  if( p ){
68417    nByte = dupedExprNodeSize(p, flags);
68418    if( flags&EXPRDUP_REDUCE ){
68419      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
68420    }
68421  }
68422  return nByte;
68423}
68424
68425/*
68426** This function is similar to sqlite3ExprDup(), except that if pzBuffer
68427** is not NULL then *pzBuffer is assumed to point to a buffer large enough
68428** to store the copy of expression p, the copies of p->u.zToken
68429** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
68430** if any. Before returning, *pzBuffer is set to the first byte passed the
68431** portion of the buffer copied into by this function.
68432*/
68433static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
68434  Expr *pNew = 0;                      /* Value to return */
68435  if( p ){
68436    const int isReduced = (flags&EXPRDUP_REDUCE);
68437    u8 *zAlloc;
68438    u32 staticFlag = 0;
68439
68440    assert( pzBuffer==0 || isReduced );
68441
68442    /* Figure out where to write the new Expr structure. */
68443    if( pzBuffer ){
68444      zAlloc = *pzBuffer;
68445      staticFlag = EP_Static;
68446    }else{
68447      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
68448    }
68449    pNew = (Expr *)zAlloc;
68450
68451    if( pNew ){
68452      /* Set nNewSize to the size allocated for the structure pointed to
68453      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
68454      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
68455      ** by the copy of the p->u.zToken string (if any).
68456      */
68457      const unsigned nStructSize = dupedExprStructSize(p, flags);
68458      const int nNewSize = nStructSize & 0xfff;
68459      int nToken;
68460      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
68461        nToken = sqlite3Strlen30(p->u.zToken) + 1;
68462      }else{
68463        nToken = 0;
68464      }
68465      if( isReduced ){
68466        assert( ExprHasProperty(p, EP_Reduced)==0 );
68467        memcpy(zAlloc, p, nNewSize);
68468      }else{
68469        int nSize = exprStructSize(p);
68470        memcpy(zAlloc, p, nSize);
68471        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
68472      }
68473
68474      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
68475      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
68476      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
68477      pNew->flags |= staticFlag;
68478
68479      /* Copy the p->u.zToken string, if any. */
68480      if( nToken ){
68481        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
68482        memcpy(zToken, p->u.zToken, nToken);
68483      }
68484
68485      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
68486        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
68487        if( ExprHasProperty(p, EP_xIsSelect) ){
68488          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
68489        }else{
68490          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
68491        }
68492      }
68493
68494      /* Fill in pNew->pLeft and pNew->pRight. */
68495      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
68496        zAlloc += dupedExprNodeSize(p, flags);
68497        if( ExprHasProperty(pNew, EP_Reduced) ){
68498          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
68499          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
68500        }
68501        if( pzBuffer ){
68502          *pzBuffer = zAlloc;
68503        }
68504      }else{
68505        pNew->flags2 = 0;
68506        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
68507          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
68508          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
68509        }
68510      }
68511
68512    }
68513  }
68514  return pNew;
68515}
68516
68517/*
68518** The following group of routines make deep copies of expressions,
68519** expression lists, ID lists, and select statements.  The copies can
68520** be deleted (by being passed to their respective ...Delete() routines)
68521** without effecting the originals.
68522**
68523** The expression list, ID, and source lists return by sqlite3ExprListDup(),
68524** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
68525** by subsequent calls to sqlite*ListAppend() routines.
68526**
68527** Any tables that the SrcList might point to are not duplicated.
68528**
68529** The flags parameter contains a combination of the EXPRDUP_XXX flags.
68530** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
68531** truncated version of the usual Expr structure that will be stored as
68532** part of the in-memory representation of the database schema.
68533*/
68534SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
68535  return exprDup(db, p, flags, 0);
68536}
68537SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
68538  ExprList *pNew;
68539  struct ExprList_item *pItem, *pOldItem;
68540  int i;
68541  if( p==0 ) return 0;
68542  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
68543  if( pNew==0 ) return 0;
68544  pNew->iECursor = 0;
68545  pNew->nExpr = pNew->nAlloc = p->nExpr;
68546  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
68547  if( pItem==0 ){
68548    sqlite3DbFree(db, pNew);
68549    return 0;
68550  }
68551  pOldItem = p->a;
68552  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
68553    Expr *pOldExpr = pOldItem->pExpr;
68554    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
68555    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
68556    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
68557    pItem->sortOrder = pOldItem->sortOrder;
68558    pItem->done = 0;
68559    pItem->iCol = pOldItem->iCol;
68560    pItem->iAlias = pOldItem->iAlias;
68561  }
68562  return pNew;
68563}
68564
68565/*
68566** If cursors, triggers, views and subqueries are all omitted from
68567** the build, then none of the following routines, except for
68568** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
68569** called with a NULL argument.
68570*/
68571#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
68572 || !defined(SQLITE_OMIT_SUBQUERY)
68573SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
68574  SrcList *pNew;
68575  int i;
68576  int nByte;
68577  if( p==0 ) return 0;
68578  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
68579  pNew = sqlite3DbMallocRaw(db, nByte );
68580  if( pNew==0 ) return 0;
68581  pNew->nSrc = pNew->nAlloc = p->nSrc;
68582  for(i=0; i<p->nSrc; i++){
68583    struct SrcList_item *pNewItem = &pNew->a[i];
68584    struct SrcList_item *pOldItem = &p->a[i];
68585    Table *pTab;
68586    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
68587    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
68588    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
68589    pNewItem->jointype = pOldItem->jointype;
68590    pNewItem->iCursor = pOldItem->iCursor;
68591    pNewItem->isPopulated = pOldItem->isPopulated;
68592    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
68593    pNewItem->notIndexed = pOldItem->notIndexed;
68594    pNewItem->pIndex = pOldItem->pIndex;
68595    pTab = pNewItem->pTab = pOldItem->pTab;
68596    if( pTab ){
68597      pTab->nRef++;
68598    }
68599    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
68600    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
68601    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
68602    pNewItem->colUsed = pOldItem->colUsed;
68603  }
68604  return pNew;
68605}
68606SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
68607  IdList *pNew;
68608  int i;
68609  if( p==0 ) return 0;
68610  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
68611  if( pNew==0 ) return 0;
68612  pNew->nId = pNew->nAlloc = p->nId;
68613  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
68614  if( pNew->a==0 ){
68615    sqlite3DbFree(db, pNew);
68616    return 0;
68617  }
68618  for(i=0; i<p->nId; i++){
68619    struct IdList_item *pNewItem = &pNew->a[i];
68620    struct IdList_item *pOldItem = &p->a[i];
68621    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
68622    pNewItem->idx = pOldItem->idx;
68623  }
68624  return pNew;
68625}
68626SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
68627  Select *pNew;
68628  if( p==0 ) return 0;
68629  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
68630  if( pNew==0 ) return 0;
68631  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
68632  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
68633  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
68634  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
68635  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
68636  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
68637  pNew->op = p->op;
68638  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
68639  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
68640  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
68641  pNew->iLimit = 0;
68642  pNew->iOffset = 0;
68643  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
68644  pNew->pRightmost = 0;
68645  pNew->addrOpenEphm[0] = -1;
68646  pNew->addrOpenEphm[1] = -1;
68647  pNew->addrOpenEphm[2] = -1;
68648  return pNew;
68649}
68650#else
68651SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
68652  assert( p==0 );
68653  return 0;
68654}
68655#endif
68656
68657
68658/*
68659** Add a new element to the end of an expression list.  If pList is
68660** initially NULL, then create a new expression list.
68661**
68662** If a memory allocation error occurs, the entire list is freed and
68663** NULL is returned.  If non-NULL is returned, then it is guaranteed
68664** that the new entry was successfully appended.
68665*/
68666SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
68667  Parse *pParse,          /* Parsing context */
68668  ExprList *pList,        /* List to which to append. Might be NULL */
68669  Expr *pExpr             /* Expression to be appended. Might be NULL */
68670){
68671  sqlite3 *db = pParse->db;
68672  if( pList==0 ){
68673    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
68674    if( pList==0 ){
68675      goto no_mem;
68676    }
68677    assert( pList->nAlloc==0 );
68678  }
68679  if( pList->nAlloc<=pList->nExpr ){
68680    struct ExprList_item *a;
68681    int n = pList->nAlloc*2 + 4;
68682    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
68683    if( a==0 ){
68684      goto no_mem;
68685    }
68686    pList->a = a;
68687    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
68688  }
68689  assert( pList->a!=0 );
68690  if( 1 ){
68691    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
68692    memset(pItem, 0, sizeof(*pItem));
68693    pItem->pExpr = pExpr;
68694  }
68695  return pList;
68696
68697no_mem:
68698  /* Avoid leaking memory if malloc has failed. */
68699  sqlite3ExprDelete(db, pExpr);
68700  sqlite3ExprListDelete(db, pList);
68701  return 0;
68702}
68703
68704/*
68705** Set the ExprList.a[].zName element of the most recently added item
68706** on the expression list.
68707**
68708** pList might be NULL following an OOM error.  But pName should never be
68709** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
68710** is set.
68711*/
68712SQLITE_PRIVATE void sqlite3ExprListSetName(
68713  Parse *pParse,          /* Parsing context */
68714  ExprList *pList,        /* List to which to add the span. */
68715  Token *pName,           /* Name to be added */
68716  int dequote             /* True to cause the name to be dequoted */
68717){
68718  assert( pList!=0 || pParse->db->mallocFailed!=0 );
68719  if( pList ){
68720    struct ExprList_item *pItem;
68721    assert( pList->nExpr>0 );
68722    pItem = &pList->a[pList->nExpr-1];
68723    assert( pItem->zName==0 );
68724    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
68725    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
68726  }
68727}
68728
68729/*
68730** Set the ExprList.a[].zSpan element of the most recently added item
68731** on the expression list.
68732**
68733** pList might be NULL following an OOM error.  But pSpan should never be
68734** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
68735** is set.
68736*/
68737SQLITE_PRIVATE void sqlite3ExprListSetSpan(
68738  Parse *pParse,          /* Parsing context */
68739  ExprList *pList,        /* List to which to add the span. */
68740  ExprSpan *pSpan         /* The span to be added */
68741){
68742  sqlite3 *db = pParse->db;
68743  assert( pList!=0 || db->mallocFailed!=0 );
68744  if( pList ){
68745    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
68746    assert( pList->nExpr>0 );
68747    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
68748    sqlite3DbFree(db, pItem->zSpan);
68749    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
68750                                    (int)(pSpan->zEnd - pSpan->zStart));
68751  }
68752}
68753
68754/*
68755** If the expression list pEList contains more than iLimit elements,
68756** leave an error message in pParse.
68757*/
68758SQLITE_PRIVATE void sqlite3ExprListCheckLength(
68759  Parse *pParse,
68760  ExprList *pEList,
68761  const char *zObject
68762){
68763  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
68764  testcase( pEList && pEList->nExpr==mx );
68765  testcase( pEList && pEList->nExpr==mx+1 );
68766  if( pEList && pEList->nExpr>mx ){
68767    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
68768  }
68769}
68770
68771/*
68772** Delete an entire expression list.
68773*/
68774SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
68775  int i;
68776  struct ExprList_item *pItem;
68777  if( pList==0 ) return;
68778  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
68779  assert( pList->nExpr<=pList->nAlloc );
68780  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
68781    sqlite3ExprDelete(db, pItem->pExpr);
68782    sqlite3DbFree(db, pItem->zName);
68783    sqlite3DbFree(db, pItem->zSpan);
68784  }
68785  sqlite3DbFree(db, pList->a);
68786  sqlite3DbFree(db, pList);
68787}
68788
68789/*
68790** These routines are Walker callbacks.  Walker.u.pi is a pointer
68791** to an integer.  These routines are checking an expression to see
68792** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
68793** not constant.
68794**
68795** These callback routines are used to implement the following:
68796**
68797**     sqlite3ExprIsConstant()
68798**     sqlite3ExprIsConstantNotJoin()
68799**     sqlite3ExprIsConstantOrFunction()
68800**
68801*/
68802static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
68803
68804  /* If pWalker->u.i is 3 then any term of the expression that comes from
68805  ** the ON or USING clauses of a join disqualifies the expression
68806  ** from being considered constant. */
68807  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
68808    pWalker->u.i = 0;
68809    return WRC_Abort;
68810  }
68811
68812  switch( pExpr->op ){
68813    /* Consider functions to be constant if all their arguments are constant
68814    ** and pWalker->u.i==2 */
68815    case TK_FUNCTION:
68816      if( pWalker->u.i==2 ) return 0;
68817      /* Fall through */
68818    case TK_ID:
68819    case TK_COLUMN:
68820    case TK_AGG_FUNCTION:
68821    case TK_AGG_COLUMN:
68822      testcase( pExpr->op==TK_ID );
68823      testcase( pExpr->op==TK_COLUMN );
68824      testcase( pExpr->op==TK_AGG_FUNCTION );
68825      testcase( pExpr->op==TK_AGG_COLUMN );
68826      pWalker->u.i = 0;
68827      return WRC_Abort;
68828    default:
68829      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
68830      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
68831      return WRC_Continue;
68832  }
68833}
68834static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
68835  UNUSED_PARAMETER(NotUsed);
68836  pWalker->u.i = 0;
68837  return WRC_Abort;
68838}
68839static int exprIsConst(Expr *p, int initFlag){
68840  Walker w;
68841  w.u.i = initFlag;
68842  w.xExprCallback = exprNodeIsConstant;
68843  w.xSelectCallback = selectNodeIsConstant;
68844  sqlite3WalkExpr(&w, p);
68845  return w.u.i;
68846}
68847
68848/*
68849** Walk an expression tree.  Return 1 if the expression is constant
68850** and 0 if it involves variables or function calls.
68851**
68852** For the purposes of this function, a double-quoted string (ex: "abc")
68853** is considered a variable but a single-quoted string (ex: 'abc') is
68854** a constant.
68855*/
68856SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
68857  return exprIsConst(p, 1);
68858}
68859
68860/*
68861** Walk an expression tree.  Return 1 if the expression is constant
68862** that does no originate from the ON or USING clauses of a join.
68863** Return 0 if it involves variables or function calls or terms from
68864** an ON or USING clause.
68865*/
68866SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
68867  return exprIsConst(p, 3);
68868}
68869
68870/*
68871** Walk an expression tree.  Return 1 if the expression is constant
68872** or a function call with constant arguments.  Return and 0 if there
68873** are any variables.
68874**
68875** For the purposes of this function, a double-quoted string (ex: "abc")
68876** is considered a variable but a single-quoted string (ex: 'abc') is
68877** a constant.
68878*/
68879SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
68880  return exprIsConst(p, 2);
68881}
68882
68883/*
68884** If the expression p codes a constant integer that is small enough
68885** to fit in a 32-bit integer, return 1 and put the value of the integer
68886** in *pValue.  If the expression is not an integer or if it is too big
68887** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
68888*/
68889SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
68890  int rc = 0;
68891  if( p->flags & EP_IntValue ){
68892    *pValue = p->u.iValue;
68893    return 1;
68894  }
68895  switch( p->op ){
68896    case TK_INTEGER: {
68897      rc = sqlite3GetInt32(p->u.zToken, pValue);
68898      assert( rc==0 );
68899      break;
68900    }
68901    case TK_UPLUS: {
68902      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
68903      break;
68904    }
68905    case TK_UMINUS: {
68906      int v;
68907      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
68908        *pValue = -v;
68909        rc = 1;
68910      }
68911      break;
68912    }
68913    default: break;
68914  }
68915  if( rc ){
68916    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
68917               || (p->flags2 & EP2_MallocedToken)==0 );
68918    p->op = TK_INTEGER;
68919    p->flags |= EP_IntValue;
68920    p->u.iValue = *pValue;
68921  }
68922  return rc;
68923}
68924
68925/*
68926** Return FALSE if there is no chance that the expression can be NULL.
68927**
68928** If the expression might be NULL or if the expression is too complex
68929** to tell return TRUE.
68930**
68931** This routine is used as an optimization, to skip OP_IsNull opcodes
68932** when we know that a value cannot be NULL.  Hence, a false positive
68933** (returning TRUE when in fact the expression can never be NULL) might
68934** be a small performance hit but is otherwise harmless.  On the other
68935** hand, a false negative (returning FALSE when the result could be NULL)
68936** will likely result in an incorrect answer.  So when in doubt, return
68937** TRUE.
68938*/
68939SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
68940  u8 op;
68941  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
68942  op = p->op;
68943  if( op==TK_REGISTER ) op = p->op2;
68944  switch( op ){
68945    case TK_INTEGER:
68946    case TK_STRING:
68947    case TK_FLOAT:
68948    case TK_BLOB:
68949      return 0;
68950    default:
68951      return 1;
68952  }
68953}
68954
68955/*
68956** Generate an OP_IsNull instruction that tests register iReg and jumps
68957** to location iDest if the value in iReg is NULL.  The value in iReg
68958** was computed by pExpr.  If we can look at pExpr at compile-time and
68959** determine that it can never generate a NULL, then the OP_IsNull operation
68960** can be omitted.
68961*/
68962SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
68963  Vdbe *v,            /* The VDBE under construction */
68964  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
68965  int iReg,           /* Test the value in this register for NULL */
68966  int iDest           /* Jump here if the value is null */
68967){
68968  if( sqlite3ExprCanBeNull(pExpr) ){
68969    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
68970  }
68971}
68972
68973/*
68974** Return TRUE if the given expression is a constant which would be
68975** unchanged by OP_Affinity with the affinity given in the second
68976** argument.
68977**
68978** This routine is used to determine if the OP_Affinity operation
68979** can be omitted.  When in doubt return FALSE.  A false negative
68980** is harmless.  A false positive, however, can result in the wrong
68981** answer.
68982*/
68983SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
68984  u8 op;
68985  if( aff==SQLITE_AFF_NONE ) return 1;
68986  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
68987  op = p->op;
68988  if( op==TK_REGISTER ) op = p->op2;
68989  switch( op ){
68990    case TK_INTEGER: {
68991      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
68992    }
68993    case TK_FLOAT: {
68994      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
68995    }
68996    case TK_STRING: {
68997      return aff==SQLITE_AFF_TEXT;
68998    }
68999    case TK_BLOB: {
69000      return 1;
69001    }
69002    case TK_COLUMN: {
69003      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
69004      return p->iColumn<0
69005          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
69006    }
69007    default: {
69008      return 0;
69009    }
69010  }
69011}
69012
69013/*
69014** Return TRUE if the given string is a row-id column name.
69015*/
69016SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
69017  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
69018  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
69019  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
69020  return 0;
69021}
69022
69023/*
69024** Return true if we are able to the IN operator optimization on a
69025** query of the form
69026**
69027**       x IN (SELECT ...)
69028**
69029** Where the SELECT... clause is as specified by the parameter to this
69030** routine.
69031**
69032** The Select object passed in has already been preprocessed and no
69033** errors have been found.
69034*/
69035#ifndef SQLITE_OMIT_SUBQUERY
69036static int isCandidateForInOpt(Select *p){
69037  SrcList *pSrc;
69038  ExprList *pEList;
69039  Table *pTab;
69040  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
69041  if( p->pPrior ) return 0;              /* Not a compound SELECT */
69042  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
69043    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
69044    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
69045    return 0; /* No DISTINCT keyword and no aggregate functions */
69046  }
69047  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
69048  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
69049  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
69050  if( p->pWhere ) return 0;              /* Has no WHERE clause */
69051  pSrc = p->pSrc;
69052  assert( pSrc!=0 );
69053  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
69054  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
69055  pTab = pSrc->a[0].pTab;
69056  if( NEVER(pTab==0) ) return 0;
69057  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
69058  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
69059  pEList = p->pEList;
69060  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
69061  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
69062  return 1;
69063}
69064#endif /* SQLITE_OMIT_SUBQUERY */
69065
69066/*
69067** This function is used by the implementation of the IN (...) operator.
69068** It's job is to find or create a b-tree structure that may be used
69069** either to test for membership of the (...) set or to iterate through
69070** its members, skipping duplicates.
69071**
69072** The index of the cursor opened on the b-tree (database table, database index
69073** or ephermal table) is stored in pX->iTable before this function returns.
69074** The returned value of this function indicates the b-tree type, as follows:
69075**
69076**   IN_INDEX_ROWID - The cursor was opened on a database table.
69077**   IN_INDEX_INDEX - The cursor was opened on a database index.
69078**   IN_INDEX_EPH -   The cursor was opened on a specially created and
69079**                    populated epheremal table.
69080**
69081** An existing b-tree may only be used if the SELECT is of the simple
69082** form:
69083**
69084**     SELECT <column> FROM <table>
69085**
69086** If the prNotFound parameter is 0, then the b-tree will be used to iterate
69087** through the set members, skipping any duplicates. In this case an
69088** epheremal table must be used unless the selected <column> is guaranteed
69089** to be unique - either because it is an INTEGER PRIMARY KEY or it
69090** has a UNIQUE constraint or UNIQUE index.
69091**
69092** If the prNotFound parameter is not 0, then the b-tree will be used
69093** for fast set membership tests. In this case an epheremal table must
69094** be used unless <column> is an INTEGER PRIMARY KEY or an index can
69095** be found with <column> as its left-most column.
69096**
69097** When the b-tree is being used for membership tests, the calling function
69098** needs to know whether or not the structure contains an SQL NULL
69099** value in order to correctly evaluate expressions like "X IN (Y, Z)".
69100** If there is any chance that the (...) might contain a NULL value at
69101** runtime, then a register is allocated and the register number written
69102** to *prNotFound. If there is no chance that the (...) contains a
69103** NULL value, then *prNotFound is left unchanged.
69104**
69105** If a register is allocated and its location stored in *prNotFound, then
69106** its initial value is NULL.  If the (...) does not remain constant
69107** for the duration of the query (i.e. the SELECT within the (...)
69108** is a correlated subquery) then the value of the allocated register is
69109** reset to NULL each time the subquery is rerun. This allows the
69110** caller to use vdbe code equivalent to the following:
69111**
69112**   if( register==NULL ){
69113**     has_null = <test if data structure contains null>
69114**     register = 1
69115**   }
69116**
69117** in order to avoid running the <test if data structure contains null>
69118** test more often than is necessary.
69119*/
69120#ifndef SQLITE_OMIT_SUBQUERY
69121SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
69122  Select *p;                            /* SELECT to the right of IN operator */
69123  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
69124  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
69125  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
69126
69127  assert( pX->op==TK_IN );
69128
69129  /* Check to see if an existing table or index can be used to
69130  ** satisfy the query.  This is preferable to generating a new
69131  ** ephemeral table.
69132  */
69133  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
69134  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
69135    sqlite3 *db = pParse->db;              /* Database connection */
69136    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
69137    int iCol = pExpr->iColumn;             /* Index of column <column> */
69138    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
69139    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
69140    int iDb;                               /* Database idx for pTab */
69141
69142    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
69143    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69144    sqlite3CodeVerifySchema(pParse, iDb);
69145    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
69146
69147    /* This function is only called from two places. In both cases the vdbe
69148    ** has already been allocated. So assume sqlite3GetVdbe() is always
69149    ** successful here.
69150    */
69151    assert(v);
69152    if( iCol<0 ){
69153      int iMem = ++pParse->nMem;
69154      int iAddr;
69155
69156      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
69157      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
69158
69159      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
69160      eType = IN_INDEX_ROWID;
69161
69162      sqlite3VdbeJumpHere(v, iAddr);
69163    }else{
69164      Index *pIdx;                         /* Iterator variable */
69165
69166      /* The collation sequence used by the comparison. If an index is to
69167      ** be used in place of a temp-table, it must be ordered according
69168      ** to this collation sequence.  */
69169      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
69170
69171      /* Check that the affinity that will be used to perform the
69172      ** comparison is the same as the affinity of the column. If
69173      ** it is not, it is not possible to use any index.
69174      */
69175      char aff = comparisonAffinity(pX);
69176      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
69177
69178      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
69179        if( (pIdx->aiColumn[0]==iCol)
69180         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
69181         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
69182        ){
69183          int iMem = ++pParse->nMem;
69184          int iAddr;
69185          char *pKey;
69186
69187          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
69188          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
69189          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
69190
69191          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
69192                               pKey,P4_KEYINFO_HANDOFF);
69193          VdbeComment((v, "%s", pIdx->zName));
69194          eType = IN_INDEX_INDEX;
69195
69196          sqlite3VdbeJumpHere(v, iAddr);
69197          if( prNotFound && !pTab->aCol[iCol].notNull ){
69198            *prNotFound = ++pParse->nMem;
69199          }
69200        }
69201      }
69202    }
69203  }
69204
69205  if( eType==0 ){
69206    /* Could not found an existing table or index to use as the RHS b-tree.
69207    ** We will have to generate an ephemeral table to do the job.
69208    */
69209    double savedNQueryLoop = pParse->nQueryLoop;
69210    int rMayHaveNull = 0;
69211    eType = IN_INDEX_EPH;
69212    if( prNotFound ){
69213      *prNotFound = rMayHaveNull = ++pParse->nMem;
69214    }else{
69215      testcase( pParse->nQueryLoop>(double)1 );
69216      pParse->nQueryLoop = (double)1;
69217      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
69218        eType = IN_INDEX_ROWID;
69219      }
69220    }
69221    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
69222    pParse->nQueryLoop = savedNQueryLoop;
69223  }else{
69224    pX->iTable = iTab;
69225  }
69226  return eType;
69227}
69228#endif
69229
69230/*
69231** Generate code for scalar subqueries used as an expression
69232** and IN operators.  Examples:
69233**
69234**     (SELECT a FROM b)          -- subquery
69235**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
69236**     x IN (4,5,11)              -- IN operator with list on right-hand side
69237**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
69238**
69239** The pExpr parameter describes the expression that contains the IN
69240** operator or subquery.
69241**
69242** If parameter isRowid is non-zero, then expression pExpr is guaranteed
69243** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
69244** to some integer key column of a table B-Tree. In this case, use an
69245** intkey B-Tree to store the set of IN(...) values instead of the usual
69246** (slower) variable length keys B-Tree.
69247**
69248** If rMayHaveNull is non-zero, that means that the operation is an IN
69249** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
69250** Furthermore, the IN is in a WHERE clause and that we really want
69251** to iterate over the RHS of the IN operator in order to quickly locate
69252** all corresponding LHS elements.  All this routine does is initialize
69253** the register given by rMayHaveNull to NULL.  Calling routines will take
69254** care of changing this register value to non-NULL if the RHS is NULL-free.
69255**
69256** If rMayHaveNull is zero, that means that the subquery is being used
69257** for membership testing only.  There is no need to initialize any
69258** registers to indicate the presense or absence of NULLs on the RHS.
69259**
69260** For a SELECT or EXISTS operator, return the register that holds the
69261** result.  For IN operators or if an error occurs, the return value is 0.
69262*/
69263#ifndef SQLITE_OMIT_SUBQUERY
69264SQLITE_PRIVATE int sqlite3CodeSubselect(
69265  Parse *pParse,          /* Parsing context */
69266  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
69267  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
69268  int isRowid             /* If true, LHS of IN operator is a rowid */
69269){
69270  int testAddr = 0;                       /* One-time test address */
69271  int rReg = 0;                           /* Register storing resulting */
69272  Vdbe *v = sqlite3GetVdbe(pParse);
69273  if( NEVER(v==0) ) return 0;
69274  sqlite3ExprCachePush(pParse);
69275
69276  /* This code must be run in its entirety every time it is encountered
69277  ** if any of the following is true:
69278  **
69279  **    *  The right-hand side is a correlated subquery
69280  **    *  The right-hand side is an expression list containing variables
69281  **    *  We are inside a trigger
69282  **
69283  ** If all of the above are false, then we can run this code just once
69284  ** save the results, and reuse the same result on subsequent invocations.
69285  */
69286  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
69287    int mem = ++pParse->nMem;
69288    sqlite3VdbeAddOp1(v, OP_If, mem);
69289    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
69290    assert( testAddr>0 || pParse->db->mallocFailed );
69291  }
69292
69293  switch( pExpr->op ){
69294    case TK_IN: {
69295      char affinity;
69296      KeyInfo keyInfo;
69297      int addr;        /* Address of OP_OpenEphemeral instruction */
69298      Expr *pLeft = pExpr->pLeft;
69299
69300      if( rMayHaveNull ){
69301        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
69302      }
69303
69304      affinity = sqlite3ExprAffinity(pLeft);
69305
69306      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
69307      ** expression it is handled the same way.  An ephemeral table is
69308      ** filled with single-field index keys representing the results
69309      ** from the SELECT or the <exprlist>.
69310      **
69311      ** If the 'x' expression is a column value, or the SELECT...
69312      ** statement returns a column value, then the affinity of that
69313      ** column is used to build the index keys. If both 'x' and the
69314      ** SELECT... statement are columns, then numeric affinity is used
69315      ** if either column has NUMERIC or INTEGER affinity. If neither
69316      ** 'x' nor the SELECT... statement are columns, then numeric affinity
69317      ** is used.
69318      */
69319      pExpr->iTable = pParse->nTab++;
69320      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
69321      memset(&keyInfo, 0, sizeof(keyInfo));
69322      keyInfo.nField = 1;
69323
69324      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69325        /* Case 1:     expr IN (SELECT ...)
69326        **
69327        ** Generate code to write the results of the select into the temporary
69328        ** table allocated and opened above.
69329        */
69330        SelectDest dest;
69331        ExprList *pEList;
69332
69333        assert( !isRowid );
69334        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
69335        dest.affinity = (u8)affinity;
69336        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
69337        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
69338          return 0;
69339        }
69340        pEList = pExpr->x.pSelect->pEList;
69341        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
69342          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
69343              pEList->a[0].pExpr);
69344        }
69345      }else if( ALWAYS(pExpr->x.pList!=0) ){
69346        /* Case 2:     expr IN (exprlist)
69347        **
69348        ** For each expression, build an index key from the evaluation and
69349        ** store it in the temporary table. If <expr> is a column, then use
69350        ** that columns affinity when building index keys. If <expr> is not
69351        ** a column, use numeric affinity.
69352        */
69353        int i;
69354        ExprList *pList = pExpr->x.pList;
69355        struct ExprList_item *pItem;
69356        int r1, r2, r3;
69357
69358        if( !affinity ){
69359          affinity = SQLITE_AFF_NONE;
69360        }
69361        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
69362
69363        /* Loop through each expression in <exprlist>. */
69364        r1 = sqlite3GetTempReg(pParse);
69365        r2 = sqlite3GetTempReg(pParse);
69366        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
69367        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
69368          Expr *pE2 = pItem->pExpr;
69369          int iValToIns;
69370
69371          /* If the expression is not constant then we will need to
69372          ** disable the test that was generated above that makes sure
69373          ** this code only executes once.  Because for a non-constant
69374          ** expression we need to rerun this code each time.
69375          */
69376          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
69377            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
69378            testAddr = 0;
69379          }
69380
69381          /* Evaluate the expression and insert it into the temp table */
69382          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
69383            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
69384          }else{
69385            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
69386            if( isRowid ){
69387              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
69388                                sqlite3VdbeCurrentAddr(v)+2);
69389              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
69390            }else{
69391              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
69392              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
69393              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
69394            }
69395          }
69396        }
69397        sqlite3ReleaseTempReg(pParse, r1);
69398        sqlite3ReleaseTempReg(pParse, r2);
69399      }
69400      if( !isRowid ){
69401        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
69402      }
69403      break;
69404    }
69405
69406    case TK_EXISTS:
69407    case TK_SELECT:
69408    default: {
69409      /* If this has to be a scalar SELECT.  Generate code to put the
69410      ** value of this select in a memory cell and record the number
69411      ** of the memory cell in iColumn.  If this is an EXISTS, write
69412      ** an integer 0 (not exists) or 1 (exists) into a memory cell
69413      ** and record that memory cell in iColumn.
69414      */
69415      Select *pSel;                         /* SELECT statement to encode */
69416      SelectDest dest;                      /* How to deal with SELECt result */
69417
69418      testcase( pExpr->op==TK_EXISTS );
69419      testcase( pExpr->op==TK_SELECT );
69420      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
69421
69422      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
69423      pSel = pExpr->x.pSelect;
69424      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
69425      if( pExpr->op==TK_SELECT ){
69426        dest.eDest = SRT_Mem;
69427        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
69428        VdbeComment((v, "Init subquery result"));
69429      }else{
69430        dest.eDest = SRT_Exists;
69431        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
69432        VdbeComment((v, "Init EXISTS result"));
69433      }
69434      sqlite3ExprDelete(pParse->db, pSel->pLimit);
69435      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
69436                                  &sqlite3IntTokens[1]);
69437      if( sqlite3Select(pParse, pSel, &dest) ){
69438        return 0;
69439      }
69440      rReg = dest.iParm;
69441      ExprSetIrreducible(pExpr);
69442      break;
69443    }
69444  }
69445
69446  if( testAddr ){
69447    sqlite3VdbeJumpHere(v, testAddr-1);
69448  }
69449  sqlite3ExprCachePop(pParse, 1);
69450
69451  return rReg;
69452}
69453#endif /* SQLITE_OMIT_SUBQUERY */
69454
69455#ifndef SQLITE_OMIT_SUBQUERY
69456/*
69457** Generate code for an IN expression.
69458**
69459**      x IN (SELECT ...)
69460**      x IN (value, value, ...)
69461**
69462** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
69463** is an array of zero or more values.  The expression is true if the LHS is
69464** contained within the RHS.  The value of the expression is unknown (NULL)
69465** if the LHS is NULL or if the LHS is not contained within the RHS and the
69466** RHS contains one or more NULL values.
69467**
69468** This routine generates code will jump to destIfFalse if the LHS is not
69469** contained within the RHS.  If due to NULLs we cannot determine if the LHS
69470** is contained in the RHS then jump to destIfNull.  If the LHS is contained
69471** within the RHS then fall through.
69472*/
69473static void sqlite3ExprCodeIN(
69474  Parse *pParse,        /* Parsing and code generating context */
69475  Expr *pExpr,          /* The IN expression */
69476  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
69477  int destIfNull        /* Jump here if the results are unknown due to NULLs */
69478){
69479  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
69480  char affinity;        /* Comparison affinity to use */
69481  int eType;            /* Type of the RHS */
69482  int r1;               /* Temporary use register */
69483  Vdbe *v;              /* Statement under construction */
69484
69485  /* Compute the RHS.   After this step, the table with cursor
69486  ** pExpr->iTable will contains the values that make up the RHS.
69487  */
69488  v = pParse->pVdbe;
69489  assert( v!=0 );       /* OOM detected prior to this routine */
69490  VdbeNoopComment((v, "begin IN expr"));
69491  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
69492
69493  /* Figure out the affinity to use to create a key from the results
69494  ** of the expression. affinityStr stores a static string suitable for
69495  ** P4 of OP_MakeRecord.
69496  */
69497  affinity = comparisonAffinity(pExpr);
69498
69499  /* Code the LHS, the <expr> from "<expr> IN (...)".
69500  */
69501  sqlite3ExprCachePush(pParse);
69502  r1 = sqlite3GetTempReg(pParse);
69503  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
69504
69505  /* If the LHS is NULL, then the result is either false or NULL depending
69506  ** on whether the RHS is empty or not, respectively.
69507  */
69508  if( destIfNull==destIfFalse ){
69509    /* Shortcut for the common case where the false and NULL outcomes are
69510    ** the same. */
69511    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
69512  }else{
69513    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
69514    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
69515    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
69516    sqlite3VdbeJumpHere(v, addr1);
69517  }
69518
69519  if( eType==IN_INDEX_ROWID ){
69520    /* In this case, the RHS is the ROWID of table b-tree
69521    */
69522    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
69523    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
69524  }else{
69525    /* In this case, the RHS is an index b-tree.
69526    */
69527    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
69528
69529    /* If the set membership test fails, then the result of the
69530    ** "x IN (...)" expression must be either 0 or NULL. If the set
69531    ** contains no NULL values, then the result is 0. If the set
69532    ** contains one or more NULL values, then the result of the
69533    ** expression is also NULL.
69534    */
69535    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
69536      /* This branch runs if it is known at compile time that the RHS
69537      ** cannot contain NULL values. This happens as the result
69538      ** of a "NOT NULL" constraint in the database schema.
69539      **
69540      ** Also run this branch if NULL is equivalent to FALSE
69541      ** for this particular IN operator.
69542      */
69543      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
69544
69545    }else{
69546      /* In this branch, the RHS of the IN might contain a NULL and
69547      ** the presence of a NULL on the RHS makes a difference in the
69548      ** outcome.
69549      */
69550      int j1, j2, j3;
69551
69552      /* First check to see if the LHS is contained in the RHS.  If so,
69553      ** then the presence of NULLs in the RHS does not matter, so jump
69554      ** over all of the code that follows.
69555      */
69556      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
69557
69558      /* Here we begin generating code that runs if the LHS is not
69559      ** contained within the RHS.  Generate additional code that
69560      ** tests the RHS for NULLs.  If the RHS contains a NULL then
69561      ** jump to destIfNull.  If there are no NULLs in the RHS then
69562      ** jump to destIfFalse.
69563      */
69564      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
69565      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
69566      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
69567      sqlite3VdbeJumpHere(v, j3);
69568      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
69569      sqlite3VdbeJumpHere(v, j2);
69570
69571      /* Jump to the appropriate target depending on whether or not
69572      ** the RHS contains a NULL
69573      */
69574      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
69575      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
69576
69577      /* The OP_Found at the top of this branch jumps here when true,
69578      ** causing the overall IN expression evaluation to fall through.
69579      */
69580      sqlite3VdbeJumpHere(v, j1);
69581    }
69582  }
69583  sqlite3ReleaseTempReg(pParse, r1);
69584  sqlite3ExprCachePop(pParse, 1);
69585  VdbeComment((v, "end IN expr"));
69586}
69587#endif /* SQLITE_OMIT_SUBQUERY */
69588
69589/*
69590** Duplicate an 8-byte value
69591*/
69592static char *dup8bytes(Vdbe *v, const char *in){
69593  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
69594  if( out ){
69595    memcpy(out, in, 8);
69596  }
69597  return out;
69598}
69599
69600#ifndef SQLITE_OMIT_FLOATING_POINT
69601/*
69602** Generate an instruction that will put the floating point
69603** value described by z[0..n-1] into register iMem.
69604**
69605** The z[] string will probably not be zero-terminated.  But the
69606** z[n] character is guaranteed to be something that does not look
69607** like the continuation of the number.
69608*/
69609static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
69610  if( ALWAYS(z!=0) ){
69611    double value;
69612    char *zV;
69613    sqlite3AtoF(z, &value);
69614    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
69615    if( negateFlag ) value = -value;
69616    zV = dup8bytes(v, (char*)&value);
69617    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
69618  }
69619}
69620#endif
69621
69622
69623/*
69624** Generate an instruction that will put the integer describe by
69625** text z[0..n-1] into register iMem.
69626**
69627** The z[] string will probably not be zero-terminated.  But the
69628** z[n] character is guaranteed to be something that does not look
69629** like the continuation of the number.
69630*/
69631static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
69632  Vdbe *v = pParse->pVdbe;
69633  if( pExpr->flags & EP_IntValue ){
69634    int i = pExpr->u.iValue;
69635    if( negFlag ) i = -i;
69636    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
69637  }else{
69638    const char *z = pExpr->u.zToken;
69639    assert( z!=0 );
69640    if( sqlite3FitsIn64Bits(z, negFlag) ){
69641      i64 value;
69642      char *zV;
69643      sqlite3Atoi64(z, &value);
69644      if( negFlag ) value = -value;
69645      zV = dup8bytes(v, (char*)&value);
69646      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
69647    }else{
69648#ifdef SQLITE_OMIT_FLOATING_POINT
69649      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
69650#else
69651      codeReal(v, z, negFlag, iMem);
69652#endif
69653    }
69654  }
69655}
69656
69657/*
69658** Clear a cache entry.
69659*/
69660static void cacheEntryClear(Parse *pParse, struct yColCache *p){
69661  if( p->tempReg ){
69662    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
69663      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
69664    }
69665    p->tempReg = 0;
69666  }
69667}
69668
69669
69670/*
69671** Record in the column cache that a particular column from a
69672** particular table is stored in a particular register.
69673*/
69674SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
69675  int i;
69676  int minLru;
69677  int idxLru;
69678  struct yColCache *p;
69679
69680  assert( iReg>0 );  /* Register numbers are always positive */
69681  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
69682
69683  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
69684  ** for testing only - to verify that SQLite always gets the same answer
69685  ** with and without the column cache.
69686  */
69687  if( pParse->db->flags & SQLITE_ColumnCache ) return;
69688
69689  /* First replace any existing entry.
69690  **
69691  ** Actually, the way the column cache is currently used, we are guaranteed
69692  ** that the object will never already be in cache.  Verify this guarantee.
69693  */
69694#ifndef NDEBUG
69695  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69696#if 0 /* This code wold remove the entry from the cache if it existed */
69697    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
69698      cacheEntryClear(pParse, p);
69699      p->iLevel = pParse->iCacheLevel;
69700      p->iReg = iReg;
69701      p->lru = pParse->iCacheCnt++;
69702      return;
69703    }
69704#endif
69705    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
69706  }
69707#endif
69708
69709  /* Find an empty slot and replace it */
69710  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69711    if( p->iReg==0 ){
69712      p->iLevel = pParse->iCacheLevel;
69713      p->iTable = iTab;
69714      p->iColumn = iCol;
69715      p->iReg = iReg;
69716      p->tempReg = 0;
69717      p->lru = pParse->iCacheCnt++;
69718      return;
69719    }
69720  }
69721
69722  /* Replace the last recently used */
69723  minLru = 0x7fffffff;
69724  idxLru = -1;
69725  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69726    if( p->lru<minLru ){
69727      idxLru = i;
69728      minLru = p->lru;
69729    }
69730  }
69731  if( ALWAYS(idxLru>=0) ){
69732    p = &pParse->aColCache[idxLru];
69733    p->iLevel = pParse->iCacheLevel;
69734    p->iTable = iTab;
69735    p->iColumn = iCol;
69736    p->iReg = iReg;
69737    p->tempReg = 0;
69738    p->lru = pParse->iCacheCnt++;
69739    return;
69740  }
69741}
69742
69743/*
69744** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
69745** Purge the range of registers from the column cache.
69746*/
69747SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
69748  int i;
69749  int iLast = iReg + nReg - 1;
69750  struct yColCache *p;
69751  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69752    int r = p->iReg;
69753    if( r>=iReg && r<=iLast ){
69754      cacheEntryClear(pParse, p);
69755      p->iReg = 0;
69756    }
69757  }
69758}
69759
69760/*
69761** Remember the current column cache context.  Any new entries added
69762** added to the column cache after this call are removed when the
69763** corresponding pop occurs.
69764*/
69765SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
69766  pParse->iCacheLevel++;
69767}
69768
69769/*
69770** Remove from the column cache any entries that were added since the
69771** the previous N Push operations.  In other words, restore the cache
69772** to the state it was in N Pushes ago.
69773*/
69774SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
69775  int i;
69776  struct yColCache *p;
69777  assert( N>0 );
69778  assert( pParse->iCacheLevel>=N );
69779  pParse->iCacheLevel -= N;
69780  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69781    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
69782      cacheEntryClear(pParse, p);
69783      p->iReg = 0;
69784    }
69785  }
69786}
69787
69788/*
69789** When a cached column is reused, make sure that its register is
69790** no longer available as a temp register.  ticket #3879:  that same
69791** register might be in the cache in multiple places, so be sure to
69792** get them all.
69793*/
69794static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
69795  int i;
69796  struct yColCache *p;
69797  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69798    if( p->iReg==iReg ){
69799      p->tempReg = 0;
69800    }
69801  }
69802}
69803
69804/*
69805** Generate code to extract the value of the iCol-th column of a table.
69806*/
69807SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
69808  Vdbe *v,        /* The VDBE under construction */
69809  Table *pTab,    /* The table containing the value */
69810  int iTabCur,    /* The cursor for this table */
69811  int iCol,       /* Index of the column to extract */
69812  int regOut      /* Extract the valud into this register */
69813){
69814  if( iCol<0 || iCol==pTab->iPKey ){
69815    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
69816  }else{
69817    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
69818    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
69819  }
69820  if( iCol>=0 ){
69821    sqlite3ColumnDefault(v, pTab, iCol, regOut);
69822  }
69823}
69824
69825/*
69826** Generate code that will extract the iColumn-th column from
69827** table pTab and store the column value in a register.  An effort
69828** is made to store the column value in register iReg, but this is
69829** not guaranteed.  The location of the column value is returned.
69830**
69831** There must be an open cursor to pTab in iTable when this routine
69832** is called.  If iColumn<0 then code is generated that extracts the rowid.
69833*/
69834SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
69835  Parse *pParse,   /* Parsing and code generating context */
69836  Table *pTab,     /* Description of the table we are reading from */
69837  int iColumn,     /* Index of the table column */
69838  int iTable,      /* The cursor pointing to the table */
69839  int iReg         /* Store results here */
69840){
69841  Vdbe *v = pParse->pVdbe;
69842  int i;
69843  struct yColCache *p;
69844
69845  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69846    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
69847      p->lru = pParse->iCacheCnt++;
69848      sqlite3ExprCachePinRegister(pParse, p->iReg);
69849      return p->iReg;
69850    }
69851  }
69852  assert( v!=0 );
69853  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
69854  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
69855  return iReg;
69856}
69857
69858/*
69859** Clear all column cache entries.
69860*/
69861SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
69862  int i;
69863  struct yColCache *p;
69864
69865  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69866    if( p->iReg ){
69867      cacheEntryClear(pParse, p);
69868      p->iReg = 0;
69869    }
69870  }
69871}
69872
69873/*
69874** Record the fact that an affinity change has occurred on iCount
69875** registers starting with iStart.
69876*/
69877SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
69878  sqlite3ExprCacheRemove(pParse, iStart, iCount);
69879}
69880
69881/*
69882** Generate code to move content from registers iFrom...iFrom+nReg-1
69883** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
69884*/
69885SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
69886  int i;
69887  struct yColCache *p;
69888  if( NEVER(iFrom==iTo) ) return;
69889  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
69890  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69891    int x = p->iReg;
69892    if( x>=iFrom && x<iFrom+nReg ){
69893      p->iReg += iTo-iFrom;
69894    }
69895  }
69896}
69897
69898/*
69899** Generate code to copy content from registers iFrom...iFrom+nReg-1
69900** over to iTo..iTo+nReg-1.
69901*/
69902SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
69903  int i;
69904  if( NEVER(iFrom==iTo) ) return;
69905  for(i=0; i<nReg; i++){
69906    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
69907  }
69908}
69909
69910#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
69911/*
69912** Return true if any register in the range iFrom..iTo (inclusive)
69913** is used as part of the column cache.
69914**
69915** This routine is used within assert() and testcase() macros only
69916** and does not appear in a normal build.
69917*/
69918static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
69919  int i;
69920  struct yColCache *p;
69921  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
69922    int r = p->iReg;
69923    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
69924  }
69925  return 0;
69926}
69927#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
69928
69929/*
69930** If the last instruction coded is an ephemeral copy of any of
69931** the registers in the nReg registers beginning with iReg, then
69932** convert the last instruction from OP_SCopy to OP_Copy.
69933*/
69934SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
69935  VdbeOp *pOp;
69936  Vdbe *v;
69937
69938  assert( pParse->db->mallocFailed==0 );
69939  v = pParse->pVdbe;
69940  assert( v!=0 );
69941  pOp = sqlite3VdbeGetOp(v, -1);
69942  assert( pOp!=0 );
69943  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
69944    pOp->opcode = OP_Copy;
69945  }
69946}
69947
69948/*
69949** Generate code to store the value of the iAlias-th alias in register
69950** target.  The first time this is called, pExpr is evaluated to compute
69951** the value of the alias.  The value is stored in an auxiliary register
69952** and the number of that register is returned.  On subsequent calls,
69953** the register number is returned without generating any code.
69954**
69955** Note that in order for this to work, code must be generated in the
69956** same order that it is executed.
69957**
69958** Aliases are numbered starting with 1.  So iAlias is in the range
69959** of 1 to pParse->nAlias inclusive.
69960**
69961** pParse->aAlias[iAlias-1] records the register number where the value
69962** of the iAlias-th alias is stored.  If zero, that means that the
69963** alias has not yet been computed.
69964*/
69965static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
69966#if 0
69967  sqlite3 *db = pParse->db;
69968  int iReg;
69969  if( pParse->nAliasAlloc<pParse->nAlias ){
69970    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
69971                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
69972    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
69973    if( db->mallocFailed ) return 0;
69974    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
69975           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
69976    pParse->nAliasAlloc = pParse->nAlias;
69977  }
69978  assert( iAlias>0 && iAlias<=pParse->nAlias );
69979  iReg = pParse->aAlias[iAlias-1];
69980  if( iReg==0 ){
69981    if( pParse->iCacheLevel>0 ){
69982      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69983    }else{
69984      iReg = ++pParse->nMem;
69985      sqlite3ExprCode(pParse, pExpr, iReg);
69986      pParse->aAlias[iAlias-1] = iReg;
69987    }
69988  }
69989  return iReg;
69990#else
69991  UNUSED_PARAMETER(iAlias);
69992  return sqlite3ExprCodeTarget(pParse, pExpr, target);
69993#endif
69994}
69995
69996/*
69997** Generate code into the current Vdbe to evaluate the given
69998** expression.  Attempt to store the results in register "target".
69999** Return the register where results are stored.
70000**
70001** With this routine, there is no guarantee that results will
70002** be stored in target.  The result might be stored in some other
70003** register if it is convenient to do so.  The calling function
70004** must check the return code and move the results to the desired
70005** register.
70006*/
70007SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
70008  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
70009  int op;                   /* The opcode being coded */
70010  int inReg = target;       /* Results stored in register inReg */
70011  int regFree1 = 0;         /* If non-zero free this temporary register */
70012  int regFree2 = 0;         /* If non-zero free this temporary register */
70013  int r1, r2, r3, r4;       /* Various register numbers */
70014  sqlite3 *db = pParse->db; /* The database connection */
70015
70016  assert( target>0 && target<=pParse->nMem );
70017  if( v==0 ){
70018    assert( pParse->db->mallocFailed );
70019    return 0;
70020  }
70021
70022  if( pExpr==0 ){
70023    op = TK_NULL;
70024  }else{
70025    op = pExpr->op;
70026  }
70027  switch( op ){
70028    case TK_AGG_COLUMN: {
70029      AggInfo *pAggInfo = pExpr->pAggInfo;
70030      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
70031      if( !pAggInfo->directMode ){
70032        assert( pCol->iMem>0 );
70033        inReg = pCol->iMem;
70034        break;
70035      }else if( pAggInfo->useSortingIdx ){
70036        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
70037                              pCol->iSorterColumn, target);
70038        break;
70039      }
70040      /* Otherwise, fall thru into the TK_COLUMN case */
70041    }
70042    case TK_COLUMN: {
70043      if( pExpr->iTable<0 ){
70044        /* This only happens when coding check constraints */
70045        assert( pParse->ckBase>0 );
70046        inReg = pExpr->iColumn + pParse->ckBase;
70047      }else{
70048        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
70049                                 pExpr->iColumn, pExpr->iTable, target);
70050      }
70051      break;
70052    }
70053    case TK_INTEGER: {
70054      codeInteger(pParse, pExpr, 0, target);
70055      break;
70056    }
70057#ifndef SQLITE_OMIT_FLOATING_POINT
70058    case TK_FLOAT: {
70059      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70060      codeReal(v, pExpr->u.zToken, 0, target);
70061      break;
70062    }
70063#endif
70064    case TK_STRING: {
70065      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70066      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
70067      break;
70068    }
70069    case TK_NULL: {
70070      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
70071      break;
70072    }
70073#ifndef SQLITE_OMIT_BLOB_LITERAL
70074    case TK_BLOB: {
70075      int n;
70076      const char *z;
70077      char *zBlob;
70078      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70079      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70080      assert( pExpr->u.zToken[1]=='\'' );
70081      z = &pExpr->u.zToken[2];
70082      n = sqlite3Strlen30(z) - 1;
70083      assert( z[n]=='\'' );
70084      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
70085      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
70086      break;
70087    }
70088#endif
70089    case TK_VARIABLE: {
70090      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70091      assert( pExpr->u.zToken!=0 );
70092      assert( pExpr->u.zToken[0]!=0 );
70093      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
70094      if( pExpr->u.zToken[1]!=0 ){
70095        sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
70096      }
70097      break;
70098    }
70099    case TK_REGISTER: {
70100      inReg = pExpr->iTable;
70101      break;
70102    }
70103    case TK_AS: {
70104      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
70105      break;
70106    }
70107#ifndef SQLITE_OMIT_CAST
70108    case TK_CAST: {
70109      /* Expressions of the form:   CAST(pLeft AS token) */
70110      int aff, to_op;
70111      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
70112      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70113      aff = sqlite3AffinityType(pExpr->u.zToken);
70114      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
70115      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
70116      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
70117      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
70118      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
70119      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
70120      testcase( to_op==OP_ToText );
70121      testcase( to_op==OP_ToBlob );
70122      testcase( to_op==OP_ToNumeric );
70123      testcase( to_op==OP_ToInt );
70124      testcase( to_op==OP_ToReal );
70125      if( inReg!=target ){
70126        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
70127        inReg = target;
70128      }
70129      sqlite3VdbeAddOp1(v, to_op, inReg);
70130      testcase( usedAsColumnCache(pParse, inReg, inReg) );
70131      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
70132      break;
70133    }
70134#endif /* SQLITE_OMIT_CAST */
70135    case TK_LT:
70136    case TK_LE:
70137    case TK_GT:
70138    case TK_GE:
70139    case TK_NE:
70140    case TK_EQ: {
70141      assert( TK_LT==OP_Lt );
70142      assert( TK_LE==OP_Le );
70143      assert( TK_GT==OP_Gt );
70144      assert( TK_GE==OP_Ge );
70145      assert( TK_EQ==OP_Eq );
70146      assert( TK_NE==OP_Ne );
70147      testcase( op==TK_LT );
70148      testcase( op==TK_LE );
70149      testcase( op==TK_GT );
70150      testcase( op==TK_GE );
70151      testcase( op==TK_EQ );
70152      testcase( op==TK_NE );
70153      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70154      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70155      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70156                  r1, r2, inReg, SQLITE_STOREP2);
70157      testcase( regFree1==0 );
70158      testcase( regFree2==0 );
70159      break;
70160    }
70161    case TK_IS:
70162    case TK_ISNOT: {
70163      testcase( op==TK_IS );
70164      testcase( op==TK_ISNOT );
70165      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70166      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70167      op = (op==TK_IS) ? TK_EQ : TK_NE;
70168      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70169                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
70170      testcase( regFree1==0 );
70171      testcase( regFree2==0 );
70172      break;
70173    }
70174    case TK_AND:
70175    case TK_OR:
70176    case TK_PLUS:
70177    case TK_STAR:
70178    case TK_MINUS:
70179    case TK_REM:
70180    case TK_BITAND:
70181    case TK_BITOR:
70182    case TK_SLASH:
70183    case TK_LSHIFT:
70184    case TK_RSHIFT:
70185    case TK_CONCAT: {
70186      assert( TK_AND==OP_And );
70187      assert( TK_OR==OP_Or );
70188      assert( TK_PLUS==OP_Add );
70189      assert( TK_MINUS==OP_Subtract );
70190      assert( TK_REM==OP_Remainder );
70191      assert( TK_BITAND==OP_BitAnd );
70192      assert( TK_BITOR==OP_BitOr );
70193      assert( TK_SLASH==OP_Divide );
70194      assert( TK_LSHIFT==OP_ShiftLeft );
70195      assert( TK_RSHIFT==OP_ShiftRight );
70196      assert( TK_CONCAT==OP_Concat );
70197      testcase( op==TK_AND );
70198      testcase( op==TK_OR );
70199      testcase( op==TK_PLUS );
70200      testcase( op==TK_MINUS );
70201      testcase( op==TK_REM );
70202      testcase( op==TK_BITAND );
70203      testcase( op==TK_BITOR );
70204      testcase( op==TK_SLASH );
70205      testcase( op==TK_LSHIFT );
70206      testcase( op==TK_RSHIFT );
70207      testcase( op==TK_CONCAT );
70208      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70209      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70210      sqlite3VdbeAddOp3(v, op, r2, r1, target);
70211      testcase( regFree1==0 );
70212      testcase( regFree2==0 );
70213      break;
70214    }
70215    case TK_UMINUS: {
70216      Expr *pLeft = pExpr->pLeft;
70217      assert( pLeft );
70218      if( pLeft->op==TK_INTEGER ){
70219        codeInteger(pParse, pLeft, 1, target);
70220#ifndef SQLITE_OMIT_FLOATING_POINT
70221      }else if( pLeft->op==TK_FLOAT ){
70222        assert( !ExprHasProperty(pExpr, EP_IntValue) );
70223        codeReal(v, pLeft->u.zToken, 1, target);
70224#endif
70225      }else{
70226        regFree1 = r1 = sqlite3GetTempReg(pParse);
70227        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
70228        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
70229        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
70230        testcase( regFree2==0 );
70231      }
70232      inReg = target;
70233      break;
70234    }
70235    case TK_BITNOT:
70236    case TK_NOT: {
70237      assert( TK_BITNOT==OP_BitNot );
70238      assert( TK_NOT==OP_Not );
70239      testcase( op==TK_BITNOT );
70240      testcase( op==TK_NOT );
70241      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70242      testcase( regFree1==0 );
70243      inReg = target;
70244      sqlite3VdbeAddOp2(v, op, r1, inReg);
70245      break;
70246    }
70247    case TK_ISNULL:
70248    case TK_NOTNULL: {
70249      int addr;
70250      assert( TK_ISNULL==OP_IsNull );
70251      assert( TK_NOTNULL==OP_NotNull );
70252      testcase( op==TK_ISNULL );
70253      testcase( op==TK_NOTNULL );
70254      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
70255      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70256      testcase( regFree1==0 );
70257      addr = sqlite3VdbeAddOp1(v, op, r1);
70258      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
70259      sqlite3VdbeJumpHere(v, addr);
70260      break;
70261    }
70262    case TK_AGG_FUNCTION: {
70263      AggInfo *pInfo = pExpr->pAggInfo;
70264      if( pInfo==0 ){
70265        assert( !ExprHasProperty(pExpr, EP_IntValue) );
70266        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
70267      }else{
70268        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
70269      }
70270      break;
70271    }
70272    case TK_CONST_FUNC:
70273    case TK_FUNCTION: {
70274      ExprList *pFarg;       /* List of function arguments */
70275      int nFarg;             /* Number of function arguments */
70276      FuncDef *pDef;         /* The function definition object */
70277      int nId;               /* Length of the function name in bytes */
70278      const char *zId;       /* The function name */
70279      int constMask = 0;     /* Mask of function arguments that are constant */
70280      int i;                 /* Loop counter */
70281      u8 enc = ENC(db);      /* The text encoding used by this database */
70282      CollSeq *pColl = 0;    /* A collating sequence */
70283
70284      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70285      testcase( op==TK_CONST_FUNC );
70286      testcase( op==TK_FUNCTION );
70287      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
70288        pFarg = 0;
70289      }else{
70290        pFarg = pExpr->x.pList;
70291      }
70292      nFarg = pFarg ? pFarg->nExpr : 0;
70293      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70294      zId = pExpr->u.zToken;
70295      nId = sqlite3Strlen30(zId);
70296      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
70297      if( pDef==0 ){
70298        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
70299        break;
70300      }
70301
70302      /* Attempt a direct implementation of the built-in COALESCE() and
70303      ** IFNULL() functions.  This avoids unnecessary evalation of
70304      ** arguments past the first non-NULL argument.
70305      */
70306      if( pDef->flags & SQLITE_FUNC_COALESCE ){
70307        int endCoalesce = sqlite3VdbeMakeLabel(v);
70308        assert( nFarg>=2 );
70309        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
70310        for(i=1; i<nFarg; i++){
70311          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
70312          sqlite3ExprCacheRemove(pParse, target, 1);
70313          sqlite3ExprCachePush(pParse);
70314          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
70315          sqlite3ExprCachePop(pParse, 1);
70316        }
70317        sqlite3VdbeResolveLabel(v, endCoalesce);
70318        break;
70319      }
70320
70321
70322      if( pFarg ){
70323        r1 = sqlite3GetTempRange(pParse, nFarg);
70324        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
70325        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
70326        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
70327      }else{
70328        r1 = 0;
70329      }
70330#ifndef SQLITE_OMIT_VIRTUALTABLE
70331      /* Possibly overload the function if the first argument is
70332      ** a virtual table column.
70333      **
70334      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
70335      ** second argument, not the first, as the argument to test to
70336      ** see if it is a column in a virtual table.  This is done because
70337      ** the left operand of infix functions (the operand we want to
70338      ** control overloading) ends up as the second argument to the
70339      ** function.  The expression "A glob B" is equivalent to
70340      ** "glob(B,A).  We want to use the A in "A glob B" to test
70341      ** for function overloading.  But we use the B term in "glob(B,A)".
70342      */
70343      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
70344        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
70345      }else if( nFarg>0 ){
70346        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
70347      }
70348#endif
70349      for(i=0; i<nFarg; i++){
70350        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
70351          constMask |= (1<<i);
70352        }
70353        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
70354          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
70355        }
70356      }
70357      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
70358        if( !pColl ) pColl = db->pDfltColl;
70359        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
70360      }
70361      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
70362                        (char*)pDef, P4_FUNCDEF);
70363      sqlite3VdbeChangeP5(v, (u8)nFarg);
70364      if( nFarg ){
70365        sqlite3ReleaseTempRange(pParse, r1, nFarg);
70366      }
70367      break;
70368    }
70369#ifndef SQLITE_OMIT_SUBQUERY
70370    case TK_EXISTS:
70371    case TK_SELECT: {
70372      testcase( op==TK_EXISTS );
70373      testcase( op==TK_SELECT );
70374      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
70375      break;
70376    }
70377    case TK_IN: {
70378      int destIfFalse = sqlite3VdbeMakeLabel(v);
70379      int destIfNull = sqlite3VdbeMakeLabel(v);
70380      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
70381      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
70382      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
70383      sqlite3VdbeResolveLabel(v, destIfFalse);
70384      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
70385      sqlite3VdbeResolveLabel(v, destIfNull);
70386      break;
70387    }
70388#endif /* SQLITE_OMIT_SUBQUERY */
70389
70390
70391    /*
70392    **    x BETWEEN y AND z
70393    **
70394    ** This is equivalent to
70395    **
70396    **    x>=y AND x<=z
70397    **
70398    ** X is stored in pExpr->pLeft.
70399    ** Y is stored in pExpr->pList->a[0].pExpr.
70400    ** Z is stored in pExpr->pList->a[1].pExpr.
70401    */
70402    case TK_BETWEEN: {
70403      Expr *pLeft = pExpr->pLeft;
70404      struct ExprList_item *pLItem = pExpr->x.pList->a;
70405      Expr *pRight = pLItem->pExpr;
70406
70407      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
70408      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
70409      testcase( regFree1==0 );
70410      testcase( regFree2==0 );
70411      r3 = sqlite3GetTempReg(pParse);
70412      r4 = sqlite3GetTempReg(pParse);
70413      codeCompare(pParse, pLeft, pRight, OP_Ge,
70414                  r1, r2, r3, SQLITE_STOREP2);
70415      pLItem++;
70416      pRight = pLItem->pExpr;
70417      sqlite3ReleaseTempReg(pParse, regFree2);
70418      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
70419      testcase( regFree2==0 );
70420      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
70421      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
70422      sqlite3ReleaseTempReg(pParse, r3);
70423      sqlite3ReleaseTempReg(pParse, r4);
70424      break;
70425    }
70426    case TK_UPLUS: {
70427      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
70428      break;
70429    }
70430
70431    case TK_TRIGGER: {
70432      /* If the opcode is TK_TRIGGER, then the expression is a reference
70433      ** to a column in the new.* or old.* pseudo-tables available to
70434      ** trigger programs. In this case Expr.iTable is set to 1 for the
70435      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
70436      ** is set to the column of the pseudo-table to read, or to -1 to
70437      ** read the rowid field.
70438      **
70439      ** The expression is implemented using an OP_Param opcode. The p1
70440      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
70441      ** to reference another column of the old.* pseudo-table, where
70442      ** i is the index of the column. For a new.rowid reference, p1 is
70443      ** set to (n+1), where n is the number of columns in each pseudo-table.
70444      ** For a reference to any other column in the new.* pseudo-table, p1
70445      ** is set to (n+2+i), where n and i are as defined previously. For
70446      ** example, if the table on which triggers are being fired is
70447      ** declared as:
70448      **
70449      **   CREATE TABLE t1(a, b);
70450      **
70451      ** Then p1 is interpreted as follows:
70452      **
70453      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
70454      **   p1==1   ->    old.a         p1==4   ->    new.a
70455      **   p1==2   ->    old.b         p1==5   ->    new.b
70456      */
70457      Table *pTab = pExpr->pTab;
70458      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
70459
70460      assert( pExpr->iTable==0 || pExpr->iTable==1 );
70461      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
70462      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
70463      assert( p1>=0 && p1<(pTab->nCol*2+2) );
70464
70465      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
70466      VdbeComment((v, "%s.%s -> $%d",
70467        (pExpr->iTable ? "new" : "old"),
70468        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
70469        target
70470      ));
70471
70472#ifndef SQLITE_OMIT_FLOATING_POINT
70473      /* If the column has REAL affinity, it may currently be stored as an
70474      ** integer. Use OP_RealAffinity to make sure it is really real.  */
70475      if( pExpr->iColumn>=0
70476       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
70477      ){
70478        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
70479      }
70480#endif
70481      break;
70482    }
70483
70484
70485    /*
70486    ** Form A:
70487    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
70488    **
70489    ** Form B:
70490    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
70491    **
70492    ** Form A is can be transformed into the equivalent form B as follows:
70493    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
70494    **        WHEN x=eN THEN rN ELSE y END
70495    **
70496    ** X (if it exists) is in pExpr->pLeft.
70497    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
70498    ** ELSE clause and no other term matches, then the result of the
70499    ** exprssion is NULL.
70500    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
70501    **
70502    ** The result of the expression is the Ri for the first matching Ei,
70503    ** or if there is no matching Ei, the ELSE term Y, or if there is
70504    ** no ELSE term, NULL.
70505    */
70506    default: assert( op==TK_CASE ); {
70507      int endLabel;                     /* GOTO label for end of CASE stmt */
70508      int nextCase;                     /* GOTO label for next WHEN clause */
70509      int nExpr;                        /* 2x number of WHEN terms */
70510      int i;                            /* Loop counter */
70511      ExprList *pEList;                 /* List of WHEN terms */
70512      struct ExprList_item *aListelem;  /* Array of WHEN terms */
70513      Expr opCompare;                   /* The X==Ei expression */
70514      Expr cacheX;                      /* Cached expression X */
70515      Expr *pX;                         /* The X expression */
70516      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
70517      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
70518
70519      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
70520      assert((pExpr->x.pList->nExpr % 2) == 0);
70521      assert(pExpr->x.pList->nExpr > 0);
70522      pEList = pExpr->x.pList;
70523      aListelem = pEList->a;
70524      nExpr = pEList->nExpr;
70525      endLabel = sqlite3VdbeMakeLabel(v);
70526      if( (pX = pExpr->pLeft)!=0 ){
70527        cacheX = *pX;
70528        testcase( pX->op==TK_COLUMN );
70529        testcase( pX->op==TK_REGISTER );
70530        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
70531        testcase( regFree1==0 );
70532        cacheX.op = TK_REGISTER;
70533        opCompare.op = TK_EQ;
70534        opCompare.pLeft = &cacheX;
70535        pTest = &opCompare;
70536      }
70537      for(i=0; i<nExpr; i=i+2){
70538        sqlite3ExprCachePush(pParse);
70539        if( pX ){
70540          assert( pTest!=0 );
70541          opCompare.pRight = aListelem[i].pExpr;
70542        }else{
70543          pTest = aListelem[i].pExpr;
70544        }
70545        nextCase = sqlite3VdbeMakeLabel(v);
70546        testcase( pTest->op==TK_COLUMN );
70547        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
70548        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
70549        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
70550        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
70551        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
70552        sqlite3ExprCachePop(pParse, 1);
70553        sqlite3VdbeResolveLabel(v, nextCase);
70554      }
70555      if( pExpr->pRight ){
70556        sqlite3ExprCachePush(pParse);
70557        sqlite3ExprCode(pParse, pExpr->pRight, target);
70558        sqlite3ExprCachePop(pParse, 1);
70559      }else{
70560        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
70561      }
70562      assert( db->mallocFailed || pParse->nErr>0
70563           || pParse->iCacheLevel==iCacheLevel );
70564      sqlite3VdbeResolveLabel(v, endLabel);
70565      break;
70566    }
70567#ifndef SQLITE_OMIT_TRIGGER
70568    case TK_RAISE: {
70569      assert( pExpr->affinity==OE_Rollback
70570           || pExpr->affinity==OE_Abort
70571           || pExpr->affinity==OE_Fail
70572           || pExpr->affinity==OE_Ignore
70573      );
70574      if( !pParse->pTriggerTab ){
70575        sqlite3ErrorMsg(pParse,
70576                       "RAISE() may only be used within a trigger-program");
70577        return 0;
70578      }
70579      if( pExpr->affinity==OE_Abort ){
70580        sqlite3MayAbort(pParse);
70581      }
70582      assert( !ExprHasProperty(pExpr, EP_IntValue) );
70583      if( pExpr->affinity==OE_Ignore ){
70584        sqlite3VdbeAddOp4(
70585            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
70586      }else{
70587        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
70588      }
70589
70590      break;
70591    }
70592#endif
70593  }
70594  sqlite3ReleaseTempReg(pParse, regFree1);
70595  sqlite3ReleaseTempReg(pParse, regFree2);
70596  return inReg;
70597}
70598
70599/*
70600** Generate code to evaluate an expression and store the results
70601** into a register.  Return the register number where the results
70602** are stored.
70603**
70604** If the register is a temporary register that can be deallocated,
70605** then write its number into *pReg.  If the result register is not
70606** a temporary, then set *pReg to zero.
70607*/
70608SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
70609  int r1 = sqlite3GetTempReg(pParse);
70610  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
70611  if( r2==r1 ){
70612    *pReg = r1;
70613  }else{
70614    sqlite3ReleaseTempReg(pParse, r1);
70615    *pReg = 0;
70616  }
70617  return r2;
70618}
70619
70620/*
70621** Generate code that will evaluate expression pExpr and store the
70622** results in register target.  The results are guaranteed to appear
70623** in register target.
70624*/
70625SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
70626  int inReg;
70627
70628  assert( target>0 && target<=pParse->nMem );
70629  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
70630  assert( pParse->pVdbe || pParse->db->mallocFailed );
70631  if( inReg!=target && pParse->pVdbe ){
70632    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
70633  }
70634  return target;
70635}
70636
70637/*
70638** Generate code that evalutes the given expression and puts the result
70639** in register target.
70640**
70641** Also make a copy of the expression results into another "cache" register
70642** and modify the expression so that the next time it is evaluated,
70643** the result is a copy of the cache register.
70644**
70645** This routine is used for expressions that are used multiple
70646** times.  They are evaluated once and the results of the expression
70647** are reused.
70648*/
70649SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
70650  Vdbe *v = pParse->pVdbe;
70651  int inReg;
70652  inReg = sqlite3ExprCode(pParse, pExpr, target);
70653  assert( target>0 );
70654  /* This routine is called for terms to INSERT or UPDATE.  And the only
70655  ** other place where expressions can be converted into TK_REGISTER is
70656  ** in WHERE clause processing.  So as currently implemented, there is
70657  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
70658  ** keep the ALWAYS() in case the conditions above change with future
70659  ** modifications or enhancements. */
70660  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
70661    int iMem;
70662    iMem = ++pParse->nMem;
70663    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
70664    pExpr->iTable = iMem;
70665    pExpr->op2 = pExpr->op;
70666    pExpr->op = TK_REGISTER;
70667  }
70668  return inReg;
70669}
70670
70671/*
70672** Return TRUE if pExpr is an constant expression that is appropriate
70673** for factoring out of a loop.  Appropriate expressions are:
70674**
70675**    *  Any expression that evaluates to two or more opcodes.
70676**
70677**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
70678**       or OP_Variable that does not need to be placed in a
70679**       specific register.
70680**
70681** There is no point in factoring out single-instruction constant
70682** expressions that need to be placed in a particular register.
70683** We could factor them out, but then we would end up adding an
70684** OP_SCopy instruction to move the value into the correct register
70685** later.  We might as well just use the original instruction and
70686** avoid the OP_SCopy.
70687*/
70688static int isAppropriateForFactoring(Expr *p){
70689  if( !sqlite3ExprIsConstantNotJoin(p) ){
70690    return 0;  /* Only constant expressions are appropriate for factoring */
70691  }
70692  if( (p->flags & EP_FixedDest)==0 ){
70693    return 1;  /* Any constant without a fixed destination is appropriate */
70694  }
70695  while( p->op==TK_UPLUS ) p = p->pLeft;
70696  switch( p->op ){
70697#ifndef SQLITE_OMIT_BLOB_LITERAL
70698    case TK_BLOB:
70699#endif
70700    case TK_VARIABLE:
70701    case TK_INTEGER:
70702    case TK_FLOAT:
70703    case TK_NULL:
70704    case TK_STRING: {
70705      testcase( p->op==TK_BLOB );
70706      testcase( p->op==TK_VARIABLE );
70707      testcase( p->op==TK_INTEGER );
70708      testcase( p->op==TK_FLOAT );
70709      testcase( p->op==TK_NULL );
70710      testcase( p->op==TK_STRING );
70711      /* Single-instruction constants with a fixed destination are
70712      ** better done in-line.  If we factor them, they will just end
70713      ** up generating an OP_SCopy to move the value to the destination
70714      ** register. */
70715      return 0;
70716    }
70717    case TK_UMINUS: {
70718      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
70719        return 0;
70720      }
70721      break;
70722    }
70723    default: {
70724      break;
70725    }
70726  }
70727  return 1;
70728}
70729
70730/*
70731** If pExpr is a constant expression that is appropriate for
70732** factoring out of a loop, then evaluate the expression
70733** into a register and convert the expression into a TK_REGISTER
70734** expression.
70735*/
70736static int evalConstExpr(Walker *pWalker, Expr *pExpr){
70737  Parse *pParse = pWalker->pParse;
70738  switch( pExpr->op ){
70739    case TK_IN:
70740    case TK_REGISTER: {
70741      return WRC_Prune;
70742    }
70743    case TK_FUNCTION:
70744    case TK_AGG_FUNCTION:
70745    case TK_CONST_FUNC: {
70746      /* The arguments to a function have a fixed destination.
70747      ** Mark them this way to avoid generated unneeded OP_SCopy
70748      ** instructions.
70749      */
70750      ExprList *pList = pExpr->x.pList;
70751      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70752      if( pList ){
70753        int i = pList->nExpr;
70754        struct ExprList_item *pItem = pList->a;
70755        for(; i>0; i--, pItem++){
70756          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
70757        }
70758      }
70759      break;
70760    }
70761  }
70762  if( isAppropriateForFactoring(pExpr) ){
70763    int r1 = ++pParse->nMem;
70764    int r2;
70765    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
70766    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
70767    pExpr->op2 = pExpr->op;
70768    pExpr->op = TK_REGISTER;
70769    pExpr->iTable = r2;
70770    return WRC_Prune;
70771  }
70772  return WRC_Continue;
70773}
70774
70775/*
70776** Preevaluate constant subexpressions within pExpr and store the
70777** results in registers.  Modify pExpr so that the constant subexpresions
70778** are TK_REGISTER opcodes that refer to the precomputed values.
70779*/
70780SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
70781  Walker w;
70782  w.xExprCallback = evalConstExpr;
70783  w.xSelectCallback = 0;
70784  w.pParse = pParse;
70785  sqlite3WalkExpr(&w, pExpr);
70786}
70787
70788
70789/*
70790** Generate code that pushes the value of every element of the given
70791** expression list into a sequence of registers beginning at target.
70792**
70793** Return the number of elements evaluated.
70794*/
70795SQLITE_PRIVATE int sqlite3ExprCodeExprList(
70796  Parse *pParse,     /* Parsing context */
70797  ExprList *pList,   /* The expression list to be coded */
70798  int target,        /* Where to write results */
70799  int doHardCopy     /* Make a hard copy of every element */
70800){
70801  struct ExprList_item *pItem;
70802  int i, n;
70803  assert( pList!=0 );
70804  assert( target>0 );
70805  n = pList->nExpr;
70806  for(pItem=pList->a, i=0; i<n; i++, pItem++){
70807    if( pItem->iAlias ){
70808      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
70809      Vdbe *v = sqlite3GetVdbe(pParse);
70810      if( iReg!=target+i ){
70811        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
70812      }
70813    }else{
70814      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
70815    }
70816    if( doHardCopy && !pParse->db->mallocFailed ){
70817      sqlite3ExprHardCopy(pParse, target, n);
70818    }
70819  }
70820  return n;
70821}
70822
70823/*
70824** Generate code for a BETWEEN operator.
70825**
70826**    x BETWEEN y AND z
70827**
70828** The above is equivalent to
70829**
70830**    x>=y AND x<=z
70831**
70832** Code it as such, taking care to do the common subexpression
70833** elementation of x.
70834*/
70835static void exprCodeBetween(
70836  Parse *pParse,    /* Parsing and code generating context */
70837  Expr *pExpr,      /* The BETWEEN expression */
70838  int dest,         /* Jump here if the jump is taken */
70839  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
70840  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
70841){
70842  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
70843  Expr compLeft;    /* The  x>=y  term */
70844  Expr compRight;   /* The  x<=z  term */
70845  Expr exprX;       /* The  x  subexpression */
70846  int regFree1 = 0; /* Temporary use register */
70847
70848  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70849  exprX = *pExpr->pLeft;
70850  exprAnd.op = TK_AND;
70851  exprAnd.pLeft = &compLeft;
70852  exprAnd.pRight = &compRight;
70853  compLeft.op = TK_GE;
70854  compLeft.pLeft = &exprX;
70855  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
70856  compRight.op = TK_LE;
70857  compRight.pLeft = &exprX;
70858  compRight.pRight = pExpr->x.pList->a[1].pExpr;
70859  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
70860  exprX.op = TK_REGISTER;
70861  if( jumpIfTrue ){
70862    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
70863  }else{
70864    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
70865  }
70866  sqlite3ReleaseTempReg(pParse, regFree1);
70867
70868  /* Ensure adequate test coverage */
70869  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
70870  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
70871  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
70872  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
70873  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
70874  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
70875  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
70876  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
70877}
70878
70879/*
70880** Generate code for a boolean expression such that a jump is made
70881** to the label "dest" if the expression is true but execution
70882** continues straight thru if the expression is false.
70883**
70884** If the expression evaluates to NULL (neither true nor false), then
70885** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
70886**
70887** This code depends on the fact that certain token values (ex: TK_EQ)
70888** are the same as opcode values (ex: OP_Eq) that implement the corresponding
70889** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
70890** the make process cause these values to align.  Assert()s in the code
70891** below verify that the numbers are aligned correctly.
70892*/
70893SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
70894  Vdbe *v = pParse->pVdbe;
70895  int op = 0;
70896  int regFree1 = 0;
70897  int regFree2 = 0;
70898  int r1, r2;
70899
70900  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
70901  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
70902  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
70903  op = pExpr->op;
70904  switch( op ){
70905    case TK_AND: {
70906      int d2 = sqlite3VdbeMakeLabel(v);
70907      testcase( jumpIfNull==0 );
70908      sqlite3ExprCachePush(pParse);
70909      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
70910      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
70911      sqlite3VdbeResolveLabel(v, d2);
70912      sqlite3ExprCachePop(pParse, 1);
70913      break;
70914    }
70915    case TK_OR: {
70916      testcase( jumpIfNull==0 );
70917      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
70918      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
70919      break;
70920    }
70921    case TK_NOT: {
70922      testcase( jumpIfNull==0 );
70923      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
70924      break;
70925    }
70926    case TK_LT:
70927    case TK_LE:
70928    case TK_GT:
70929    case TK_GE:
70930    case TK_NE:
70931    case TK_EQ: {
70932      assert( TK_LT==OP_Lt );
70933      assert( TK_LE==OP_Le );
70934      assert( TK_GT==OP_Gt );
70935      assert( TK_GE==OP_Ge );
70936      assert( TK_EQ==OP_Eq );
70937      assert( TK_NE==OP_Ne );
70938      testcase( op==TK_LT );
70939      testcase( op==TK_LE );
70940      testcase( op==TK_GT );
70941      testcase( op==TK_GE );
70942      testcase( op==TK_EQ );
70943      testcase( op==TK_NE );
70944      testcase( jumpIfNull==0 );
70945      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70946      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70947      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70948                  r1, r2, dest, jumpIfNull);
70949      testcase( regFree1==0 );
70950      testcase( regFree2==0 );
70951      break;
70952    }
70953    case TK_IS:
70954    case TK_ISNOT: {
70955      testcase( op==TK_IS );
70956      testcase( op==TK_ISNOT );
70957      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70958      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
70959      op = (op==TK_IS) ? TK_EQ : TK_NE;
70960      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
70961                  r1, r2, dest, SQLITE_NULLEQ);
70962      testcase( regFree1==0 );
70963      testcase( regFree2==0 );
70964      break;
70965    }
70966    case TK_ISNULL:
70967    case TK_NOTNULL: {
70968      assert( TK_ISNULL==OP_IsNull );
70969      assert( TK_NOTNULL==OP_NotNull );
70970      testcase( op==TK_ISNULL );
70971      testcase( op==TK_NOTNULL );
70972      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
70973      sqlite3VdbeAddOp2(v, op, r1, dest);
70974      testcase( regFree1==0 );
70975      break;
70976    }
70977    case TK_BETWEEN: {
70978      testcase( jumpIfNull==0 );
70979      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
70980      break;
70981    }
70982    case TK_IN: {
70983      int destIfFalse = sqlite3VdbeMakeLabel(v);
70984      int destIfNull = jumpIfNull ? dest : destIfFalse;
70985      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
70986      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
70987      sqlite3VdbeResolveLabel(v, destIfFalse);
70988      break;
70989    }
70990    default: {
70991      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
70992      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
70993      testcase( regFree1==0 );
70994      testcase( jumpIfNull==0 );
70995      break;
70996    }
70997  }
70998  sqlite3ReleaseTempReg(pParse, regFree1);
70999  sqlite3ReleaseTempReg(pParse, regFree2);
71000}
71001
71002/*
71003** Generate code for a boolean expression such that a jump is made
71004** to the label "dest" if the expression is false but execution
71005** continues straight thru if the expression is true.
71006**
71007** If the expression evaluates to NULL (neither true nor false) then
71008** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
71009** is 0.
71010*/
71011SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
71012  Vdbe *v = pParse->pVdbe;
71013  int op = 0;
71014  int regFree1 = 0;
71015  int regFree2 = 0;
71016  int r1, r2;
71017
71018  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
71019  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
71020  if( pExpr==0 )    return;
71021
71022  /* The value of pExpr->op and op are related as follows:
71023  **
71024  **       pExpr->op            op
71025  **       ---------          ----------
71026  **       TK_ISNULL          OP_NotNull
71027  **       TK_NOTNULL         OP_IsNull
71028  **       TK_NE              OP_Eq
71029  **       TK_EQ              OP_Ne
71030  **       TK_GT              OP_Le
71031  **       TK_LE              OP_Gt
71032  **       TK_GE              OP_Lt
71033  **       TK_LT              OP_Ge
71034  **
71035  ** For other values of pExpr->op, op is undefined and unused.
71036  ** The value of TK_ and OP_ constants are arranged such that we
71037  ** can compute the mapping above using the following expression.
71038  ** Assert()s verify that the computation is correct.
71039  */
71040  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
71041
71042  /* Verify correct alignment of TK_ and OP_ constants
71043  */
71044  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
71045  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
71046  assert( pExpr->op!=TK_NE || op==OP_Eq );
71047  assert( pExpr->op!=TK_EQ || op==OP_Ne );
71048  assert( pExpr->op!=TK_LT || op==OP_Ge );
71049  assert( pExpr->op!=TK_LE || op==OP_Gt );
71050  assert( pExpr->op!=TK_GT || op==OP_Le );
71051  assert( pExpr->op!=TK_GE || op==OP_Lt );
71052
71053  switch( pExpr->op ){
71054    case TK_AND: {
71055      testcase( jumpIfNull==0 );
71056      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
71057      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
71058      break;
71059    }
71060    case TK_OR: {
71061      int d2 = sqlite3VdbeMakeLabel(v);
71062      testcase( jumpIfNull==0 );
71063      sqlite3ExprCachePush(pParse);
71064      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
71065      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
71066      sqlite3VdbeResolveLabel(v, d2);
71067      sqlite3ExprCachePop(pParse, 1);
71068      break;
71069    }
71070    case TK_NOT: {
71071      testcase( jumpIfNull==0 );
71072      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
71073      break;
71074    }
71075    case TK_LT:
71076    case TK_LE:
71077    case TK_GT:
71078    case TK_GE:
71079    case TK_NE:
71080    case TK_EQ: {
71081      testcase( op==TK_LT );
71082      testcase( op==TK_LE );
71083      testcase( op==TK_GT );
71084      testcase( op==TK_GE );
71085      testcase( op==TK_EQ );
71086      testcase( op==TK_NE );
71087      testcase( jumpIfNull==0 );
71088      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71089      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71090      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71091                  r1, r2, dest, jumpIfNull);
71092      testcase( regFree1==0 );
71093      testcase( regFree2==0 );
71094      break;
71095    }
71096    case TK_IS:
71097    case TK_ISNOT: {
71098      testcase( pExpr->op==TK_IS );
71099      testcase( pExpr->op==TK_ISNOT );
71100      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71101      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71102      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
71103      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71104                  r1, r2, dest, SQLITE_NULLEQ);
71105      testcase( regFree1==0 );
71106      testcase( regFree2==0 );
71107      break;
71108    }
71109    case TK_ISNULL:
71110    case TK_NOTNULL: {
71111      testcase( op==TK_ISNULL );
71112      testcase( op==TK_NOTNULL );
71113      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71114      sqlite3VdbeAddOp2(v, op, r1, dest);
71115      testcase( regFree1==0 );
71116      break;
71117    }
71118    case TK_BETWEEN: {
71119      testcase( jumpIfNull==0 );
71120      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
71121      break;
71122    }
71123    case TK_IN: {
71124      if( jumpIfNull ){
71125        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
71126      }else{
71127        int destIfNull = sqlite3VdbeMakeLabel(v);
71128        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
71129        sqlite3VdbeResolveLabel(v, destIfNull);
71130      }
71131      break;
71132    }
71133    default: {
71134      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
71135      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
71136      testcase( regFree1==0 );
71137      testcase( jumpIfNull==0 );
71138      break;
71139    }
71140  }
71141  sqlite3ReleaseTempReg(pParse, regFree1);
71142  sqlite3ReleaseTempReg(pParse, regFree2);
71143}
71144
71145/*
71146** Do a deep comparison of two expression trees.  Return 0 if the two
71147** expressions are completely identical.  Return 1 if they differ only
71148** by a COLLATE operator at the top level.  Return 2 if there are differences
71149** other than the top-level COLLATE operator.
71150**
71151** Sometimes this routine will return 2 even if the two expressions
71152** really are equivalent.  If we cannot prove that the expressions are
71153** identical, we return 2 just to be safe.  So if this routine
71154** returns 2, then you do not really know for certain if the two
71155** expressions are the same.  But if you get a 0 or 1 return, then you
71156** can be sure the expressions are the same.  In the places where
71157** this routine is used, it does not hurt to get an extra 2 - that
71158** just might result in some slightly slower code.  But returning
71159** an incorrect 0 or 1 could lead to a malfunction.
71160*/
71161SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
71162  if( pA==0||pB==0 ){
71163    return pB==pA ? 0 : 2;
71164  }
71165  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
71166  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
71167  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
71168    return 2;
71169  }
71170  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
71171  if( pA->op!=pB->op ) return 2;
71172  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
71173  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
71174  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
71175  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
71176  if( ExprHasProperty(pA, EP_IntValue) ){
71177    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
71178      return 2;
71179    }
71180  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
71181    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
71182    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
71183      return 2;
71184    }
71185  }
71186  if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
71187  if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
71188  return 0;
71189}
71190
71191/*
71192** Compare two ExprList objects.  Return 0 if they are identical and
71193** non-zero if they differ in any way.
71194**
71195** This routine might return non-zero for equivalent ExprLists.  The
71196** only consequence will be disabled optimizations.  But this routine
71197** must never return 0 if the two ExprList objects are different, or
71198** a malfunction will result.
71199**
71200** Two NULL pointers are considered to be the same.  But a NULL pointer
71201** always differs from a non-NULL pointer.
71202*/
71203SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
71204  int i;
71205  if( pA==0 && pB==0 ) return 0;
71206  if( pA==0 || pB==0 ) return 1;
71207  if( pA->nExpr!=pB->nExpr ) return 1;
71208  for(i=0; i<pA->nExpr; i++){
71209    Expr *pExprA = pA->a[i].pExpr;
71210    Expr *pExprB = pB->a[i].pExpr;
71211    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
71212    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
71213  }
71214  return 0;
71215}
71216
71217/*
71218** Add a new element to the pAggInfo->aCol[] array.  Return the index of
71219** the new element.  Return a negative number if malloc fails.
71220*/
71221static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
71222  int i;
71223  pInfo->aCol = sqlite3ArrayAllocate(
71224       db,
71225       pInfo->aCol,
71226       sizeof(pInfo->aCol[0]),
71227       3,
71228       &pInfo->nColumn,
71229       &pInfo->nColumnAlloc,
71230       &i
71231  );
71232  return i;
71233}
71234
71235/*
71236** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
71237** the new element.  Return a negative number if malloc fails.
71238*/
71239static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
71240  int i;
71241  pInfo->aFunc = sqlite3ArrayAllocate(
71242       db,
71243       pInfo->aFunc,
71244       sizeof(pInfo->aFunc[0]),
71245       3,
71246       &pInfo->nFunc,
71247       &pInfo->nFuncAlloc,
71248       &i
71249  );
71250  return i;
71251}
71252
71253/*
71254** This is the xExprCallback for a tree walker.  It is used to
71255** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
71256** for additional information.
71257*/
71258static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
71259  int i;
71260  NameContext *pNC = pWalker->u.pNC;
71261  Parse *pParse = pNC->pParse;
71262  SrcList *pSrcList = pNC->pSrcList;
71263  AggInfo *pAggInfo = pNC->pAggInfo;
71264
71265  switch( pExpr->op ){
71266    case TK_AGG_COLUMN:
71267    case TK_COLUMN: {
71268      testcase( pExpr->op==TK_AGG_COLUMN );
71269      testcase( pExpr->op==TK_COLUMN );
71270      /* Check to see if the column is in one of the tables in the FROM
71271      ** clause of the aggregate query */
71272      if( ALWAYS(pSrcList!=0) ){
71273        struct SrcList_item *pItem = pSrcList->a;
71274        for(i=0; i<pSrcList->nSrc; i++, pItem++){
71275          struct AggInfo_col *pCol;
71276          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
71277          if( pExpr->iTable==pItem->iCursor ){
71278            /* If we reach this point, it means that pExpr refers to a table
71279            ** that is in the FROM clause of the aggregate query.
71280            **
71281            ** Make an entry for the column in pAggInfo->aCol[] if there
71282            ** is not an entry there already.
71283            */
71284            int k;
71285            pCol = pAggInfo->aCol;
71286            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
71287              if( pCol->iTable==pExpr->iTable &&
71288                  pCol->iColumn==pExpr->iColumn ){
71289                break;
71290              }
71291            }
71292            if( (k>=pAggInfo->nColumn)
71293             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
71294            ){
71295              pCol = &pAggInfo->aCol[k];
71296              pCol->pTab = pExpr->pTab;
71297              pCol->iTable = pExpr->iTable;
71298              pCol->iColumn = pExpr->iColumn;
71299              pCol->iMem = ++pParse->nMem;
71300              pCol->iSorterColumn = -1;
71301              pCol->pExpr = pExpr;
71302              if( pAggInfo->pGroupBy ){
71303                int j, n;
71304                ExprList *pGB = pAggInfo->pGroupBy;
71305                struct ExprList_item *pTerm = pGB->a;
71306                n = pGB->nExpr;
71307                for(j=0; j<n; j++, pTerm++){
71308                  Expr *pE = pTerm->pExpr;
71309                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
71310                      pE->iColumn==pExpr->iColumn ){
71311                    pCol->iSorterColumn = j;
71312                    break;
71313                  }
71314                }
71315              }
71316              if( pCol->iSorterColumn<0 ){
71317                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
71318              }
71319            }
71320            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
71321            ** because it was there before or because we just created it).
71322            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
71323            ** pAggInfo->aCol[] entry.
71324            */
71325            ExprSetIrreducible(pExpr);
71326            pExpr->pAggInfo = pAggInfo;
71327            pExpr->op = TK_AGG_COLUMN;
71328            pExpr->iAgg = (i16)k;
71329            break;
71330          } /* endif pExpr->iTable==pItem->iCursor */
71331        } /* end loop over pSrcList */
71332      }
71333      return WRC_Prune;
71334    }
71335    case TK_AGG_FUNCTION: {
71336      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
71337      ** to be ignored */
71338      if( pNC->nDepth==0 ){
71339        /* Check to see if pExpr is a duplicate of another aggregate
71340        ** function that is already in the pAggInfo structure
71341        */
71342        struct AggInfo_func *pItem = pAggInfo->aFunc;
71343        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
71344          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
71345            break;
71346          }
71347        }
71348        if( i>=pAggInfo->nFunc ){
71349          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
71350          */
71351          u8 enc = ENC(pParse->db);
71352          i = addAggInfoFunc(pParse->db, pAggInfo);
71353          if( i>=0 ){
71354            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71355            pItem = &pAggInfo->aFunc[i];
71356            pItem->pExpr = pExpr;
71357            pItem->iMem = ++pParse->nMem;
71358            assert( !ExprHasProperty(pExpr, EP_IntValue) );
71359            pItem->pFunc = sqlite3FindFunction(pParse->db,
71360                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
71361                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
71362            if( pExpr->flags & EP_Distinct ){
71363              pItem->iDistinct = pParse->nTab++;
71364            }else{
71365              pItem->iDistinct = -1;
71366            }
71367          }
71368        }
71369        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
71370        */
71371        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
71372        ExprSetIrreducible(pExpr);
71373        pExpr->iAgg = (i16)i;
71374        pExpr->pAggInfo = pAggInfo;
71375        return WRC_Prune;
71376      }
71377    }
71378  }
71379  return WRC_Continue;
71380}
71381static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
71382  NameContext *pNC = pWalker->u.pNC;
71383  if( pNC->nDepth==0 ){
71384    pNC->nDepth++;
71385    sqlite3WalkSelect(pWalker, pSelect);
71386    pNC->nDepth--;
71387    return WRC_Prune;
71388  }else{
71389    return WRC_Continue;
71390  }
71391}
71392
71393/*
71394** Analyze the given expression looking for aggregate functions and
71395** for variables that need to be added to the pParse->aAgg[] array.
71396** Make additional entries to the pParse->aAgg[] array as necessary.
71397**
71398** This routine should only be called after the expression has been
71399** analyzed by sqlite3ResolveExprNames().
71400*/
71401SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
71402  Walker w;
71403  w.xExprCallback = analyzeAggregate;
71404  w.xSelectCallback = analyzeAggregatesInSelect;
71405  w.u.pNC = pNC;
71406  assert( pNC->pSrcList!=0 );
71407  sqlite3WalkExpr(&w, pExpr);
71408}
71409
71410/*
71411** Call sqlite3ExprAnalyzeAggregates() for every expression in an
71412** expression list.  Return the number of errors.
71413**
71414** If an error is found, the analysis is cut short.
71415*/
71416SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
71417  struct ExprList_item *pItem;
71418  int i;
71419  if( pList ){
71420    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
71421      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
71422    }
71423  }
71424}
71425
71426/*
71427** Allocate a single new register for use to hold some intermediate result.
71428*/
71429SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
71430  if( pParse->nTempReg==0 ){
71431    return ++pParse->nMem;
71432  }
71433  return pParse->aTempReg[--pParse->nTempReg];
71434}
71435
71436/*
71437** Deallocate a register, making available for reuse for some other
71438** purpose.
71439**
71440** If a register is currently being used by the column cache, then
71441** the dallocation is deferred until the column cache line that uses
71442** the register becomes stale.
71443*/
71444SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
71445  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
71446    int i;
71447    struct yColCache *p;
71448    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
71449      if( p->iReg==iReg ){
71450        p->tempReg = 1;
71451        return;
71452      }
71453    }
71454    pParse->aTempReg[pParse->nTempReg++] = iReg;
71455  }
71456}
71457
71458/*
71459** Allocate or deallocate a block of nReg consecutive registers
71460*/
71461SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
71462  int i, n;
71463  i = pParse->iRangeReg;
71464  n = pParse->nRangeReg;
71465  if( nReg<=n ){
71466    assert( !usedAsColumnCache(pParse, i, i+n-1) );
71467    pParse->iRangeReg += nReg;
71468    pParse->nRangeReg -= nReg;
71469  }else{
71470    i = pParse->nMem+1;
71471    pParse->nMem += nReg;
71472  }
71473  return i;
71474}
71475SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
71476  sqlite3ExprCacheRemove(pParse, iReg, nReg);
71477  if( nReg>pParse->nRangeReg ){
71478    pParse->nRangeReg = nReg;
71479    pParse->iRangeReg = iReg;
71480  }
71481}
71482
71483/************** End of expr.c ************************************************/
71484/************** Begin file alter.c *******************************************/
71485/*
71486** 2005 February 15
71487**
71488** The author disclaims copyright to this source code.  In place of
71489** a legal notice, here is a blessing:
71490**
71491**    May you do good and not evil.
71492**    May you find forgiveness for yourself and forgive others.
71493**    May you share freely, never taking more than you give.
71494**
71495*************************************************************************
71496** This file contains C code routines that used to generate VDBE code
71497** that implements the ALTER TABLE command.
71498*/
71499
71500/*
71501** The code in this file only exists if we are not omitting the
71502** ALTER TABLE logic from the build.
71503*/
71504#ifndef SQLITE_OMIT_ALTERTABLE
71505
71506
71507/*
71508** This function is used by SQL generated to implement the
71509** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
71510** CREATE INDEX command. The second is a table name. The table name in
71511** the CREATE TABLE or CREATE INDEX statement is replaced with the third
71512** argument and the result returned. Examples:
71513**
71514** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
71515**     -> 'CREATE TABLE def(a, b, c)'
71516**
71517** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
71518**     -> 'CREATE INDEX i ON def(a, b, c)'
71519*/
71520static void renameTableFunc(
71521  sqlite3_context *context,
71522  int NotUsed,
71523  sqlite3_value **argv
71524){
71525  unsigned char const *zSql = sqlite3_value_text(argv[0]);
71526  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
71527
71528  int token;
71529  Token tname;
71530  unsigned char const *zCsr = zSql;
71531  int len = 0;
71532  char *zRet;
71533
71534  sqlite3 *db = sqlite3_context_db_handle(context);
71535
71536  UNUSED_PARAMETER(NotUsed);
71537
71538  /* The principle used to locate the table name in the CREATE TABLE
71539  ** statement is that the table name is the first non-space token that
71540  ** is immediately followed by a TK_LP or TK_USING token.
71541  */
71542  if( zSql ){
71543    do {
71544      if( !*zCsr ){
71545        /* Ran out of input before finding an opening bracket. Return NULL. */
71546        return;
71547      }
71548
71549      /* Store the token that zCsr points to in tname. */
71550      tname.z = (char*)zCsr;
71551      tname.n = len;
71552
71553      /* Advance zCsr to the next token. Store that token type in 'token',
71554      ** and its length in 'len' (to be used next iteration of this loop).
71555      */
71556      do {
71557        zCsr += len;
71558        len = sqlite3GetToken(zCsr, &token);
71559      } while( token==TK_SPACE );
71560      assert( len>0 );
71561    } while( token!=TK_LP && token!=TK_USING );
71562
71563    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
71564       zTableName, tname.z+tname.n);
71565    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
71566  }
71567}
71568
71569/*
71570** This C function implements an SQL user function that is used by SQL code
71571** generated by the ALTER TABLE ... RENAME command to modify the definition
71572** of any foreign key constraints that use the table being renamed as the
71573** parent table. It is passed three arguments:
71574**
71575**   1) The complete text of the CREATE TABLE statement being modified,
71576**   2) The old name of the table being renamed, and
71577**   3) The new name of the table being renamed.
71578**
71579** It returns the new CREATE TABLE statement. For example:
71580**
71581**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
71582**       -> 'CREATE TABLE t1(a REFERENCES t3)'
71583*/
71584#ifndef SQLITE_OMIT_FOREIGN_KEY
71585static void renameParentFunc(
71586  sqlite3_context *context,
71587  int NotUsed,
71588  sqlite3_value **argv
71589){
71590  sqlite3 *db = sqlite3_context_db_handle(context);
71591  char *zOutput = 0;
71592  char *zResult;
71593  unsigned char const *zInput = sqlite3_value_text(argv[0]);
71594  unsigned char const *zOld = sqlite3_value_text(argv[1]);
71595  unsigned char const *zNew = sqlite3_value_text(argv[2]);
71596
71597  unsigned const char *z;         /* Pointer to token */
71598  int n;                          /* Length of token z */
71599  int token;                      /* Type of token */
71600
71601  UNUSED_PARAMETER(NotUsed);
71602  for(z=zInput; *z; z=z+n){
71603    n = sqlite3GetToken(z, &token);
71604    if( token==TK_REFERENCES ){
71605      char *zParent;
71606      do {
71607        z += n;
71608        n = sqlite3GetToken(z, &token);
71609      }while( token==TK_SPACE );
71610
71611      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
71612      if( zParent==0 ) break;
71613      sqlite3Dequote(zParent);
71614      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
71615        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
71616            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
71617        );
71618        sqlite3DbFree(db, zOutput);
71619        zOutput = zOut;
71620        zInput = &z[n];
71621      }
71622      sqlite3DbFree(db, zParent);
71623    }
71624  }
71625
71626  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
71627  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
71628  sqlite3DbFree(db, zOutput);
71629}
71630#endif
71631
71632#ifndef SQLITE_OMIT_TRIGGER
71633/* This function is used by SQL generated to implement the
71634** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
71635** statement. The second is a table name. The table name in the CREATE
71636** TRIGGER statement is replaced with the third argument and the result
71637** returned. This is analagous to renameTableFunc() above, except for CREATE
71638** TRIGGER, not CREATE INDEX and CREATE TABLE.
71639*/
71640static void renameTriggerFunc(
71641  sqlite3_context *context,
71642  int NotUsed,
71643  sqlite3_value **argv
71644){
71645  unsigned char const *zSql = sqlite3_value_text(argv[0]);
71646  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
71647
71648  int token;
71649  Token tname;
71650  int dist = 3;
71651  unsigned char const *zCsr = zSql;
71652  int len = 0;
71653  char *zRet;
71654  sqlite3 *db = sqlite3_context_db_handle(context);
71655
71656  UNUSED_PARAMETER(NotUsed);
71657
71658  /* The principle used to locate the table name in the CREATE TRIGGER
71659  ** statement is that the table name is the first token that is immediatedly
71660  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
71661  ** of TK_WHEN, TK_BEGIN or TK_FOR.
71662  */
71663  if( zSql ){
71664    do {
71665
71666      if( !*zCsr ){
71667        /* Ran out of input before finding the table name. Return NULL. */
71668        return;
71669      }
71670
71671      /* Store the token that zCsr points to in tname. */
71672      tname.z = (char*)zCsr;
71673      tname.n = len;
71674
71675      /* Advance zCsr to the next token. Store that token type in 'token',
71676      ** and its length in 'len' (to be used next iteration of this loop).
71677      */
71678      do {
71679        zCsr += len;
71680        len = sqlite3GetToken(zCsr, &token);
71681      }while( token==TK_SPACE );
71682      assert( len>0 );
71683
71684      /* Variable 'dist' stores the number of tokens read since the most
71685      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
71686      ** token is read and 'dist' equals 2, the condition stated above
71687      ** to be met.
71688      **
71689      ** Note that ON cannot be a database, table or column name, so
71690      ** there is no need to worry about syntax like
71691      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
71692      */
71693      dist++;
71694      if( token==TK_DOT || token==TK_ON ){
71695        dist = 0;
71696      }
71697    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
71698
71699    /* Variable tname now contains the token that is the old table-name
71700    ** in the CREATE TRIGGER statement.
71701    */
71702    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
71703       zTableName, tname.z+tname.n);
71704    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
71705  }
71706}
71707#endif   /* !SQLITE_OMIT_TRIGGER */
71708
71709/*
71710** Register built-in functions used to help implement ALTER TABLE
71711*/
71712SQLITE_PRIVATE void sqlite3AlterFunctions(void){
71713  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
71714    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
71715#ifndef SQLITE_OMIT_TRIGGER
71716    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
71717#endif
71718#ifndef SQLITE_OMIT_FOREIGN_KEY
71719    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
71720#endif
71721  };
71722  int i;
71723  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
71724  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
71725
71726  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
71727    sqlite3FuncDefInsert(pHash, &aFunc[i]);
71728  }
71729}
71730
71731/*
71732** This function is used to create the text of expressions of the form:
71733**
71734**   name=<constant1> OR name=<constant2> OR ...
71735**
71736** If argument zWhere is NULL, then a pointer string containing the text
71737** "name=<constant>" is returned, where <constant> is the quoted version
71738** of the string passed as argument zConstant. The returned buffer is
71739** allocated using sqlite3DbMalloc(). It is the responsibility of the
71740** caller to ensure that it is eventually freed.
71741**
71742** If argument zWhere is not NULL, then the string returned is
71743** "<where> OR name=<constant>", where <where> is the contents of zWhere.
71744** In this case zWhere is passed to sqlite3DbFree() before returning.
71745**
71746*/
71747static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
71748  char *zNew;
71749  if( !zWhere ){
71750    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
71751  }else{
71752    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
71753    sqlite3DbFree(db, zWhere);
71754  }
71755  return zNew;
71756}
71757
71758#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
71759/*
71760** Generate the text of a WHERE expression which can be used to select all
71761** tables that have foreign key constraints that refer to table pTab (i.e.
71762** constraints for which pTab is the parent table) from the sqlite_master
71763** table.
71764*/
71765static char *whereForeignKeys(Parse *pParse, Table *pTab){
71766  FKey *p;
71767  char *zWhere = 0;
71768  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
71769    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
71770  }
71771  return zWhere;
71772}
71773#endif
71774
71775/*
71776** Generate the text of a WHERE expression which can be used to select all
71777** temporary triggers on table pTab from the sqlite_temp_master table. If
71778** table pTab has no temporary triggers, or is itself stored in the
71779** temporary database, NULL is returned.
71780*/
71781static char *whereTempTriggers(Parse *pParse, Table *pTab){
71782  Trigger *pTrig;
71783  char *zWhere = 0;
71784  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
71785
71786  /* If the table is not located in the temp-db (in which case NULL is
71787  ** returned, loop through the tables list of triggers. For each trigger
71788  ** that is not part of the temp-db schema, add a clause to the WHERE
71789  ** expression being built up in zWhere.
71790  */
71791  if( pTab->pSchema!=pTempSchema ){
71792    sqlite3 *db = pParse->db;
71793    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
71794      if( pTrig->pSchema==pTempSchema ){
71795        zWhere = whereOrName(db, zWhere, pTrig->zName);
71796      }
71797    }
71798  }
71799  return zWhere;
71800}
71801
71802/*
71803** Generate code to drop and reload the internal representation of table
71804** pTab from the database, including triggers and temporary triggers.
71805** Argument zName is the name of the table in the database schema at
71806** the time the generated code is executed. This can be different from
71807** pTab->zName if this function is being called to code part of an
71808** "ALTER TABLE RENAME TO" statement.
71809*/
71810static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
71811  Vdbe *v;
71812  char *zWhere;
71813  int iDb;                   /* Index of database containing pTab */
71814#ifndef SQLITE_OMIT_TRIGGER
71815  Trigger *pTrig;
71816#endif
71817
71818  v = sqlite3GetVdbe(pParse);
71819  if( NEVER(v==0) ) return;
71820  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71821  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
71822  assert( iDb>=0 );
71823
71824#ifndef SQLITE_OMIT_TRIGGER
71825  /* Drop any table triggers from the internal schema. */
71826  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
71827    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
71828    assert( iTrigDb==iDb || iTrigDb==1 );
71829    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
71830  }
71831#endif
71832
71833  /* Drop the table and index from the internal schema.  */
71834  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
71835
71836  /* Reload the table, index and permanent trigger schemas. */
71837  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
71838  if( !zWhere ) return;
71839  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
71840
71841#ifndef SQLITE_OMIT_TRIGGER
71842  /* Now, if the table is not stored in the temp database, reload any temp
71843  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
71844  */
71845  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
71846    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
71847  }
71848#endif
71849}
71850
71851/*
71852** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
71853** command.
71854*/
71855SQLITE_PRIVATE void sqlite3AlterRenameTable(
71856  Parse *pParse,            /* Parser context. */
71857  SrcList *pSrc,            /* The table to rename. */
71858  Token *pName              /* The new table name. */
71859){
71860  int iDb;                  /* Database that contains the table */
71861  char *zDb;                /* Name of database iDb */
71862  Table *pTab;              /* Table being renamed */
71863  char *zName = 0;          /* NULL-terminated version of pName */
71864  sqlite3 *db = pParse->db; /* Database connection */
71865  int nTabName;             /* Number of UTF-8 characters in zTabName */
71866  const char *zTabName;     /* Original name of the table */
71867  Vdbe *v;
71868#ifndef SQLITE_OMIT_TRIGGER
71869  char *zWhere = 0;         /* Where clause to locate temp triggers */
71870#endif
71871  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
71872  int savedDbFlags;         /* Saved value of db->flags */
71873
71874  savedDbFlags = db->flags;
71875  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
71876  assert( pSrc->nSrc==1 );
71877  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
71878
71879  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
71880  if( !pTab ) goto exit_rename_table;
71881  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
71882  zDb = db->aDb[iDb].zName;
71883  db->flags |= SQLITE_PreferBuiltin;
71884
71885  /* Get a NULL terminated version of the new table name. */
71886  zName = sqlite3NameFromToken(db, pName);
71887  if( !zName ) goto exit_rename_table;
71888
71889  /* Check that a table or index named 'zName' does not already exist
71890  ** in database iDb. If so, this is an error.
71891  */
71892  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
71893    sqlite3ErrorMsg(pParse,
71894        "there is already another table or index with this name: %s", zName);
71895    goto exit_rename_table;
71896  }
71897
71898  /* Make sure it is not a system table being altered, or a reserved name
71899  ** that the table is being renamed to.
71900  */
71901  if( sqlite3Strlen30(pTab->zName)>6
71902   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
71903  ){
71904    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
71905    goto exit_rename_table;
71906  }
71907  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
71908    goto exit_rename_table;
71909  }
71910
71911#ifndef SQLITE_OMIT_VIEW
71912  if( pTab->pSelect ){
71913    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
71914    goto exit_rename_table;
71915  }
71916#endif
71917
71918#ifndef SQLITE_OMIT_AUTHORIZATION
71919  /* Invoke the authorization callback. */
71920  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
71921    goto exit_rename_table;
71922  }
71923#endif
71924
71925#ifndef SQLITE_OMIT_VIRTUALTABLE
71926  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
71927    goto exit_rename_table;
71928  }
71929  if( IsVirtual(pTab) ){
71930    pVTab = sqlite3GetVTable(db, pTab);
71931    if( pVTab->pVtab->pModule->xRename==0 ){
71932      pVTab = 0;
71933    }
71934  }
71935#endif
71936
71937  /* Begin a transaction and code the VerifyCookie for database iDb.
71938  ** Then modify the schema cookie (since the ALTER TABLE modifies the
71939  ** schema). Open a statement transaction if the table is a virtual
71940  ** table.
71941  */
71942  v = sqlite3GetVdbe(pParse);
71943  if( v==0 ){
71944    goto exit_rename_table;
71945  }
71946  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
71947  sqlite3ChangeCookie(pParse, iDb);
71948
71949  /* If this is a virtual table, invoke the xRename() function if
71950  ** one is defined. The xRename() callback will modify the names
71951  ** of any resources used by the v-table implementation (including other
71952  ** SQLite tables) that are identified by the name of the virtual table.
71953  */
71954#ifndef SQLITE_OMIT_VIRTUALTABLE
71955  if( pVTab ){
71956    int i = ++pParse->nMem;
71957    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
71958    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
71959    sqlite3MayAbort(pParse);
71960  }
71961#endif
71962
71963  /* figure out how many UTF-8 characters are in zName */
71964  zTabName = pTab->zName;
71965  nTabName = sqlite3Utf8CharLen(zTabName, -1);
71966
71967#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
71968  if( db->flags&SQLITE_ForeignKeys ){
71969    /* If foreign-key support is enabled, rewrite the CREATE TABLE
71970    ** statements corresponding to all child tables of foreign key constraints
71971    ** for which the renamed table is the parent table.  */
71972    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
71973      sqlite3NestedParse(pParse,
71974          "UPDATE \"%w\".%s SET "
71975              "sql = sqlite_rename_parent(sql, %Q, %Q) "
71976              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
71977      sqlite3DbFree(db, zWhere);
71978    }
71979  }
71980#endif
71981
71982  /* Modify the sqlite_master table to use the new table name. */
71983  sqlite3NestedParse(pParse,
71984      "UPDATE %Q.%s SET "
71985#ifdef SQLITE_OMIT_TRIGGER
71986          "sql = sqlite_rename_table(sql, %Q), "
71987#else
71988          "sql = CASE "
71989            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
71990            "ELSE sqlite_rename_table(sql, %Q) END, "
71991#endif
71992          "tbl_name = %Q, "
71993          "name = CASE "
71994            "WHEN type='table' THEN %Q "
71995            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
71996             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
71997            "ELSE name END "
71998      "WHERE tbl_name=%Q AND "
71999          "(type='table' OR type='index' OR type='trigger');",
72000      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
72001#ifndef SQLITE_OMIT_TRIGGER
72002      zName,
72003#endif
72004      zName, nTabName, zTabName
72005  );
72006
72007#ifndef SQLITE_OMIT_AUTOINCREMENT
72008  /* If the sqlite_sequence table exists in this database, then update
72009  ** it with the new table name.
72010  */
72011  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
72012    sqlite3NestedParse(pParse,
72013        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
72014        zDb, zName, pTab->zName);
72015  }
72016#endif
72017
72018#ifndef SQLITE_OMIT_TRIGGER
72019  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
72020  ** table. Don't do this if the table being ALTERed is itself located in
72021  ** the temp database.
72022  */
72023  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
72024    sqlite3NestedParse(pParse,
72025        "UPDATE sqlite_temp_master SET "
72026            "sql = sqlite_rename_trigger(sql, %Q), "
72027            "tbl_name = %Q "
72028            "WHERE %s;", zName, zName, zWhere);
72029    sqlite3DbFree(db, zWhere);
72030  }
72031#endif
72032
72033#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72034  if( db->flags&SQLITE_ForeignKeys ){
72035    FKey *p;
72036    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
72037      Table *pFrom = p->pFrom;
72038      if( pFrom!=pTab ){
72039        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
72040      }
72041    }
72042  }
72043#endif
72044
72045  /* Drop and reload the internal table schema. */
72046  reloadTableSchema(pParse, pTab, zName);
72047
72048exit_rename_table:
72049  sqlite3SrcListDelete(db, pSrc);
72050  sqlite3DbFree(db, zName);
72051  db->flags = savedDbFlags;
72052}
72053
72054
72055/*
72056** Generate code to make sure the file format number is at least minFormat.
72057** The generated code will increase the file format number if necessary.
72058*/
72059SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
72060  Vdbe *v;
72061  v = sqlite3GetVdbe(pParse);
72062  /* The VDBE should have been allocated before this routine is called.
72063  ** If that allocation failed, we would have quit before reaching this
72064  ** point */
72065  if( ALWAYS(v) ){
72066    int r1 = sqlite3GetTempReg(pParse);
72067    int r2 = sqlite3GetTempReg(pParse);
72068    int j1;
72069    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
72070    sqlite3VdbeUsesBtree(v, iDb);
72071    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
72072    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
72073    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
72074    sqlite3VdbeJumpHere(v, j1);
72075    sqlite3ReleaseTempReg(pParse, r1);
72076    sqlite3ReleaseTempReg(pParse, r2);
72077  }
72078}
72079
72080/*
72081** This function is called after an "ALTER TABLE ... ADD" statement
72082** has been parsed. Argument pColDef contains the text of the new
72083** column definition.
72084**
72085** The Table structure pParse->pNewTable was extended to include
72086** the new column during parsing.
72087*/
72088SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
72089  Table *pNew;              /* Copy of pParse->pNewTable */
72090  Table *pTab;              /* Table being altered */
72091  int iDb;                  /* Database number */
72092  const char *zDb;          /* Database name */
72093  const char *zTab;         /* Table name */
72094  char *zCol;               /* Null-terminated column definition */
72095  Column *pCol;             /* The new column */
72096  Expr *pDflt;              /* Default value for the new column */
72097  sqlite3 *db;              /* The database connection; */
72098
72099  db = pParse->db;
72100  if( pParse->nErr || db->mallocFailed ) return;
72101  pNew = pParse->pNewTable;
72102  assert( pNew );
72103
72104  assert( sqlite3BtreeHoldsAllMutexes(db) );
72105  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
72106  zDb = db->aDb[iDb].zName;
72107  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
72108  pCol = &pNew->aCol[pNew->nCol-1];
72109  pDflt = pCol->pDflt;
72110  pTab = sqlite3FindTable(db, zTab, zDb);
72111  assert( pTab );
72112
72113#ifndef SQLITE_OMIT_AUTHORIZATION
72114  /* Invoke the authorization callback. */
72115  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
72116    return;
72117  }
72118#endif
72119
72120  /* If the default value for the new column was specified with a
72121  ** literal NULL, then set pDflt to 0. This simplifies checking
72122  ** for an SQL NULL default below.
72123  */
72124  if( pDflt && pDflt->op==TK_NULL ){
72125    pDflt = 0;
72126  }
72127
72128  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
72129  ** If there is a NOT NULL constraint, then the default value for the
72130  ** column must not be NULL.
72131  */
72132  if( pCol->isPrimKey ){
72133    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
72134    return;
72135  }
72136  if( pNew->pIndex ){
72137    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
72138    return;
72139  }
72140  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
72141    sqlite3ErrorMsg(pParse,
72142        "Cannot add a REFERENCES column with non-NULL default value");
72143    return;
72144  }
72145  if( pCol->notNull && !pDflt ){
72146    sqlite3ErrorMsg(pParse,
72147        "Cannot add a NOT NULL column with default value NULL");
72148    return;
72149  }
72150
72151  /* Ensure the default expression is something that sqlite3ValueFromExpr()
72152  ** can handle (i.e. not CURRENT_TIME etc.)
72153  */
72154  if( pDflt ){
72155    sqlite3_value *pVal;
72156    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
72157      db->mallocFailed = 1;
72158      return;
72159    }
72160    if( !pVal ){
72161      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
72162      return;
72163    }
72164    sqlite3ValueFree(pVal);
72165  }
72166
72167  /* Modify the CREATE TABLE statement. */
72168  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
72169  if( zCol ){
72170    char *zEnd = &zCol[pColDef->n-1];
72171    int savedDbFlags = db->flags;
72172    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
72173      *zEnd-- = '\0';
72174    }
72175    db->flags |= SQLITE_PreferBuiltin;
72176    sqlite3NestedParse(pParse,
72177        "UPDATE \"%w\".%s SET "
72178          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
72179        "WHERE type = 'table' AND name = %Q",
72180      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
72181      zTab
72182    );
72183    sqlite3DbFree(db, zCol);
72184    db->flags = savedDbFlags;
72185  }
72186
72187  /* If the default value of the new column is NULL, then set the file
72188  ** format to 2. If the default value of the new column is not NULL,
72189  ** the file format becomes 3.
72190  */
72191  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
72192
72193  /* Reload the schema of the modified table. */
72194  reloadTableSchema(pParse, pTab, pTab->zName);
72195}
72196
72197/*
72198** This function is called by the parser after the table-name in
72199** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
72200** pSrc is the full-name of the table being altered.
72201**
72202** This routine makes a (partial) copy of the Table structure
72203** for the table being altered and sets Parse.pNewTable to point
72204** to it. Routines called by the parser as the column definition
72205** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
72206** the copy. The copy of the Table structure is deleted by tokenize.c
72207** after parsing is finished.
72208**
72209** Routine sqlite3AlterFinishAddColumn() will be called to complete
72210** coding the "ALTER TABLE ... ADD" statement.
72211*/
72212SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
72213  Table *pNew;
72214  Table *pTab;
72215  Vdbe *v;
72216  int iDb;
72217  int i;
72218  int nAlloc;
72219  sqlite3 *db = pParse->db;
72220
72221  /* Look up the table being altered. */
72222  assert( pParse->pNewTable==0 );
72223  assert( sqlite3BtreeHoldsAllMutexes(db) );
72224  if( db->mallocFailed ) goto exit_begin_add_column;
72225  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
72226  if( !pTab ) goto exit_begin_add_column;
72227
72228#ifndef SQLITE_OMIT_VIRTUALTABLE
72229  if( IsVirtual(pTab) ){
72230    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
72231    goto exit_begin_add_column;
72232  }
72233#endif
72234
72235  /* Make sure this is not an attempt to ALTER a view. */
72236  if( pTab->pSelect ){
72237    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
72238    goto exit_begin_add_column;
72239  }
72240
72241  assert( pTab->addColOffset>0 );
72242  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72243
72244  /* Put a copy of the Table struct in Parse.pNewTable for the
72245  ** sqlite3AddColumn() function and friends to modify.  But modify
72246  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
72247  ** prefix, we insure that the name will not collide with an existing
72248  ** table because user table are not allowed to have the "sqlite_"
72249  ** prefix on their name.
72250  */
72251  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
72252  if( !pNew ) goto exit_begin_add_column;
72253  pParse->pNewTable = pNew;
72254  pNew->nRef = 1;
72255  pNew->nCol = pTab->nCol;
72256  assert( pNew->nCol>0 );
72257  nAlloc = (((pNew->nCol-1)/8)*8)+8;
72258  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
72259  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
72260  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
72261  if( !pNew->aCol || !pNew->zName ){
72262    db->mallocFailed = 1;
72263    goto exit_begin_add_column;
72264  }
72265  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
72266  for(i=0; i<pNew->nCol; i++){
72267    Column *pCol = &pNew->aCol[i];
72268    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
72269    pCol->zColl = 0;
72270    pCol->zType = 0;
72271    pCol->pDflt = 0;
72272    pCol->zDflt = 0;
72273  }
72274  pNew->pSchema = db->aDb[iDb].pSchema;
72275  pNew->addColOffset = pTab->addColOffset;
72276  pNew->nRef = 1;
72277
72278  /* Begin a transaction and increment the schema cookie.  */
72279  sqlite3BeginWriteOperation(pParse, 0, iDb);
72280  v = sqlite3GetVdbe(pParse);
72281  if( !v ) goto exit_begin_add_column;
72282  sqlite3ChangeCookie(pParse, iDb);
72283
72284exit_begin_add_column:
72285  sqlite3SrcListDelete(db, pSrc);
72286  return;
72287}
72288#endif  /* SQLITE_ALTER_TABLE */
72289
72290/************** End of alter.c ***********************************************/
72291/************** Begin file analyze.c *****************************************/
72292/*
72293** 2005 July 8
72294**
72295** The author disclaims copyright to this source code.  In place of
72296** a legal notice, here is a blessing:
72297**
72298**    May you do good and not evil.
72299**    May you find forgiveness for yourself and forgive others.
72300**    May you share freely, never taking more than you give.
72301**
72302*************************************************************************
72303** This file contains code associated with the ANALYZE command.
72304*/
72305#ifndef SQLITE_OMIT_ANALYZE
72306
72307/*
72308** This routine generates code that opens the sqlite_stat1 table for
72309** writing with cursor iStatCur. If the library was built with the
72310** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
72311** opened for writing using cursor (iStatCur+1)
72312**
72313** If the sqlite_stat1 tables does not previously exist, it is created.
72314** Similarly, if the sqlite_stat2 table does not exist and the library
72315** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
72316**
72317** Argument zWhere may be a pointer to a buffer containing a table name,
72318** or it may be a NULL pointer. If it is not NULL, then all entries in
72319** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
72320** with the named table are deleted. If zWhere==0, then code is generated
72321** to delete all stat table entries.
72322*/
72323static void openStatTable(
72324  Parse *pParse,          /* Parsing context */
72325  int iDb,                /* The database we are looking in */
72326  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
72327  const char *zWhere      /* Delete entries associated with this table */
72328){
72329  static const struct {
72330    const char *zName;
72331    const char *zCols;
72332  } aTable[] = {
72333    { "sqlite_stat1", "tbl,idx,stat" },
72334#ifdef SQLITE_ENABLE_STAT2
72335    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
72336#endif
72337  };
72338
72339  int aRoot[] = {0, 0};
72340  u8 aCreateTbl[] = {0, 0};
72341
72342  int i;
72343  sqlite3 *db = pParse->db;
72344  Db *pDb;
72345  Vdbe *v = sqlite3GetVdbe(pParse);
72346  if( v==0 ) return;
72347  assert( sqlite3BtreeHoldsAllMutexes(db) );
72348  assert( sqlite3VdbeDb(v)==db );
72349  pDb = &db->aDb[iDb];
72350
72351  for(i=0; i<ArraySize(aTable); i++){
72352    const char *zTab = aTable[i].zName;
72353    Table *pStat;
72354    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
72355      /* The sqlite_stat[12] table does not exist. Create it. Note that a
72356      ** side-effect of the CREATE TABLE statement is to leave the rootpage
72357      ** of the new table in register pParse->regRoot. This is important
72358      ** because the OpenWrite opcode below will be needing it. */
72359      sqlite3NestedParse(pParse,
72360          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
72361      );
72362      aRoot[i] = pParse->regRoot;
72363      aCreateTbl[i] = 1;
72364    }else{
72365      /* The table already exists. If zWhere is not NULL, delete all entries
72366      ** associated with the table zWhere. If zWhere is NULL, delete the
72367      ** entire contents of the table. */
72368      aRoot[i] = pStat->tnum;
72369      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
72370      if( zWhere ){
72371        sqlite3NestedParse(pParse,
72372           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
72373        );
72374      }else{
72375        /* The sqlite_stat[12] table already exists.  Delete all rows. */
72376        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
72377      }
72378    }
72379  }
72380
72381  /* Open the sqlite_stat[12] tables for writing. */
72382  for(i=0; i<ArraySize(aTable); i++){
72383    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
72384    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
72385    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
72386  }
72387}
72388
72389/*
72390** Generate code to do an analysis of all indices associated with
72391** a single table.
72392*/
72393static void analyzeOneTable(
72394  Parse *pParse,   /* Parser context */
72395  Table *pTab,     /* Table whose indices are to be analyzed */
72396  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
72397  int iMem         /* Available memory locations begin here */
72398){
72399  sqlite3 *db = pParse->db;    /* Database handle */
72400  Index *pIdx;                 /* An index to being analyzed */
72401  int iIdxCur;                 /* Cursor open on index being analyzed */
72402  Vdbe *v;                     /* The virtual machine being built up */
72403  int i;                       /* Loop counter */
72404  int topOfLoop;               /* The top of the loop */
72405  int endOfLoop;               /* The end of the loop */
72406  int addr;                    /* The address of an instruction */
72407  int iDb;                     /* Index of database containing pTab */
72408  int regTabname = iMem++;     /* Register containing table name */
72409  int regIdxname = iMem++;     /* Register containing index name */
72410  int regSampleno = iMem++;    /* Register containing next sample number */
72411  int regCol = iMem++;         /* Content of a column analyzed table */
72412  int regRec = iMem++;         /* Register holding completed record */
72413  int regTemp = iMem++;        /* Temporary use register */
72414  int regRowid = iMem++;       /* Rowid for the inserted record */
72415
72416#ifdef SQLITE_ENABLE_STAT2
72417  int regTemp2 = iMem++;       /* Temporary use register */
72418  int regSamplerecno = iMem++; /* Index of next sample to record */
72419  int regRecno = iMem++;       /* Current sample index */
72420  int regLast = iMem++;        /* Index of last sample to record */
72421  int regFirst = iMem++;       /* Index of first sample to record */
72422#endif
72423
72424  v = sqlite3GetVdbe(pParse);
72425  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
72426    /* Do no analysis for tables that have no indices */
72427    return;
72428  }
72429  assert( sqlite3BtreeHoldsAllMutexes(db) );
72430  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72431  assert( iDb>=0 );
72432#ifndef SQLITE_OMIT_AUTHORIZATION
72433  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
72434      db->aDb[iDb].zName ) ){
72435    return;
72436  }
72437#endif
72438
72439  /* Establish a read-lock on the table at the shared-cache level. */
72440  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72441
72442  iIdxCur = pParse->nTab++;
72443  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72444    int nCol = pIdx->nColumn;
72445    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72446
72447    if( iMem+1+(nCol*2)>pParse->nMem ){
72448      pParse->nMem = iMem+1+(nCol*2);
72449    }
72450
72451    /* Open a cursor to the index to be analyzed. */
72452    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
72453    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
72454        (char *)pKey, P4_KEYINFO_HANDOFF);
72455    VdbeComment((v, "%s", pIdx->zName));
72456
72457    /* Populate the registers containing the table and index names. */
72458    if( pTab->pIndex==pIdx ){
72459      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
72460    }
72461    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
72462
72463#ifdef SQLITE_ENABLE_STAT2
72464
72465    /* If this iteration of the loop is generating code to analyze the
72466    ** first index in the pTab->pIndex list, then register regLast has
72467    ** not been populated. In this case populate it now.  */
72468    if( pTab->pIndex==pIdx ){
72469      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
72470      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
72471      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
72472
72473      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
72474      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
72475      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
72476      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
72477      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
72478      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
72479      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
72480      sqlite3VdbeJumpHere(v, addr);
72481    }
72482
72483    /* Zero the regSampleno and regRecno registers. */
72484    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
72485    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
72486    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
72487#endif
72488
72489    /* The block of memory cells initialized here is used as follows.
72490    **
72491    **    iMem:
72492    **        The total number of rows in the table.
72493    **
72494    **    iMem+1 .. iMem+nCol:
72495    **        Number of distinct entries in index considering the
72496    **        left-most N columns only, where N is between 1 and nCol,
72497    **        inclusive.
72498    **
72499    **    iMem+nCol+1 .. Mem+2*nCol:
72500    **        Previous value of indexed columns, from left to right.
72501    **
72502    ** Cells iMem through iMem+nCol are initialized to 0. The others are
72503    ** initialized to contain an SQL NULL.
72504    */
72505    for(i=0; i<=nCol; i++){
72506      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
72507    }
72508    for(i=0; i<nCol; i++){
72509      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
72510    }
72511
72512    /* Start the analysis loop. This loop runs through all the entries in
72513    ** the index b-tree.  */
72514    endOfLoop = sqlite3VdbeMakeLabel(v);
72515    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
72516    topOfLoop = sqlite3VdbeCurrentAddr(v);
72517    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
72518
72519    for(i=0; i<nCol; i++){
72520      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
72521#ifdef SQLITE_ENABLE_STAT2
72522      if( i==0 ){
72523        /* Check if the record that cursor iIdxCur points to contains a
72524        ** value that should be stored in the sqlite_stat2 table. If so,
72525        ** store it.  */
72526        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
72527        assert( regTabname+1==regIdxname
72528             && regTabname+2==regSampleno
72529             && regTabname+3==regCol
72530        );
72531        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
72532        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
72533        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
72534        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
72535
72536        /* Calculate new values for regSamplerecno and regSampleno.
72537        **
72538        **   sampleno = sampleno + 1
72539        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
72540        */
72541        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
72542        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
72543        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
72544        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
72545        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
72546        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
72547        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
72548
72549        sqlite3VdbeJumpHere(v, ne);
72550        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
72551      }
72552#endif
72553
72554      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
72555      /**** TODO:  add collating sequence *****/
72556      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
72557    }
72558    if( db->mallocFailed ){
72559      /* If a malloc failure has occurred, then the result of the expression
72560      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
72561      ** below may be negative. Which causes an assert() to fail (or an
72562      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
72563      return;
72564    }
72565    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
72566    for(i=0; i<nCol; i++){
72567      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
72568      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
72569      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
72570    }
72571
72572    /* End of the analysis loop. */
72573    sqlite3VdbeResolveLabel(v, endOfLoop);
72574    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
72575    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
72576
72577    /* Store the results in sqlite_stat1.
72578    **
72579    ** The result is a single row of the sqlite_stat1 table.  The first
72580    ** two columns are the names of the table and index.  The third column
72581    ** is a string composed of a list of integer statistics about the
72582    ** index.  The first integer in the list is the total number of entries
72583    ** in the index.  There is one additional integer in the list for each
72584    ** column of the table.  This additional integer is a guess of how many
72585    ** rows of the table the index will select.  If D is the count of distinct
72586    ** values and K is the total number of rows, then the integer is computed
72587    ** as:
72588    **
72589    **        I = (K+D-1)/D
72590    **
72591    ** If K==0 then no entry is made into the sqlite_stat1 table.
72592    ** If K>0 then it is always the case the D>0 so division by zero
72593    ** is never possible.
72594    */
72595    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
72596    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
72597    for(i=0; i<nCol; i++){
72598      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
72599      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
72600      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
72601      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
72602      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
72603      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
72604      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
72605    }
72606    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
72607    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
72608    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
72609    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
72610    sqlite3VdbeJumpHere(v, addr);
72611  }
72612}
72613
72614/*
72615** Generate code that will cause the most recent index analysis to
72616** be laoded into internal hash tables where is can be used.
72617*/
72618static void loadAnalysis(Parse *pParse, int iDb){
72619  Vdbe *v = sqlite3GetVdbe(pParse);
72620  if( v ){
72621    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
72622  }
72623}
72624
72625/*
72626** Generate code that will do an analysis of an entire database
72627*/
72628static void analyzeDatabase(Parse *pParse, int iDb){
72629  sqlite3 *db = pParse->db;
72630  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
72631  HashElem *k;
72632  int iStatCur;
72633  int iMem;
72634
72635  sqlite3BeginWriteOperation(pParse, 0, iDb);
72636  iStatCur = pParse->nTab;
72637  pParse->nTab += 2;
72638  openStatTable(pParse, iDb, iStatCur, 0);
72639  iMem = pParse->nMem+1;
72640  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
72641    Table *pTab = (Table*)sqliteHashData(k);
72642    analyzeOneTable(pParse, pTab, iStatCur, iMem);
72643  }
72644  loadAnalysis(pParse, iDb);
72645}
72646
72647/*
72648** Generate code that will do an analysis of a single table in
72649** a database.
72650*/
72651static void analyzeTable(Parse *pParse, Table *pTab){
72652  int iDb;
72653  int iStatCur;
72654
72655  assert( pTab!=0 );
72656  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
72657  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72658  sqlite3BeginWriteOperation(pParse, 0, iDb);
72659  iStatCur = pParse->nTab;
72660  pParse->nTab += 2;
72661  openStatTable(pParse, iDb, iStatCur, pTab->zName);
72662  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
72663  loadAnalysis(pParse, iDb);
72664}
72665
72666/*
72667** Generate code for the ANALYZE command.  The parser calls this routine
72668** when it recognizes an ANALYZE command.
72669**
72670**        ANALYZE                            -- 1
72671**        ANALYZE  <database>                -- 2
72672**        ANALYZE  ?<database>.?<tablename>  -- 3
72673**
72674** Form 1 causes all indices in all attached databases to be analyzed.
72675** Form 2 analyzes all indices the single database named.
72676** Form 3 analyzes all indices associated with the named table.
72677*/
72678SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
72679  sqlite3 *db = pParse->db;
72680  int iDb;
72681  int i;
72682  char *z, *zDb;
72683  Table *pTab;
72684  Token *pTableName;
72685
72686  /* Read the database schema. If an error occurs, leave an error message
72687  ** and code in pParse and return NULL. */
72688  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
72689  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
72690    return;
72691  }
72692
72693  assert( pName2!=0 || pName1==0 );
72694  if( pName1==0 ){
72695    /* Form 1:  Analyze everything */
72696    for(i=0; i<db->nDb; i++){
72697      if( i==1 ) continue;  /* Do not analyze the TEMP database */
72698      analyzeDatabase(pParse, i);
72699    }
72700  }else if( pName2->n==0 ){
72701    /* Form 2:  Analyze the database or table named */
72702    iDb = sqlite3FindDb(db, pName1);
72703    if( iDb>=0 ){
72704      analyzeDatabase(pParse, iDb);
72705    }else{
72706      z = sqlite3NameFromToken(db, pName1);
72707      if( z ){
72708        pTab = sqlite3LocateTable(pParse, 0, z, 0);
72709        sqlite3DbFree(db, z);
72710        if( pTab ){
72711          analyzeTable(pParse, pTab);
72712        }
72713      }
72714    }
72715  }else{
72716    /* Form 3: Analyze the fully qualified table name */
72717    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
72718    if( iDb>=0 ){
72719      zDb = db->aDb[iDb].zName;
72720      z = sqlite3NameFromToken(db, pTableName);
72721      if( z ){
72722        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
72723        sqlite3DbFree(db, z);
72724        if( pTab ){
72725          analyzeTable(pParse, pTab);
72726        }
72727      }
72728    }
72729  }
72730}
72731
72732/*
72733** Used to pass information from the analyzer reader through to the
72734** callback routine.
72735*/
72736typedef struct analysisInfo analysisInfo;
72737struct analysisInfo {
72738  sqlite3 *db;
72739  const char *zDatabase;
72740};
72741
72742/*
72743** This callback is invoked once for each index when reading the
72744** sqlite_stat1 table.
72745**
72746**     argv[0] = name of the index
72747**     argv[1] = results of analysis - on integer for each column
72748*/
72749static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
72750  analysisInfo *pInfo = (analysisInfo*)pData;
72751  Index *pIndex;
72752  int i, c;
72753  unsigned int v;
72754  const char *z;
72755
72756  assert( argc==2 );
72757  UNUSED_PARAMETER2(NotUsed, argc);
72758
72759  if( argv==0 || argv[0]==0 || argv[1]==0 ){
72760    return 0;
72761  }
72762  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
72763  if( pIndex==0 ){
72764    return 0;
72765  }
72766  z = argv[1];
72767  for(i=0; *z && i<=pIndex->nColumn; i++){
72768    v = 0;
72769    while( (c=z[0])>='0' && c<='9' ){
72770      v = v*10 + c - '0';
72771      z++;
72772    }
72773    pIndex->aiRowEst[i] = v;
72774    if( *z==' ' ) z++;
72775  }
72776  return 0;
72777}
72778
72779/*
72780** If the Index.aSample variable is not NULL, delete the aSample[] array
72781** and its contents.
72782*/
72783SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
72784#ifdef SQLITE_ENABLE_STAT2
72785  if( pIdx->aSample ){
72786    int j;
72787    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
72788      IndexSample *p = &pIdx->aSample[j];
72789      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
72790        sqlite3DbFree(db, p->u.z);
72791      }
72792    }
72793    sqlite3DbFree(db, pIdx->aSample);
72794  }
72795#else
72796  UNUSED_PARAMETER(db);
72797  UNUSED_PARAMETER(pIdx);
72798#endif
72799}
72800
72801/*
72802** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
72803** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
72804** arrays. The contents of sqlite_stat2 are used to populate the
72805** Index.aSample[] arrays.
72806**
72807** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
72808** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
72809** during compilation and the sqlite_stat2 table is present, no data is
72810** read from it.
72811**
72812** If SQLITE_ENABLE_STAT2 was defined during compilation and the
72813** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
72814** returned. However, in this case, data is read from the sqlite_stat1
72815** table (if it is present) before returning.
72816**
72817** If an OOM error occurs, this function always sets db->mallocFailed.
72818** This means if the caller does not care about other errors, the return
72819** code may be ignored.
72820*/
72821SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
72822  analysisInfo sInfo;
72823  HashElem *i;
72824  char *zSql;
72825  int rc;
72826
72827  assert( iDb>=0 && iDb<db->nDb );
72828  assert( db->aDb[iDb].pBt!=0 );
72829  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
72830
72831  /* Clear any prior statistics */
72832  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
72833    Index *pIdx = sqliteHashData(i);
72834    sqlite3DefaultRowEst(pIdx);
72835    sqlite3DeleteIndexSamples(db, pIdx);
72836    pIdx->aSample = 0;
72837  }
72838
72839  /* Check to make sure the sqlite_stat1 table exists */
72840  sInfo.db = db;
72841  sInfo.zDatabase = db->aDb[iDb].zName;
72842  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
72843    return SQLITE_ERROR;
72844  }
72845
72846  /* Load new statistics out of the sqlite_stat1 table */
72847  zSql = sqlite3MPrintf(db,
72848      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
72849  if( zSql==0 ){
72850    rc = SQLITE_NOMEM;
72851  }else{
72852    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
72853    sqlite3DbFree(db, zSql);
72854  }
72855
72856
72857  /* Load the statistics from the sqlite_stat2 table. */
72858#ifdef SQLITE_ENABLE_STAT2
72859  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
72860    rc = SQLITE_ERROR;
72861  }
72862  if( rc==SQLITE_OK ){
72863    sqlite3_stmt *pStmt = 0;
72864
72865    zSql = sqlite3MPrintf(db,
72866        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
72867    if( !zSql ){
72868      rc = SQLITE_NOMEM;
72869    }else{
72870      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
72871      sqlite3DbFree(db, zSql);
72872    }
72873
72874    if( rc==SQLITE_OK ){
72875      while( sqlite3_step(pStmt)==SQLITE_ROW ){
72876        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
72877        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
72878        if( pIdx ){
72879          int iSample = sqlite3_column_int(pStmt, 1);
72880          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
72881            int eType = sqlite3_column_type(pStmt, 2);
72882
72883            if( pIdx->aSample==0 ){
72884              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
72885              pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
72886              if( pIdx->aSample==0 ){
72887                db->mallocFailed = 1;
72888                break;
72889              }
72890	      memset(pIdx->aSample, 0, sz);
72891            }
72892
72893            assert( pIdx->aSample );
72894            {
72895              IndexSample *pSample = &pIdx->aSample[iSample];
72896              pSample->eType = (u8)eType;
72897              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
72898                pSample->u.r = sqlite3_column_double(pStmt, 2);
72899              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
72900                const char *z = (const char *)(
72901                    (eType==SQLITE_BLOB) ?
72902                    sqlite3_column_blob(pStmt, 2):
72903                    sqlite3_column_text(pStmt, 2)
72904                );
72905                int n = sqlite3_column_bytes(pStmt, 2);
72906                if( n>24 ){
72907                  n = 24;
72908                }
72909                pSample->nByte = (u8)n;
72910                if( n < 1){
72911                  pSample->u.z = 0;
72912                }else{
72913                  pSample->u.z = sqlite3DbStrNDup(0, z, n);
72914                  if( pSample->u.z==0 ){
72915                    db->mallocFailed = 1;
72916                    break;
72917                  }
72918                }
72919              }
72920            }
72921          }
72922        }
72923      }
72924      rc = sqlite3_finalize(pStmt);
72925    }
72926  }
72927#endif
72928
72929  if( rc==SQLITE_NOMEM ){
72930    db->mallocFailed = 1;
72931  }
72932  return rc;
72933}
72934
72935
72936#endif /* SQLITE_OMIT_ANALYZE */
72937
72938/************** End of analyze.c *********************************************/
72939/************** Begin file attach.c ******************************************/
72940/*
72941** 2003 April 6
72942**
72943** The author disclaims copyright to this source code.  In place of
72944** a legal notice, here is a blessing:
72945**
72946**    May you do good and not evil.
72947**    May you find forgiveness for yourself and forgive others.
72948**    May you share freely, never taking more than you give.
72949**
72950*************************************************************************
72951** This file contains code used to implement the ATTACH and DETACH commands.
72952*/
72953
72954#ifndef SQLITE_OMIT_ATTACH
72955/*
72956** Resolve an expression that was part of an ATTACH or DETACH statement. This
72957** is slightly different from resolving a normal SQL expression, because simple
72958** identifiers are treated as strings, not possible column names or aliases.
72959**
72960** i.e. if the parser sees:
72961**
72962**     ATTACH DATABASE abc AS def
72963**
72964** it treats the two expressions as literal strings 'abc' and 'def' instead of
72965** looking for columns of the same name.
72966**
72967** This only applies to the root node of pExpr, so the statement:
72968**
72969**     ATTACH DATABASE abc||def AS 'db2'
72970**
72971** will fail because neither abc or def can be resolved.
72972*/
72973static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
72974{
72975  int rc = SQLITE_OK;
72976  if( pExpr ){
72977    if( pExpr->op!=TK_ID ){
72978      rc = sqlite3ResolveExprNames(pName, pExpr);
72979      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
72980        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
72981        return SQLITE_ERROR;
72982      }
72983    }else{
72984      pExpr->op = TK_STRING;
72985    }
72986  }
72987  return rc;
72988}
72989
72990/*
72991** An SQL user-function registered to do the work of an ATTACH statement. The
72992** three arguments to the function come directly from an attach statement:
72993**
72994**     ATTACH DATABASE x AS y KEY z
72995**
72996**     SELECT sqlite_attach(x, y, z)
72997**
72998** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
72999** third argument.
73000*/
73001static void attachFunc(
73002  sqlite3_context *context,
73003  int NotUsed,
73004  sqlite3_value **argv
73005){
73006  int i;
73007  int rc = 0;
73008  sqlite3 *db = sqlite3_context_db_handle(context);
73009  const char *zName;
73010  const char *zFile;
73011  Db *aNew;
73012  char *zErrDyn = 0;
73013
73014  UNUSED_PARAMETER(NotUsed);
73015
73016  zFile = (const char *)sqlite3_value_text(argv[0]);
73017  zName = (const char *)sqlite3_value_text(argv[1]);
73018  if( zFile==0 ) zFile = "";
73019  if( zName==0 ) zName = "";
73020
73021  /* Check for the following errors:
73022  **
73023  **     * Too many attached databases,
73024  **     * Transaction currently open
73025  **     * Specified database name already being used.
73026  */
73027  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
73028    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
73029      db->aLimit[SQLITE_LIMIT_ATTACHED]
73030    );
73031    goto attach_error;
73032  }
73033  if( !db->autoCommit ){
73034    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
73035    goto attach_error;
73036  }
73037  for(i=0; i<db->nDb; i++){
73038    char *z = db->aDb[i].zName;
73039    assert( z && zName );
73040    if( sqlite3StrICmp(z, zName)==0 ){
73041      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
73042      goto attach_error;
73043    }
73044  }
73045
73046  /* Allocate the new entry in the db->aDb[] array and initialise the schema
73047  ** hash tables.
73048  */
73049  if( db->aDb==db->aDbStatic ){
73050    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
73051    if( aNew==0 ) return;
73052    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
73053  }else{
73054    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
73055    if( aNew==0 ) return;
73056  }
73057  db->aDb = aNew;
73058  aNew = &db->aDb[db->nDb];
73059  memset(aNew, 0, sizeof(*aNew));
73060
73061  /* Open the database file. If the btree is successfully opened, use
73062  ** it to obtain the database schema. At this point the schema may
73063  ** or may not be initialised.
73064  */
73065  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
73066                           db->openFlags | SQLITE_OPEN_MAIN_DB,
73067                           &aNew->pBt);
73068  db->nDb++;
73069  if( rc==SQLITE_CONSTRAINT ){
73070    rc = SQLITE_ERROR;
73071    zErrDyn = sqlite3MPrintf(db, "database is already attached");
73072  }else if( rc==SQLITE_OK ){
73073    Pager *pPager;
73074    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
73075    if( !aNew->pSchema ){
73076      rc = SQLITE_NOMEM;
73077    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
73078      zErrDyn = sqlite3MPrintf(db,
73079        "attached databases must use the same text encoding as main database");
73080      rc = SQLITE_ERROR;
73081    }
73082    pPager = sqlite3BtreePager(aNew->pBt);
73083    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
73084    sqlite3BtreeSecureDelete(aNew->pBt,
73085                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
73086  }
73087  aNew->safety_level = 3;
73088  aNew->zName = sqlite3DbStrDup(db, zName);
73089  if( rc==SQLITE_OK && aNew->zName==0 ){
73090    rc = SQLITE_NOMEM;
73091  }
73092
73093
73094#ifdef SQLITE_HAS_CODEC
73095  if( rc==SQLITE_OK ){
73096    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
73097    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
73098    int nKey;
73099    char *zKey;
73100    int t = sqlite3_value_type(argv[2]);
73101    switch( t ){
73102      case SQLITE_INTEGER:
73103      case SQLITE_FLOAT:
73104        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
73105        rc = SQLITE_ERROR;
73106        break;
73107
73108      case SQLITE_TEXT:
73109      case SQLITE_BLOB:
73110        nKey = sqlite3_value_bytes(argv[2]);
73111        zKey = (char *)sqlite3_value_blob(argv[2]);
73112        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
73113        break;
73114
73115      case SQLITE_NULL:
73116        /* No key specified.  Use the key from the main database */
73117        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
73118        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
73119        break;
73120    }
73121  }
73122#endif
73123
73124  /* If the file was opened successfully, read the schema for the new database.
73125  ** If this fails, or if opening the file failed, then close the file and
73126  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
73127  ** we found it.
73128  */
73129  if( rc==SQLITE_OK ){
73130    sqlite3BtreeEnterAll(db);
73131    rc = sqlite3Init(db, &zErrDyn);
73132    sqlite3BtreeLeaveAll(db);
73133  }
73134  if( rc ){
73135    int iDb = db->nDb - 1;
73136    assert( iDb>=2 );
73137    if( db->aDb[iDb].pBt ){
73138      sqlite3BtreeClose(db->aDb[iDb].pBt);
73139      db->aDb[iDb].pBt = 0;
73140      db->aDb[iDb].pSchema = 0;
73141    }
73142    sqlite3ResetInternalSchema(db, 0);
73143    db->nDb = iDb;
73144    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
73145      db->mallocFailed = 1;
73146      sqlite3DbFree(db, zErrDyn);
73147      zErrDyn = sqlite3MPrintf(db, "out of memory");
73148    }else if( zErrDyn==0 ){
73149      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
73150    }
73151    goto attach_error;
73152  }
73153
73154  return;
73155
73156attach_error:
73157  /* Return an error if we get here */
73158  if( zErrDyn ){
73159    sqlite3_result_error(context, zErrDyn, -1);
73160    sqlite3DbFree(db, zErrDyn);
73161  }
73162  if( rc ) sqlite3_result_error_code(context, rc);
73163}
73164
73165/*
73166** An SQL user-function registered to do the work of an DETACH statement. The
73167** three arguments to the function come directly from a detach statement:
73168**
73169**     DETACH DATABASE x
73170**
73171**     SELECT sqlite_detach(x)
73172*/
73173static void detachFunc(
73174  sqlite3_context *context,
73175  int NotUsed,
73176  sqlite3_value **argv
73177){
73178  const char *zName = (const char *)sqlite3_value_text(argv[0]);
73179  sqlite3 *db = sqlite3_context_db_handle(context);
73180  int i;
73181  Db *pDb = 0;
73182  char zErr[128];
73183
73184  UNUSED_PARAMETER(NotUsed);
73185
73186  if( zName==0 ) zName = "";
73187  for(i=0; i<db->nDb; i++){
73188    pDb = &db->aDb[i];
73189    if( pDb->pBt==0 ) continue;
73190    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
73191  }
73192
73193  if( i>=db->nDb ){
73194    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
73195    goto detach_error;
73196  }
73197  if( i<2 ){
73198    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
73199    goto detach_error;
73200  }
73201  if( !db->autoCommit ){
73202    sqlite3_snprintf(sizeof(zErr), zErr,
73203                     "cannot DETACH database within transaction");
73204    goto detach_error;
73205  }
73206  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
73207    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
73208    goto detach_error;
73209  }
73210
73211  sqlite3BtreeClose(pDb->pBt);
73212  pDb->pBt = 0;
73213  pDb->pSchema = 0;
73214  sqlite3ResetInternalSchema(db, 0);
73215  return;
73216
73217detach_error:
73218  sqlite3_result_error(context, zErr, -1);
73219}
73220
73221/*
73222** This procedure generates VDBE code for a single invocation of either the
73223** sqlite_detach() or sqlite_attach() SQL user functions.
73224*/
73225static void codeAttach(
73226  Parse *pParse,       /* The parser context */
73227  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
73228  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
73229  Expr *pAuthArg,      /* Expression to pass to authorization callback */
73230  Expr *pFilename,     /* Name of database file */
73231  Expr *pDbname,       /* Name of the database to use internally */
73232  Expr *pKey           /* Database key for encryption extension */
73233){
73234  int rc;
73235  NameContext sName;
73236  Vdbe *v;
73237  sqlite3* db = pParse->db;
73238  int regArgs;
73239
73240  memset(&sName, 0, sizeof(NameContext));
73241  sName.pParse = pParse;
73242
73243  if(
73244      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
73245      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
73246      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
73247  ){
73248    pParse->nErr++;
73249    goto attach_end;
73250  }
73251
73252#ifndef SQLITE_OMIT_AUTHORIZATION
73253  if( pAuthArg ){
73254    char *zAuthArg = pAuthArg->u.zToken;
73255    if( NEVER(zAuthArg==0) ){
73256      goto attach_end;
73257    }
73258    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
73259    if(rc!=SQLITE_OK ){
73260      goto attach_end;
73261    }
73262  }
73263#endif /* SQLITE_OMIT_AUTHORIZATION */
73264
73265
73266  v = sqlite3GetVdbe(pParse);
73267  regArgs = sqlite3GetTempRange(pParse, 4);
73268  sqlite3ExprCode(pParse, pFilename, regArgs);
73269  sqlite3ExprCode(pParse, pDbname, regArgs+1);
73270  sqlite3ExprCode(pParse, pKey, regArgs+2);
73271
73272  assert( v || db->mallocFailed );
73273  if( v ){
73274    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
73275    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
73276    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
73277    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
73278
73279    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
73280    ** statement only). For DETACH, set it to false (expire all existing
73281    ** statements).
73282    */
73283    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
73284  }
73285
73286attach_end:
73287  sqlite3ExprDelete(db, pFilename);
73288  sqlite3ExprDelete(db, pDbname);
73289  sqlite3ExprDelete(db, pKey);
73290}
73291
73292/*
73293** Called by the parser to compile a DETACH statement.
73294**
73295**     DETACH pDbname
73296*/
73297SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
73298  static const FuncDef detach_func = {
73299    1,                /* nArg */
73300    SQLITE_UTF8,      /* iPrefEnc */
73301    0,                /* flags */
73302    0,                /* pUserData */
73303    0,                /* pNext */
73304    detachFunc,       /* xFunc */
73305    0,                /* xStep */
73306    0,                /* xFinalize */
73307    "sqlite_detach",  /* zName */
73308    0                 /* pHash */
73309  };
73310  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
73311}
73312
73313/*
73314** Called by the parser to compile an ATTACH statement.
73315**
73316**     ATTACH p AS pDbname KEY pKey
73317*/
73318SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
73319  static const FuncDef attach_func = {
73320    3,                /* nArg */
73321    SQLITE_UTF8,      /* iPrefEnc */
73322    0,                /* flags */
73323    0,                /* pUserData */
73324    0,                /* pNext */
73325    attachFunc,       /* xFunc */
73326    0,                /* xStep */
73327    0,                /* xFinalize */
73328    "sqlite_attach",  /* zName */
73329    0                 /* pHash */
73330  };
73331  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
73332}
73333#endif /* SQLITE_OMIT_ATTACH */
73334
73335/*
73336** Initialize a DbFixer structure.  This routine must be called prior
73337** to passing the structure to one of the sqliteFixAAAA() routines below.
73338**
73339** The return value indicates whether or not fixation is required.  TRUE
73340** means we do need to fix the database references, FALSE means we do not.
73341*/
73342SQLITE_PRIVATE int sqlite3FixInit(
73343  DbFixer *pFix,      /* The fixer to be initialized */
73344  Parse *pParse,      /* Error messages will be written here */
73345  int iDb,            /* This is the database that must be used */
73346  const char *zType,  /* "view", "trigger", or "index" */
73347  const Token *pName  /* Name of the view, trigger, or index */
73348){
73349  sqlite3 *db;
73350
73351  if( NEVER(iDb<0) || iDb==1 ) return 0;
73352  db = pParse->db;
73353  assert( db->nDb>iDb );
73354  pFix->pParse = pParse;
73355  pFix->zDb = db->aDb[iDb].zName;
73356  pFix->zType = zType;
73357  pFix->pName = pName;
73358  return 1;
73359}
73360
73361/*
73362** The following set of routines walk through the parse tree and assign
73363** a specific database to all table references where the database name
73364** was left unspecified in the original SQL statement.  The pFix structure
73365** must have been initialized by a prior call to sqlite3FixInit().
73366**
73367** These routines are used to make sure that an index, trigger, or
73368** view in one database does not refer to objects in a different database.
73369** (Exception: indices, triggers, and views in the TEMP database are
73370** allowed to refer to anything.)  If a reference is explicitly made
73371** to an object in a different database, an error message is added to
73372** pParse->zErrMsg and these routines return non-zero.  If everything
73373** checks out, these routines return 0.
73374*/
73375SQLITE_PRIVATE int sqlite3FixSrcList(
73376  DbFixer *pFix,       /* Context of the fixation */
73377  SrcList *pList       /* The Source list to check and modify */
73378){
73379  int i;
73380  const char *zDb;
73381  struct SrcList_item *pItem;
73382
73383  if( NEVER(pList==0) ) return 0;
73384  zDb = pFix->zDb;
73385  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
73386    if( pItem->zDatabase==0 ){
73387      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
73388    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
73389      sqlite3ErrorMsg(pFix->pParse,
73390         "%s %T cannot reference objects in database %s",
73391         pFix->zType, pFix->pName, pItem->zDatabase);
73392      return 1;
73393    }
73394#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
73395    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
73396    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
73397#endif
73398  }
73399  return 0;
73400}
73401#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
73402SQLITE_PRIVATE int sqlite3FixSelect(
73403  DbFixer *pFix,       /* Context of the fixation */
73404  Select *pSelect      /* The SELECT statement to be fixed to one database */
73405){
73406  while( pSelect ){
73407    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
73408      return 1;
73409    }
73410    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
73411      return 1;
73412    }
73413    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
73414      return 1;
73415    }
73416    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
73417      return 1;
73418    }
73419    pSelect = pSelect->pPrior;
73420  }
73421  return 0;
73422}
73423SQLITE_PRIVATE int sqlite3FixExpr(
73424  DbFixer *pFix,     /* Context of the fixation */
73425  Expr *pExpr        /* The expression to be fixed to one database */
73426){
73427  while( pExpr ){
73428    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
73429    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73430      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
73431    }else{
73432      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
73433    }
73434    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
73435      return 1;
73436    }
73437    pExpr = pExpr->pLeft;
73438  }
73439  return 0;
73440}
73441SQLITE_PRIVATE int sqlite3FixExprList(
73442  DbFixer *pFix,     /* Context of the fixation */
73443  ExprList *pList    /* The expression to be fixed to one database */
73444){
73445  int i;
73446  struct ExprList_item *pItem;
73447  if( pList==0 ) return 0;
73448  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
73449    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
73450      return 1;
73451    }
73452  }
73453  return 0;
73454}
73455#endif
73456
73457#ifndef SQLITE_OMIT_TRIGGER
73458SQLITE_PRIVATE int sqlite3FixTriggerStep(
73459  DbFixer *pFix,     /* Context of the fixation */
73460  TriggerStep *pStep /* The trigger step be fixed to one database */
73461){
73462  while( pStep ){
73463    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
73464      return 1;
73465    }
73466    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
73467      return 1;
73468    }
73469    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
73470      return 1;
73471    }
73472    pStep = pStep->pNext;
73473  }
73474  return 0;
73475}
73476#endif
73477
73478/************** End of attach.c **********************************************/
73479/************** Begin file auth.c ********************************************/
73480/*
73481** 2003 January 11
73482**
73483** The author disclaims copyright to this source code.  In place of
73484** a legal notice, here is a blessing:
73485**
73486**    May you do good and not evil.
73487**    May you find forgiveness for yourself and forgive others.
73488**    May you share freely, never taking more than you give.
73489**
73490*************************************************************************
73491** This file contains code used to implement the sqlite3_set_authorizer()
73492** API.  This facility is an optional feature of the library.  Embedded
73493** systems that do not need this facility may omit it by recompiling
73494** the library with -DSQLITE_OMIT_AUTHORIZATION=1
73495*/
73496
73497/*
73498** All of the code in this file may be omitted by defining a single
73499** macro.
73500*/
73501#ifndef SQLITE_OMIT_AUTHORIZATION
73502
73503/*
73504** Set or clear the access authorization function.
73505**
73506** The access authorization function is be called during the compilation
73507** phase to verify that the user has read and/or write access permission on
73508** various fields of the database.  The first argument to the auth function
73509** is a copy of the 3rd argument to this routine.  The second argument
73510** to the auth function is one of these constants:
73511**
73512**       SQLITE_CREATE_INDEX
73513**       SQLITE_CREATE_TABLE
73514**       SQLITE_CREATE_TEMP_INDEX
73515**       SQLITE_CREATE_TEMP_TABLE
73516**       SQLITE_CREATE_TEMP_TRIGGER
73517**       SQLITE_CREATE_TEMP_VIEW
73518**       SQLITE_CREATE_TRIGGER
73519**       SQLITE_CREATE_VIEW
73520**       SQLITE_DELETE
73521**       SQLITE_DROP_INDEX
73522**       SQLITE_DROP_TABLE
73523**       SQLITE_DROP_TEMP_INDEX
73524**       SQLITE_DROP_TEMP_TABLE
73525**       SQLITE_DROP_TEMP_TRIGGER
73526**       SQLITE_DROP_TEMP_VIEW
73527**       SQLITE_DROP_TRIGGER
73528**       SQLITE_DROP_VIEW
73529**       SQLITE_INSERT
73530**       SQLITE_PRAGMA
73531**       SQLITE_READ
73532**       SQLITE_SELECT
73533**       SQLITE_TRANSACTION
73534**       SQLITE_UPDATE
73535**
73536** The third and fourth arguments to the auth function are the name of
73537** the table and the column that are being accessed.  The auth function
73538** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
73539** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
73540** means that the SQL statement will never-run - the sqlite3_exec() call
73541** will return with an error.  SQLITE_IGNORE means that the SQL statement
73542** should run but attempts to read the specified column will return NULL
73543** and attempts to write the column will be ignored.
73544**
73545** Setting the auth function to NULL disables this hook.  The default
73546** setting of the auth function is NULL.
73547*/
73548SQLITE_API int sqlite3_set_authorizer(
73549  sqlite3 *db,
73550  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
73551  void *pArg
73552){
73553  sqlite3_mutex_enter(db->mutex);
73554  db->xAuth = xAuth;
73555  db->pAuthArg = pArg;
73556  sqlite3ExpirePreparedStatements(db);
73557  sqlite3_mutex_leave(db->mutex);
73558  return SQLITE_OK;
73559}
73560
73561/*
73562** Write an error message into pParse->zErrMsg that explains that the
73563** user-supplied authorization function returned an illegal value.
73564*/
73565static void sqliteAuthBadReturnCode(Parse *pParse){
73566  sqlite3ErrorMsg(pParse, "authorizer malfunction");
73567  pParse->rc = SQLITE_ERROR;
73568}
73569
73570/*
73571** Invoke the authorization callback for permission to read column zCol from
73572** table zTab in database zDb. This function assumes that an authorization
73573** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
73574**
73575** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
73576** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
73577** is treated as SQLITE_DENY. In this case an error is left in pParse.
73578*/
73579SQLITE_PRIVATE int sqlite3AuthReadCol(
73580  Parse *pParse,                  /* The parser context */
73581  const char *zTab,               /* Table name */
73582  const char *zCol,               /* Column name */
73583  int iDb                         /* Index of containing database. */
73584){
73585  sqlite3 *db = pParse->db;       /* Database handle */
73586  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
73587  int rc;                         /* Auth callback return code */
73588
73589  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
73590  if( rc==SQLITE_DENY ){
73591    if( db->nDb>2 || iDb!=0 ){
73592      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
73593    }else{
73594      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
73595    }
73596    pParse->rc = SQLITE_AUTH;
73597  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
73598    sqliteAuthBadReturnCode(pParse);
73599  }
73600  return rc;
73601}
73602
73603/*
73604** The pExpr should be a TK_COLUMN expression.  The table referred to
73605** is in pTabList or else it is the NEW or OLD table of a trigger.
73606** Check to see if it is OK to read this particular column.
73607**
73608** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
73609** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
73610** then generate an error.
73611*/
73612SQLITE_PRIVATE void sqlite3AuthRead(
73613  Parse *pParse,        /* The parser context */
73614  Expr *pExpr,          /* The expression to check authorization on */
73615  Schema *pSchema,      /* The schema of the expression */
73616  SrcList *pTabList     /* All table that pExpr might refer to */
73617){
73618  sqlite3 *db = pParse->db;
73619  Table *pTab = 0;      /* The table being read */
73620  const char *zCol;     /* Name of the column of the table */
73621  int iSrc;             /* Index in pTabList->a[] of table being read */
73622  int iDb;              /* The index of the database the expression refers to */
73623  int iCol;             /* Index of column in table */
73624
73625  if( db->xAuth==0 ) return;
73626  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
73627  if( iDb<0 ){
73628    /* An attempt to read a column out of a subquery or other
73629    ** temporary table. */
73630    return;
73631  }
73632
73633  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
73634  if( pExpr->op==TK_TRIGGER ){
73635    pTab = pParse->pTriggerTab;
73636  }else{
73637    assert( pTabList );
73638    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
73639      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
73640        pTab = pTabList->a[iSrc].pTab;
73641        break;
73642      }
73643    }
73644  }
73645  iCol = pExpr->iColumn;
73646  if( NEVER(pTab==0) ) return;
73647
73648  if( iCol>=0 ){
73649    assert( iCol<pTab->nCol );
73650    zCol = pTab->aCol[iCol].zName;
73651  }else if( pTab->iPKey>=0 ){
73652    assert( pTab->iPKey<pTab->nCol );
73653    zCol = pTab->aCol[pTab->iPKey].zName;
73654  }else{
73655    zCol = "ROWID";
73656  }
73657  assert( iDb>=0 && iDb<db->nDb );
73658  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
73659    pExpr->op = TK_NULL;
73660  }
73661}
73662
73663/*
73664** Do an authorization check using the code and arguments given.  Return
73665** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
73666** is returned, then the error count and error message in pParse are
73667** modified appropriately.
73668*/
73669SQLITE_PRIVATE int sqlite3AuthCheck(
73670  Parse *pParse,
73671  int code,
73672  const char *zArg1,
73673  const char *zArg2,
73674  const char *zArg3
73675){
73676  sqlite3 *db = pParse->db;
73677  int rc;
73678
73679  /* Don't do any authorization checks if the database is initialising
73680  ** or if the parser is being invoked from within sqlite3_declare_vtab.
73681  */
73682  if( db->init.busy || IN_DECLARE_VTAB ){
73683    return SQLITE_OK;
73684  }
73685
73686  if( db->xAuth==0 ){
73687    return SQLITE_OK;
73688  }
73689  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
73690  if( rc==SQLITE_DENY ){
73691    sqlite3ErrorMsg(pParse, "not authorized");
73692    pParse->rc = SQLITE_AUTH;
73693  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
73694    rc = SQLITE_DENY;
73695    sqliteAuthBadReturnCode(pParse);
73696  }
73697  return rc;
73698}
73699
73700/*
73701** Push an authorization context.  After this routine is called, the
73702** zArg3 argument to authorization callbacks will be zContext until
73703** popped.  Or if pParse==0, this routine is a no-op.
73704*/
73705SQLITE_PRIVATE void sqlite3AuthContextPush(
73706  Parse *pParse,
73707  AuthContext *pContext,
73708  const char *zContext
73709){
73710  assert( pParse );
73711  pContext->pParse = pParse;
73712  pContext->zAuthContext = pParse->zAuthContext;
73713  pParse->zAuthContext = zContext;
73714}
73715
73716/*
73717** Pop an authorization context that was previously pushed
73718** by sqlite3AuthContextPush
73719*/
73720SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
73721  if( pContext->pParse ){
73722    pContext->pParse->zAuthContext = pContext->zAuthContext;
73723    pContext->pParse = 0;
73724  }
73725}
73726
73727#endif /* SQLITE_OMIT_AUTHORIZATION */
73728
73729/************** End of auth.c ************************************************/
73730/************** Begin file build.c *******************************************/
73731/*
73732** 2001 September 15
73733**
73734** The author disclaims copyright to this source code.  In place of
73735** a legal notice, here is a blessing:
73736**
73737**    May you do good and not evil.
73738**    May you find forgiveness for yourself and forgive others.
73739**    May you share freely, never taking more than you give.
73740**
73741*************************************************************************
73742** This file contains C code routines that are called by the SQLite parser
73743** when syntax rules are reduced.  The routines in this file handle the
73744** following kinds of SQL syntax:
73745**
73746**     CREATE TABLE
73747**     DROP TABLE
73748**     CREATE INDEX
73749**     DROP INDEX
73750**     creating ID lists
73751**     BEGIN TRANSACTION
73752**     COMMIT
73753**     ROLLBACK
73754*/
73755
73756/*
73757** This routine is called when a new SQL statement is beginning to
73758** be parsed.  Initialize the pParse structure as needed.
73759*/
73760SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
73761  pParse->explain = (u8)explainFlag;
73762  pParse->nVar = 0;
73763}
73764
73765#ifndef SQLITE_OMIT_SHARED_CACHE
73766/*
73767** The TableLock structure is only used by the sqlite3TableLock() and
73768** codeTableLocks() functions.
73769*/
73770struct TableLock {
73771  int iDb;             /* The database containing the table to be locked */
73772  int iTab;            /* The root page of the table to be locked */
73773  u8 isWriteLock;      /* True for write lock.  False for a read lock */
73774  const char *zName;   /* Name of the table */
73775};
73776
73777/*
73778** Record the fact that we want to lock a table at run-time.
73779**
73780** The table to be locked has root page iTab and is found in database iDb.
73781** A read or a write lock can be taken depending on isWritelock.
73782**
73783** This routine just records the fact that the lock is desired.  The
73784** code to make the lock occur is generated by a later call to
73785** codeTableLocks() which occurs during sqlite3FinishCoding().
73786*/
73787SQLITE_PRIVATE void sqlite3TableLock(
73788  Parse *pParse,     /* Parsing context */
73789  int iDb,           /* Index of the database containing the table to lock */
73790  int iTab,          /* Root page number of the table to be locked */
73791  u8 isWriteLock,    /* True for a write lock */
73792  const char *zName  /* Name of the table to be locked */
73793){
73794  Parse *pToplevel = sqlite3ParseToplevel(pParse);
73795  int i;
73796  int nBytes;
73797  TableLock *p;
73798  assert( iDb>=0 );
73799
73800  for(i=0; i<pToplevel->nTableLock; i++){
73801    p = &pToplevel->aTableLock[i];
73802    if( p->iDb==iDb && p->iTab==iTab ){
73803      p->isWriteLock = (p->isWriteLock || isWriteLock);
73804      return;
73805    }
73806  }
73807
73808  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
73809  pToplevel->aTableLock =
73810      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
73811  if( pToplevel->aTableLock ){
73812    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
73813    p->iDb = iDb;
73814    p->iTab = iTab;
73815    p->isWriteLock = isWriteLock;
73816    p->zName = zName;
73817  }else{
73818    pToplevel->nTableLock = 0;
73819    pToplevel->db->mallocFailed = 1;
73820  }
73821}
73822
73823/*
73824** Code an OP_TableLock instruction for each table locked by the
73825** statement (configured by calls to sqlite3TableLock()).
73826*/
73827static void codeTableLocks(Parse *pParse){
73828  int i;
73829  Vdbe *pVdbe;
73830
73831  pVdbe = sqlite3GetVdbe(pParse);
73832  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
73833
73834  for(i=0; i<pParse->nTableLock; i++){
73835    TableLock *p = &pParse->aTableLock[i];
73836    int p1 = p->iDb;
73837    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
73838                      p->zName, P4_STATIC);
73839  }
73840}
73841#else
73842  #define codeTableLocks(x)
73843#endif
73844
73845/*
73846** This routine is called after a single SQL statement has been
73847** parsed and a VDBE program to execute that statement has been
73848** prepared.  This routine puts the finishing touches on the
73849** VDBE program and resets the pParse structure for the next
73850** parse.
73851**
73852** Note that if an error occurred, it might be the case that
73853** no VDBE code was generated.
73854*/
73855SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
73856  sqlite3 *db;
73857  Vdbe *v;
73858
73859  db = pParse->db;
73860  if( db->mallocFailed ) return;
73861  if( pParse->nested ) return;
73862  if( pParse->nErr ) return;
73863
73864  /* Begin by generating some termination code at the end of the
73865  ** vdbe program
73866  */
73867  v = sqlite3GetVdbe(pParse);
73868  assert( !pParse->isMultiWrite
73869       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
73870  if( v ){
73871    sqlite3VdbeAddOp0(v, OP_Halt);
73872
73873    /* The cookie mask contains one bit for each database file open.
73874    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
73875    ** set for each database that is used.  Generate code to start a
73876    ** transaction on each used database and to verify the schema cookie
73877    ** on each used database.
73878    */
73879    if( pParse->cookieGoto>0 ){
73880      u32 mask;
73881      int iDb;
73882      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
73883      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
73884        if( (mask & pParse->cookieMask)==0 ) continue;
73885        sqlite3VdbeUsesBtree(v, iDb);
73886        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
73887        if( db->init.busy==0 ){
73888          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
73889        }
73890      }
73891#ifndef SQLITE_OMIT_VIRTUALTABLE
73892      {
73893        int i;
73894        for(i=0; i<pParse->nVtabLock; i++){
73895          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
73896          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
73897        }
73898        pParse->nVtabLock = 0;
73899      }
73900#endif
73901
73902      /* Once all the cookies have been verified and transactions opened,
73903      ** obtain the required table-locks. This is a no-op unless the
73904      ** shared-cache feature is enabled.
73905      */
73906      codeTableLocks(pParse);
73907
73908      /* Initialize any AUTOINCREMENT data structures required.
73909      */
73910      sqlite3AutoincrementBegin(pParse);
73911
73912      /* Finally, jump back to the beginning of the executable code. */
73913      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
73914    }
73915  }
73916
73917
73918  /* Get the VDBE program ready for execution
73919  */
73920  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
73921#ifdef SQLITE_DEBUG
73922    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
73923    sqlite3VdbeTrace(v, trace);
73924#endif
73925    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
73926    /* A minimum of one cursor is required if autoincrement is used
73927    *  See ticket [a696379c1f08866] */
73928    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
73929    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
73930                         pParse->nTab, pParse->nMaxArg, pParse->explain,
73931                         pParse->isMultiWrite && pParse->mayAbort);
73932    pParse->rc = SQLITE_DONE;
73933    pParse->colNamesSet = 0;
73934  }else{
73935    pParse->rc = SQLITE_ERROR;
73936  }
73937  pParse->nTab = 0;
73938  pParse->nMem = 0;
73939  pParse->nSet = 0;
73940  pParse->nVar = 0;
73941  pParse->cookieMask = 0;
73942  pParse->cookieGoto = 0;
73943}
73944
73945/*
73946** Run the parser and code generator recursively in order to generate
73947** code for the SQL statement given onto the end of the pParse context
73948** currently under construction.  When the parser is run recursively
73949** this way, the final OP_Halt is not appended and other initialization
73950** and finalization steps are omitted because those are handling by the
73951** outermost parser.
73952**
73953** Not everything is nestable.  This facility is designed to permit
73954** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
73955** care if you decide to try to use this routine for some other purposes.
73956*/
73957SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
73958  va_list ap;
73959  char *zSql;
73960  char *zErrMsg = 0;
73961  sqlite3 *db = pParse->db;
73962# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
73963  char saveBuf[SAVE_SZ];
73964
73965  if( pParse->nErr ) return;
73966  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
73967  va_start(ap, zFormat);
73968  zSql = sqlite3VMPrintf(db, zFormat, ap);
73969  va_end(ap);
73970  if( zSql==0 ){
73971    return;   /* A malloc must have failed */
73972  }
73973  pParse->nested++;
73974  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
73975  memset(&pParse->nVar, 0, SAVE_SZ);
73976  sqlite3RunParser(pParse, zSql, &zErrMsg);
73977  sqlite3DbFree(db, zErrMsg);
73978  sqlite3DbFree(db, zSql);
73979  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
73980  pParse->nested--;
73981}
73982
73983/*
73984** Locate the in-memory structure that describes a particular database
73985** table given the name of that table and (optionally) the name of the
73986** database containing the table.  Return NULL if not found.
73987**
73988** If zDatabase is 0, all databases are searched for the table and the
73989** first matching table is returned.  (No checking for duplicate table
73990** names is done.)  The search order is TEMP first, then MAIN, then any
73991** auxiliary databases added using the ATTACH command.
73992**
73993** See also sqlite3LocateTable().
73994*/
73995SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
73996  Table *p = 0;
73997  int i;
73998  int nName;
73999  assert( zName!=0 );
74000  nName = sqlite3Strlen30(zName);
74001  for(i=OMIT_TEMPDB; i<db->nDb; i++){
74002    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
74003    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
74004    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
74005    if( p ) break;
74006  }
74007  return p;
74008}
74009
74010/*
74011** Locate the in-memory structure that describes a particular database
74012** table given the name of that table and (optionally) the name of the
74013** database containing the table.  Return NULL if not found.  Also leave an
74014** error message in pParse->zErrMsg.
74015**
74016** The difference between this routine and sqlite3FindTable() is that this
74017** routine leaves an error message in pParse->zErrMsg where
74018** sqlite3FindTable() does not.
74019*/
74020SQLITE_PRIVATE Table *sqlite3LocateTable(
74021  Parse *pParse,         /* context in which to report errors */
74022  int isView,            /* True if looking for a VIEW rather than a TABLE */
74023  const char *zName,     /* Name of the table we are looking for */
74024  const char *zDbase     /* Name of the database.  Might be NULL */
74025){
74026  Table *p;
74027
74028  /* Read the database schema. If an error occurs, leave an error message
74029  ** and code in pParse and return NULL. */
74030  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74031    return 0;
74032  }
74033
74034  p = sqlite3FindTable(pParse->db, zName, zDbase);
74035  if( p==0 ){
74036    const char *zMsg = isView ? "no such view" : "no such table";
74037    if( zDbase ){
74038      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
74039    }else{
74040      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
74041    }
74042    pParse->checkSchema = 1;
74043  }
74044  return p;
74045}
74046
74047/*
74048** Locate the in-memory structure that describes
74049** a particular index given the name of that index
74050** and the name of the database that contains the index.
74051** Return NULL if not found.
74052**
74053** If zDatabase is 0, all databases are searched for the
74054** table and the first matching index is returned.  (No checking
74055** for duplicate index names is done.)  The search order is
74056** TEMP first, then MAIN, then any auxiliary databases added
74057** using the ATTACH command.
74058*/
74059SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
74060  Index *p = 0;
74061  int i;
74062  int nName = sqlite3Strlen30(zName);
74063  for(i=OMIT_TEMPDB; i<db->nDb; i++){
74064    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
74065    Schema *pSchema = db->aDb[j].pSchema;
74066    assert( pSchema );
74067    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
74068    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
74069    if( p ) break;
74070  }
74071  return p;
74072}
74073
74074/*
74075** Reclaim the memory used by an index
74076*/
74077static void freeIndex(sqlite3 *db, Index *p){
74078#ifndef SQLITE_OMIT_ANALYZE
74079  sqlite3DeleteIndexSamples(db, p);
74080#endif
74081  sqlite3DbFree(db, p->zColAff);
74082  sqlite3DbFree(db, p);
74083}
74084
74085/*
74086** For the index called zIdxName which is found in the database iDb,
74087** unlike that index from its Table then remove the index from
74088** the index hash table and free all memory structures associated
74089** with the index.
74090*/
74091SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
74092  Index *pIndex;
74093  int len;
74094  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
74095
74096  len = sqlite3Strlen30(zIdxName);
74097  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
74098  if( pIndex ){
74099    if( pIndex->pTable->pIndex==pIndex ){
74100      pIndex->pTable->pIndex = pIndex->pNext;
74101    }else{
74102      Index *p;
74103      /* Justification of ALWAYS();  The index must be on the list of
74104      ** indices. */
74105      p = pIndex->pTable->pIndex;
74106      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
74107      if( ALWAYS(p && p->pNext==pIndex) ){
74108        p->pNext = pIndex->pNext;
74109      }
74110    }
74111    freeIndex(db, pIndex);
74112  }
74113  db->flags |= SQLITE_InternChanges;
74114}
74115
74116/*
74117** Erase all schema information from the in-memory hash tables of
74118** a single database.  This routine is called to reclaim memory
74119** before the database closes.  It is also called during a rollback
74120** if there were schema changes during the transaction or if a
74121** schema-cookie mismatch occurs.
74122**
74123** If iDb==0 then reset the internal schema tables for all database
74124** files.  If iDb>=1 then reset the internal schema for only the
74125** single file indicated.
74126*/
74127SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
74128  int i, j;
74129  assert( iDb>=0 && iDb<db->nDb );
74130
74131  if( iDb==0 ){
74132    sqlite3BtreeEnterAll(db);
74133  }
74134  for(i=iDb; i<db->nDb; i++){
74135    Db *pDb = &db->aDb[i];
74136    if( pDb->pSchema ){
74137      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
74138      sqlite3SchemaFree(pDb->pSchema);
74139    }
74140    if( iDb>0 ) return;
74141  }
74142  assert( iDb==0 );
74143  db->flags &= ~SQLITE_InternChanges;
74144  sqlite3VtabUnlockList(db);
74145  sqlite3BtreeLeaveAll(db);
74146
74147  /* If one or more of the auxiliary database files has been closed,
74148  ** then remove them from the auxiliary database list.  We take the
74149  ** opportunity to do this here since we have just deleted all of the
74150  ** schema hash tables and therefore do not have to make any changes
74151  ** to any of those tables.
74152  */
74153  for(i=j=2; i<db->nDb; i++){
74154    struct Db *pDb = &db->aDb[i];
74155    if( pDb->pBt==0 ){
74156      sqlite3DbFree(db, pDb->zName);
74157      pDb->zName = 0;
74158      continue;
74159    }
74160    if( j<i ){
74161      db->aDb[j] = db->aDb[i];
74162    }
74163    j++;
74164  }
74165  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
74166  db->nDb = j;
74167  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
74168    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
74169    sqlite3DbFree(db, db->aDb);
74170    db->aDb = db->aDbStatic;
74171  }
74172}
74173
74174/*
74175** This routine is called when a commit occurs.
74176*/
74177SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
74178  db->flags &= ~SQLITE_InternChanges;
74179}
74180
74181/*
74182** Delete memory allocated for the column names of a table or view (the
74183** Table.aCol[] array).
74184*/
74185static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
74186  int i;
74187  Column *pCol;
74188  assert( pTable!=0 );
74189  if( (pCol = pTable->aCol)!=0 ){
74190    for(i=0; i<pTable->nCol; i++, pCol++){
74191      sqlite3DbFree(db, pCol->zName);
74192      sqlite3ExprDelete(db, pCol->pDflt);
74193      sqlite3DbFree(db, pCol->zDflt);
74194      sqlite3DbFree(db, pCol->zType);
74195      sqlite3DbFree(db, pCol->zColl);
74196    }
74197    sqlite3DbFree(db, pTable->aCol);
74198  }
74199}
74200
74201/*
74202** Remove the memory data structures associated with the given
74203** Table.  No changes are made to disk by this routine.
74204**
74205** This routine just deletes the data structure.  It does not unlink
74206** the table data structure from the hash table.  But it does destroy
74207** memory structures of the indices and foreign keys associated with
74208** the table.
74209*/
74210SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
74211  Index *pIndex, *pNext;
74212
74213  assert( !pTable || pTable->nRef>0 );
74214
74215  /* Do not delete the table until the reference count reaches zero. */
74216  if( !pTable ) return;
74217  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
74218
74219  /* Delete all indices associated with this table. */
74220  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
74221    pNext = pIndex->pNext;
74222    assert( pIndex->pSchema==pTable->pSchema );
74223    if( !db || db->pnBytesFreed==0 ){
74224      char *zName = pIndex->zName;
74225      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
74226	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
74227      );
74228      assert( pOld==pIndex || pOld==0 );
74229    }
74230    freeIndex(db, pIndex);
74231  }
74232
74233  /* Delete any foreign keys attached to this table. */
74234  sqlite3FkDelete(db, pTable);
74235
74236  /* Delete the Table structure itself.
74237  */
74238  sqliteDeleteColumnNames(db, pTable);
74239  sqlite3DbFree(db, pTable->zName);
74240  sqlite3DbFree(db, pTable->zColAff);
74241  sqlite3SelectDelete(db, pTable->pSelect);
74242#ifndef SQLITE_OMIT_CHECK
74243  sqlite3ExprDelete(db, pTable->pCheck);
74244#endif
74245#ifndef SQLITE_OMIT_VIRTUALTABLE
74246  sqlite3VtabClear(db, pTable);
74247#endif
74248  sqlite3DbFree(db, pTable);
74249}
74250
74251/*
74252** Unlink the given table from the hash tables and the delete the
74253** table structure with all its indices and foreign keys.
74254*/
74255SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
74256  Table *p;
74257  Db *pDb;
74258
74259  assert( db!=0 );
74260  assert( iDb>=0 && iDb<db->nDb );
74261  assert( zTabName );
74262  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
74263  pDb = &db->aDb[iDb];
74264  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
74265                        sqlite3Strlen30(zTabName),0);
74266  sqlite3DeleteTable(db, p);
74267  db->flags |= SQLITE_InternChanges;
74268}
74269
74270/*
74271** Given a token, return a string that consists of the text of that
74272** token.  Space to hold the returned string
74273** is obtained from sqliteMalloc() and must be freed by the calling
74274** function.
74275**
74276** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
74277** surround the body of the token are removed.
74278**
74279** Tokens are often just pointers into the original SQL text and so
74280** are not \000 terminated and are not persistent.  The returned string
74281** is \000 terminated and is persistent.
74282*/
74283SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
74284  char *zName;
74285  if( pName ){
74286    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
74287    sqlite3Dequote(zName);
74288  }else{
74289    zName = 0;
74290  }
74291  return zName;
74292}
74293
74294/*
74295** Open the sqlite_master table stored in database number iDb for
74296** writing. The table is opened using cursor 0.
74297*/
74298SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
74299  Vdbe *v = sqlite3GetVdbe(p);
74300  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
74301  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
74302  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
74303  if( p->nTab==0 ){
74304    p->nTab = 1;
74305  }
74306}
74307
74308/*
74309** Parameter zName points to a nul-terminated buffer containing the name
74310** of a database ("main", "temp" or the name of an attached db). This
74311** function returns the index of the named database in db->aDb[], or
74312** -1 if the named db cannot be found.
74313*/
74314SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
74315  int i = -1;         /* Database number */
74316  if( zName ){
74317    Db *pDb;
74318    int n = sqlite3Strlen30(zName);
74319    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
74320      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
74321          0==sqlite3StrICmp(pDb->zName, zName) ){
74322        break;
74323      }
74324    }
74325  }
74326  return i;
74327}
74328
74329/*
74330** The token *pName contains the name of a database (either "main" or
74331** "temp" or the name of an attached db). This routine returns the
74332** index of the named database in db->aDb[], or -1 if the named db
74333** does not exist.
74334*/
74335SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
74336  int i;                               /* Database number */
74337  char *zName;                         /* Name we are searching for */
74338  zName = sqlite3NameFromToken(db, pName);
74339  i = sqlite3FindDbName(db, zName);
74340  sqlite3DbFree(db, zName);
74341  return i;
74342}
74343
74344/* The table or view or trigger name is passed to this routine via tokens
74345** pName1 and pName2. If the table name was fully qualified, for example:
74346**
74347** CREATE TABLE xxx.yyy (...);
74348**
74349** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
74350** the table name is not fully qualified, i.e.:
74351**
74352** CREATE TABLE yyy(...);
74353**
74354** Then pName1 is set to "yyy" and pName2 is "".
74355**
74356** This routine sets the *ppUnqual pointer to point at the token (pName1 or
74357** pName2) that stores the unqualified table name.  The index of the
74358** database "xxx" is returned.
74359*/
74360SQLITE_PRIVATE int sqlite3TwoPartName(
74361  Parse *pParse,      /* Parsing and code generating context */
74362  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
74363  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
74364  Token **pUnqual     /* Write the unqualified object name here */
74365){
74366  int iDb;                    /* Database holding the object */
74367  sqlite3 *db = pParse->db;
74368
74369  if( ALWAYS(pName2!=0) && pName2->n>0 ){
74370    if( db->init.busy ) {
74371      sqlite3ErrorMsg(pParse, "corrupt database");
74372      pParse->nErr++;
74373      return -1;
74374    }
74375    *pUnqual = pName2;
74376    iDb = sqlite3FindDb(db, pName1);
74377    if( iDb<0 ){
74378      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
74379      pParse->nErr++;
74380      return -1;
74381    }
74382  }else{
74383    assert( db->init.iDb==0 || db->init.busy );
74384    iDb = db->init.iDb;
74385    *pUnqual = pName1;
74386  }
74387  return iDb;
74388}
74389
74390/*
74391** This routine is used to check if the UTF-8 string zName is a legal
74392** unqualified name for a new schema object (table, index, view or
74393** trigger). All names are legal except those that begin with the string
74394** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
74395** is reserved for internal use.
74396*/
74397SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
74398  if( !pParse->db->init.busy && pParse->nested==0
74399          && (pParse->db->flags & SQLITE_WriteSchema)==0
74400          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
74401    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
74402    return SQLITE_ERROR;
74403  }
74404  return SQLITE_OK;
74405}
74406
74407/*
74408** Begin constructing a new table representation in memory.  This is
74409** the first of several action routines that get called in response
74410** to a CREATE TABLE statement.  In particular, this routine is called
74411** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
74412** flag is true if the table should be stored in the auxiliary database
74413** file instead of in the main database file.  This is normally the case
74414** when the "TEMP" or "TEMPORARY" keyword occurs in between
74415** CREATE and TABLE.
74416**
74417** The new table record is initialized and put in pParse->pNewTable.
74418** As more of the CREATE TABLE statement is parsed, additional action
74419** routines will be called to add more information to this record.
74420** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
74421** is called to complete the construction of the new table record.
74422*/
74423SQLITE_PRIVATE void sqlite3StartTable(
74424  Parse *pParse,   /* Parser context */
74425  Token *pName1,   /* First part of the name of the table or view */
74426  Token *pName2,   /* Second part of the name of the table or view */
74427  int isTemp,      /* True if this is a TEMP table */
74428  int isView,      /* True if this is a VIEW */
74429  int isVirtual,   /* True if this is a VIRTUAL table */
74430  int noErr        /* Do nothing if table already exists */
74431){
74432  Table *pTable;
74433  char *zName = 0; /* The name of the new table */
74434  sqlite3 *db = pParse->db;
74435  Vdbe *v;
74436  int iDb;         /* Database number to create the table in */
74437  Token *pName;    /* Unqualified name of the table to create */
74438
74439  /* The table or view name to create is passed to this routine via tokens
74440  ** pName1 and pName2. If the table name was fully qualified, for example:
74441  **
74442  ** CREATE TABLE xxx.yyy (...);
74443  **
74444  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
74445  ** the table name is not fully qualified, i.e.:
74446  **
74447  ** CREATE TABLE yyy(...);
74448  **
74449  ** Then pName1 is set to "yyy" and pName2 is "".
74450  **
74451  ** The call below sets the pName pointer to point at the token (pName1 or
74452  ** pName2) that stores the unqualified table name. The variable iDb is
74453  ** set to the index of the database that the table or view is to be
74454  ** created in.
74455  */
74456  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74457  if( iDb<0 ) return;
74458  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
74459    /* If creating a temp table, the name may not be qualified */
74460    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
74461    return;
74462  }
74463  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
74464
74465  pParse->sNameToken = *pName;
74466  zName = sqlite3NameFromToken(db, pName);
74467  if( zName==0 ) return;
74468  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
74469    goto begin_table_error;
74470  }
74471  if( db->init.iDb==1 ) isTemp = 1;
74472#ifndef SQLITE_OMIT_AUTHORIZATION
74473  assert( (isTemp & 1)==isTemp );
74474  {
74475    int code;
74476    char *zDb = db->aDb[iDb].zName;
74477    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
74478      goto begin_table_error;
74479    }
74480    if( isView ){
74481      if( !OMIT_TEMPDB && isTemp ){
74482        code = SQLITE_CREATE_TEMP_VIEW;
74483      }else{
74484        code = SQLITE_CREATE_VIEW;
74485      }
74486    }else{
74487      if( !OMIT_TEMPDB && isTemp ){
74488        code = SQLITE_CREATE_TEMP_TABLE;
74489      }else{
74490        code = SQLITE_CREATE_TABLE;
74491      }
74492    }
74493    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
74494      goto begin_table_error;
74495    }
74496  }
74497#endif
74498
74499  /* Make sure the new table name does not collide with an existing
74500  ** index or table name in the same database.  Issue an error message if
74501  ** it does. The exception is if the statement being parsed was passed
74502  ** to an sqlite3_declare_vtab() call. In that case only the column names
74503  ** and types will be used, so there is no need to test for namespace
74504  ** collisions.
74505  */
74506  if( !IN_DECLARE_VTAB ){
74507    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74508      goto begin_table_error;
74509    }
74510    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
74511    if( pTable ){
74512      if( !noErr ){
74513        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
74514      }
74515      goto begin_table_error;
74516    }
74517    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
74518      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
74519      goto begin_table_error;
74520    }
74521  }
74522
74523  pTable = sqlite3DbMallocZero(db, sizeof(Table));
74524  if( pTable==0 ){
74525    db->mallocFailed = 1;
74526    pParse->rc = SQLITE_NOMEM;
74527    pParse->nErr++;
74528    goto begin_table_error;
74529  }
74530  pTable->zName = zName;
74531  pTable->iPKey = -1;
74532  pTable->pSchema = db->aDb[iDb].pSchema;
74533  pTable->nRef = 1;
74534  assert( pParse->pNewTable==0 );
74535  pParse->pNewTable = pTable;
74536
74537  /* If this is the magic sqlite_sequence table used by autoincrement,
74538  ** then record a pointer to this table in the main database structure
74539  ** so that INSERT can find the table easily.
74540  */
74541#ifndef SQLITE_OMIT_AUTOINCREMENT
74542  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
74543    pTable->pSchema->pSeqTab = pTable;
74544  }
74545#endif
74546
74547  /* Begin generating the code that will insert the table record into
74548  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
74549  ** and allocate the record number for the table entry now.  Before any
74550  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
74551  ** indices to be created and the table record must come before the
74552  ** indices.  Hence, the record number for the table must be allocated
74553  ** now.
74554  */
74555  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
74556    int j1;
74557    int fileFormat;
74558    int reg1, reg2, reg3;
74559    sqlite3BeginWriteOperation(pParse, 0, iDb);
74560
74561#ifndef SQLITE_OMIT_VIRTUALTABLE
74562    if( isVirtual ){
74563      sqlite3VdbeAddOp0(v, OP_VBegin);
74564    }
74565#endif
74566
74567    /* If the file format and encoding in the database have not been set,
74568    ** set them now.
74569    */
74570    reg1 = pParse->regRowid = ++pParse->nMem;
74571    reg2 = pParse->regRoot = ++pParse->nMem;
74572    reg3 = ++pParse->nMem;
74573    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
74574    sqlite3VdbeUsesBtree(v, iDb);
74575    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
74576    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
74577                  1 : SQLITE_MAX_FILE_FORMAT;
74578    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
74579    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
74580    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
74581    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
74582    sqlite3VdbeJumpHere(v, j1);
74583
74584    /* This just creates a place-holder record in the sqlite_master table.
74585    ** The record created does not contain anything yet.  It will be replaced
74586    ** by the real entry in code generated at sqlite3EndTable().
74587    **
74588    ** The rowid for the new entry is left in register pParse->regRowid.
74589    ** The root page number of the new table is left in reg pParse->regRoot.
74590    ** The rowid and root page number values are needed by the code that
74591    ** sqlite3EndTable will generate.
74592    */
74593#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
74594    if( isView || isVirtual ){
74595      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
74596    }else
74597#endif
74598    {
74599      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
74600    }
74601    sqlite3OpenMasterTable(pParse, iDb);
74602    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
74603    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
74604    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
74605    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74606    sqlite3VdbeAddOp0(v, OP_Close);
74607  }
74608
74609  /* Normal (non-error) return. */
74610  return;
74611
74612  /* If an error occurs, we jump here */
74613begin_table_error:
74614  sqlite3DbFree(db, zName);
74615  return;
74616}
74617
74618/*
74619** This macro is used to compare two strings in a case-insensitive manner.
74620** It is slightly faster than calling sqlite3StrICmp() directly, but
74621** produces larger code.
74622**
74623** WARNING: This macro is not compatible with the strcmp() family. It
74624** returns true if the two strings are equal, otherwise false.
74625*/
74626#define STRICMP(x, y) (\
74627sqlite3UpperToLower[*(unsigned char *)(x)]==   \
74628sqlite3UpperToLower[*(unsigned char *)(y)]     \
74629&& sqlite3StrICmp((x)+1,(y)+1)==0 )
74630
74631/*
74632** Add a new column to the table currently being constructed.
74633**
74634** The parser calls this routine once for each column declaration
74635** in a CREATE TABLE statement.  sqlite3StartTable() gets called
74636** first to get things going.  Then this routine is called for each
74637** column.
74638*/
74639SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
74640  Table *p;
74641  int i;
74642  char *z;
74643  Column *pCol;
74644  sqlite3 *db = pParse->db;
74645  if( (p = pParse->pNewTable)==0 ) return;
74646#if SQLITE_MAX_COLUMN
74647  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74648    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
74649    return;
74650  }
74651#endif
74652  z = sqlite3NameFromToken(db, pName);
74653  if( z==0 ) return;
74654  for(i=0; i<p->nCol; i++){
74655    if( STRICMP(z, p->aCol[i].zName) ){
74656      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
74657      sqlite3DbFree(db, z);
74658      return;
74659    }
74660  }
74661  if( (p->nCol & 0x7)==0 ){
74662    Column *aNew;
74663    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
74664    if( aNew==0 ){
74665      sqlite3DbFree(db, z);
74666      return;
74667    }
74668    p->aCol = aNew;
74669  }
74670  pCol = &p->aCol[p->nCol];
74671  memset(pCol, 0, sizeof(p->aCol[0]));
74672  pCol->zName = z;
74673
74674  /* If there is no type specified, columns have the default affinity
74675  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
74676  ** be called next to set pCol->affinity correctly.
74677  */
74678  pCol->affinity = SQLITE_AFF_NONE;
74679  p->nCol++;
74680}
74681
74682/*
74683** This routine is called by the parser while in the middle of
74684** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
74685** been seen on a column.  This routine sets the notNull flag on
74686** the column currently under construction.
74687*/
74688SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
74689  Table *p;
74690  p = pParse->pNewTable;
74691  if( p==0 || NEVER(p->nCol<1) ) return;
74692  p->aCol[p->nCol-1].notNull = (u8)onError;
74693}
74694
74695/*
74696** Scan the column type name zType (length nType) and return the
74697** associated affinity type.
74698**
74699** This routine does a case-independent search of zType for the
74700** substrings in the following table. If one of the substrings is
74701** found, the corresponding affinity is returned. If zType contains
74702** more than one of the substrings, entries toward the top of
74703** the table take priority. For example, if zType is 'BLOBINT',
74704** SQLITE_AFF_INTEGER is returned.
74705**
74706** Substring     | Affinity
74707** --------------------------------
74708** 'INT'         | SQLITE_AFF_INTEGER
74709** 'CHAR'        | SQLITE_AFF_TEXT
74710** 'CLOB'        | SQLITE_AFF_TEXT
74711** 'TEXT'        | SQLITE_AFF_TEXT
74712** 'BLOB'        | SQLITE_AFF_NONE
74713** 'REAL'        | SQLITE_AFF_REAL
74714** 'FLOA'        | SQLITE_AFF_REAL
74715** 'DOUB'        | SQLITE_AFF_REAL
74716**
74717** If none of the substrings in the above table are found,
74718** SQLITE_AFF_NUMERIC is returned.
74719*/
74720SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
74721  u32 h = 0;
74722  char aff = SQLITE_AFF_NUMERIC;
74723
74724  if( zIn ) while( zIn[0] ){
74725    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
74726    zIn++;
74727    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
74728      aff = SQLITE_AFF_TEXT;
74729    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
74730      aff = SQLITE_AFF_TEXT;
74731    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
74732      aff = SQLITE_AFF_TEXT;
74733    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
74734        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
74735      aff = SQLITE_AFF_NONE;
74736#ifndef SQLITE_OMIT_FLOATING_POINT
74737    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
74738        && aff==SQLITE_AFF_NUMERIC ){
74739      aff = SQLITE_AFF_REAL;
74740    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
74741        && aff==SQLITE_AFF_NUMERIC ){
74742      aff = SQLITE_AFF_REAL;
74743    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
74744        && aff==SQLITE_AFF_NUMERIC ){
74745      aff = SQLITE_AFF_REAL;
74746#endif
74747    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
74748      aff = SQLITE_AFF_INTEGER;
74749      break;
74750    }
74751  }
74752
74753  return aff;
74754}
74755
74756/*
74757** This routine is called by the parser while in the middle of
74758** parsing a CREATE TABLE statement.  The pFirst token is the first
74759** token in the sequence of tokens that describe the type of the
74760** column currently under construction.   pLast is the last token
74761** in the sequence.  Use this information to construct a string
74762** that contains the typename of the column and store that string
74763** in zType.
74764*/
74765SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
74766  Table *p;
74767  Column *pCol;
74768
74769  p = pParse->pNewTable;
74770  if( p==0 || NEVER(p->nCol<1) ) return;
74771  pCol = &p->aCol[p->nCol-1];
74772  assert( pCol->zType==0 );
74773  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
74774  pCol->affinity = sqlite3AffinityType(pCol->zType);
74775}
74776
74777/*
74778** The expression is the default value for the most recently added column
74779** of the table currently under construction.
74780**
74781** Default value expressions must be constant.  Raise an exception if this
74782** is not the case.
74783**
74784** This routine is called by the parser while in the middle of
74785** parsing a CREATE TABLE statement.
74786*/
74787SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
74788  Table *p;
74789  Column *pCol;
74790  sqlite3 *db = pParse->db;
74791  p = pParse->pNewTable;
74792  if( p!=0 ){
74793    pCol = &(p->aCol[p->nCol-1]);
74794    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
74795      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
74796          pCol->zName);
74797    }else{
74798      /* A copy of pExpr is used instead of the original, as pExpr contains
74799      ** tokens that point to volatile memory. The 'span' of the expression
74800      ** is required by pragma table_info.
74801      */
74802      sqlite3ExprDelete(db, pCol->pDflt);
74803      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
74804      sqlite3DbFree(db, pCol->zDflt);
74805      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
74806                                     (int)(pSpan->zEnd - pSpan->zStart));
74807    }
74808  }
74809  sqlite3ExprDelete(db, pSpan->pExpr);
74810}
74811
74812/*
74813** Designate the PRIMARY KEY for the table.  pList is a list of names
74814** of columns that form the primary key.  If pList is NULL, then the
74815** most recently added column of the table is the primary key.
74816**
74817** A table can have at most one primary key.  If the table already has
74818** a primary key (and this is the second primary key) then create an
74819** error.
74820**
74821** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
74822** then we will try to use that column as the rowid.  Set the Table.iPKey
74823** field of the table under construction to be the index of the
74824** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
74825** no INTEGER PRIMARY KEY.
74826**
74827** If the key is not an INTEGER PRIMARY KEY, then create a unique
74828** index for the key.  No index is created for INTEGER PRIMARY KEYs.
74829*/
74830SQLITE_PRIVATE void sqlite3AddPrimaryKey(
74831  Parse *pParse,    /* Parsing context */
74832  ExprList *pList,  /* List of field names to be indexed */
74833  int onError,      /* What to do with a uniqueness conflict */
74834  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
74835  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
74836){
74837  Table *pTab = pParse->pNewTable;
74838  char *zType = 0;
74839  int iCol = -1, i;
74840  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
74841  if( pTab->tabFlags & TF_HasPrimaryKey ){
74842    sqlite3ErrorMsg(pParse,
74843      "table \"%s\" has more than one primary key", pTab->zName);
74844    goto primary_key_exit;
74845  }
74846  pTab->tabFlags |= TF_HasPrimaryKey;
74847  if( pList==0 ){
74848    iCol = pTab->nCol - 1;
74849    pTab->aCol[iCol].isPrimKey = 1;
74850  }else{
74851    for(i=0; i<pList->nExpr; i++){
74852      for(iCol=0; iCol<pTab->nCol; iCol++){
74853        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
74854          break;
74855        }
74856      }
74857      if( iCol<pTab->nCol ){
74858        pTab->aCol[iCol].isPrimKey = 1;
74859      }
74860    }
74861    if( pList->nExpr>1 ) iCol = -1;
74862  }
74863  if( iCol>=0 && iCol<pTab->nCol ){
74864    zType = pTab->aCol[iCol].zType;
74865  }
74866  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
74867        && sortOrder==SQLITE_SO_ASC ){
74868    pTab->iPKey = iCol;
74869    pTab->keyConf = (u8)onError;
74870    assert( autoInc==0 || autoInc==1 );
74871    pTab->tabFlags |= autoInc*TF_Autoincrement;
74872  }else if( autoInc ){
74873#ifndef SQLITE_OMIT_AUTOINCREMENT
74874    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
74875       "INTEGER PRIMARY KEY");
74876#endif
74877  }else{
74878    Index *p;
74879    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
74880    if( p ){
74881      p->autoIndex = 2;
74882    }
74883    pList = 0;
74884  }
74885
74886primary_key_exit:
74887  sqlite3ExprListDelete(pParse->db, pList);
74888  return;
74889}
74890
74891/*
74892** Add a new CHECK constraint to the table currently under construction.
74893*/
74894SQLITE_PRIVATE void sqlite3AddCheckConstraint(
74895  Parse *pParse,    /* Parsing context */
74896  Expr *pCheckExpr  /* The check expression */
74897){
74898  sqlite3 *db = pParse->db;
74899#ifndef SQLITE_OMIT_CHECK
74900  Table *pTab = pParse->pNewTable;
74901  if( pTab && !IN_DECLARE_VTAB ){
74902    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
74903  }else
74904#endif
74905  {
74906    sqlite3ExprDelete(db, pCheckExpr);
74907  }
74908}
74909
74910/*
74911** Set the collation function of the most recently parsed table column
74912** to the CollSeq given.
74913*/
74914SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
74915  Table *p;
74916  int i;
74917  char *zColl;              /* Dequoted name of collation sequence */
74918  sqlite3 *db;
74919
74920  if( (p = pParse->pNewTable)==0 ) return;
74921  i = p->nCol-1;
74922  db = pParse->db;
74923  zColl = sqlite3NameFromToken(db, pToken);
74924  if( !zColl ) return;
74925
74926  if( sqlite3LocateCollSeq(pParse, zColl) ){
74927    Index *pIdx;
74928    p->aCol[i].zColl = zColl;
74929
74930    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
74931    ** then an index may have been created on this column before the
74932    ** collation type was added. Correct this if it is the case.
74933    */
74934    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
74935      assert( pIdx->nColumn==1 );
74936      if( pIdx->aiColumn[0]==i ){
74937        pIdx->azColl[0] = p->aCol[i].zColl;
74938      }
74939    }
74940  }else{
74941    sqlite3DbFree(db, zColl);
74942  }
74943}
74944
74945/*
74946** This function returns the collation sequence for database native text
74947** encoding identified by the string zName, length nName.
74948**
74949** If the requested collation sequence is not available, or not available
74950** in the database native encoding, the collation factory is invoked to
74951** request it. If the collation factory does not supply such a sequence,
74952** and the sequence is available in another text encoding, then that is
74953** returned instead.
74954**
74955** If no versions of the requested collations sequence are available, or
74956** another error occurs, NULL is returned and an error message written into
74957** pParse.
74958**
74959** This routine is a wrapper around sqlite3FindCollSeq().  This routine
74960** invokes the collation factory if the named collation cannot be found
74961** and generates an error message.
74962**
74963** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
74964*/
74965SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
74966  sqlite3 *db = pParse->db;
74967  u8 enc = ENC(db);
74968  u8 initbusy = db->init.busy;
74969  CollSeq *pColl;
74970
74971  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
74972  if( !initbusy && (!pColl || !pColl->xCmp) ){
74973    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
74974    if( !pColl ){
74975      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
74976    }
74977  }
74978
74979  return pColl;
74980}
74981
74982
74983/*
74984** Generate code that will increment the schema cookie.
74985**
74986** The schema cookie is used to determine when the schema for the
74987** database changes.  After each schema change, the cookie value
74988** changes.  When a process first reads the schema it records the
74989** cookie.  Thereafter, whenever it goes to access the database,
74990** it checks the cookie to make sure the schema has not changed
74991** since it was last read.
74992**
74993** This plan is not completely bullet-proof.  It is possible for
74994** the schema to change multiple times and for the cookie to be
74995** set back to prior value.  But schema changes are infrequent
74996** and the probability of hitting the same cookie value is only
74997** 1 chance in 2^32.  So we're safe enough.
74998*/
74999SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
75000  int r1 = sqlite3GetTempReg(pParse);
75001  sqlite3 *db = pParse->db;
75002  Vdbe *v = pParse->pVdbe;
75003  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
75004  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
75005  sqlite3ReleaseTempReg(pParse, r1);
75006}
75007
75008/*
75009** Measure the number of characters needed to output the given
75010** identifier.  The number returned includes any quotes used
75011** but does not include the null terminator.
75012**
75013** The estimate is conservative.  It might be larger that what is
75014** really needed.
75015*/
75016static int identLength(const char *z){
75017  int n;
75018  for(n=0; *z; n++, z++){
75019    if( *z=='"' ){ n++; }
75020  }
75021  return n + 2;
75022}
75023
75024/*
75025** The first parameter is a pointer to an output buffer. The second
75026** parameter is a pointer to an integer that contains the offset at
75027** which to write into the output buffer. This function copies the
75028** nul-terminated string pointed to by the third parameter, zSignedIdent,
75029** to the specified offset in the buffer and updates *pIdx to refer
75030** to the first byte after the last byte written before returning.
75031**
75032** If the string zSignedIdent consists entirely of alpha-numeric
75033** characters, does not begin with a digit and is not an SQL keyword,
75034** then it is copied to the output buffer exactly as it is. Otherwise,
75035** it is quoted using double-quotes.
75036*/
75037static void identPut(char *z, int *pIdx, char *zSignedIdent){
75038  unsigned char *zIdent = (unsigned char*)zSignedIdent;
75039  int i, j, needQuote;
75040  i = *pIdx;
75041
75042  for(j=0; zIdent[j]; j++){
75043    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
75044  }
75045  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
75046  if( !needQuote ){
75047    needQuote = zIdent[j];
75048  }
75049
75050  if( needQuote ) z[i++] = '"';
75051  for(j=0; zIdent[j]; j++){
75052    z[i++] = zIdent[j];
75053    if( zIdent[j]=='"' ) z[i++] = '"';
75054  }
75055  if( needQuote ) z[i++] = '"';
75056  z[i] = 0;
75057  *pIdx = i;
75058}
75059
75060/*
75061** Generate a CREATE TABLE statement appropriate for the given
75062** table.  Memory to hold the text of the statement is obtained
75063** from sqliteMalloc() and must be freed by the calling function.
75064*/
75065static char *createTableStmt(sqlite3 *db, Table *p){
75066  int i, k, n;
75067  char *zStmt;
75068  char *zSep, *zSep2, *zEnd;
75069  Column *pCol;
75070  n = 0;
75071  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
75072    n += identLength(pCol->zName) + 5;
75073  }
75074  n += identLength(p->zName);
75075  if( n<50 ){
75076    zSep = "";
75077    zSep2 = ",";
75078    zEnd = ")";
75079  }else{
75080    zSep = "\n  ";
75081    zSep2 = ",\n  ";
75082    zEnd = "\n)";
75083  }
75084  n += 35 + 6*p->nCol;
75085  zStmt = sqlite3DbMallocRaw(0, n);
75086  if( zStmt==0 ){
75087    db->mallocFailed = 1;
75088    return 0;
75089  }
75090  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
75091  k = sqlite3Strlen30(zStmt);
75092  identPut(zStmt, &k, p->zName);
75093  zStmt[k++] = '(';
75094  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
75095    static const char * const azType[] = {
75096        /* SQLITE_AFF_TEXT    */ " TEXT",
75097        /* SQLITE_AFF_NONE    */ "",
75098        /* SQLITE_AFF_NUMERIC */ " NUM",
75099        /* SQLITE_AFF_INTEGER */ " INT",
75100        /* SQLITE_AFF_REAL    */ " REAL"
75101    };
75102    int len;
75103    const char *zType;
75104
75105    sqlite3_snprintf(n-k, &zStmt[k], zSep);
75106    k += sqlite3Strlen30(&zStmt[k]);
75107    zSep = zSep2;
75108    identPut(zStmt, &k, pCol->zName);
75109    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
75110    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
75111    testcase( pCol->affinity==SQLITE_AFF_TEXT );
75112    testcase( pCol->affinity==SQLITE_AFF_NONE );
75113    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
75114    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
75115    testcase( pCol->affinity==SQLITE_AFF_REAL );
75116
75117    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
75118    len = sqlite3Strlen30(zType);
75119    assert( pCol->affinity==SQLITE_AFF_NONE
75120            || pCol->affinity==sqlite3AffinityType(zType) );
75121    memcpy(&zStmt[k], zType, len);
75122    k += len;
75123    assert( k<=n );
75124  }
75125  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
75126  return zStmt;
75127}
75128
75129/*
75130** This routine is called to report the final ")" that terminates
75131** a CREATE TABLE statement.
75132**
75133** The table structure that other action routines have been building
75134** is added to the internal hash tables, assuming no errors have
75135** occurred.
75136**
75137** An entry for the table is made in the master table on disk, unless
75138** this is a temporary table or db->init.busy==1.  When db->init.busy==1
75139** it means we are reading the sqlite_master table because we just
75140** connected to the database or because the sqlite_master table has
75141** recently changed, so the entry for this table already exists in
75142** the sqlite_master table.  We do not want to create it again.
75143**
75144** If the pSelect argument is not NULL, it means that this routine
75145** was called to create a table generated from a
75146** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
75147** the new table will match the result set of the SELECT.
75148*/
75149SQLITE_PRIVATE void sqlite3EndTable(
75150  Parse *pParse,          /* Parse context */
75151  Token *pCons,           /* The ',' token after the last column defn. */
75152  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
75153  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
75154){
75155  Table *p;
75156  sqlite3 *db = pParse->db;
75157  int iDb;
75158
75159  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
75160    return;
75161  }
75162  p = pParse->pNewTable;
75163  if( p==0 ) return;
75164
75165  assert( !db->init.busy || !pSelect );
75166
75167  iDb = sqlite3SchemaToIndex(db, p->pSchema);
75168
75169#ifndef SQLITE_OMIT_CHECK
75170  /* Resolve names in all CHECK constraint expressions.
75171  */
75172  if( p->pCheck ){
75173    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
75174    NameContext sNC;                /* Name context for pParse->pNewTable */
75175
75176    memset(&sNC, 0, sizeof(sNC));
75177    memset(&sSrc, 0, sizeof(sSrc));
75178    sSrc.nSrc = 1;
75179    sSrc.a[0].zName = p->zName;
75180    sSrc.a[0].pTab = p;
75181    sSrc.a[0].iCursor = -1;
75182    sNC.pParse = pParse;
75183    sNC.pSrcList = &sSrc;
75184    sNC.isCheck = 1;
75185    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
75186      return;
75187    }
75188  }
75189#endif /* !defined(SQLITE_OMIT_CHECK) */
75190
75191  /* If the db->init.busy is 1 it means we are reading the SQL off the
75192  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
75193  ** So do not write to the disk again.  Extract the root page number
75194  ** for the table from the db->init.newTnum field.  (The page number
75195  ** should have been put there by the sqliteOpenCb routine.)
75196  */
75197  if( db->init.busy ){
75198    p->tnum = db->init.newTnum;
75199  }
75200
75201  /* If not initializing, then create a record for the new table
75202  ** in the SQLITE_MASTER table of the database.
75203  **
75204  ** If this is a TEMPORARY table, write the entry into the auxiliary
75205  ** file instead of into the main database file.
75206  */
75207  if( !db->init.busy ){
75208    int n;
75209    Vdbe *v;
75210    char *zType;    /* "view" or "table" */
75211    char *zType2;   /* "VIEW" or "TABLE" */
75212    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
75213
75214    v = sqlite3GetVdbe(pParse);
75215    if( NEVER(v==0) ) return;
75216
75217    sqlite3VdbeAddOp1(v, OP_Close, 0);
75218
75219    /*
75220    ** Initialize zType for the new view or table.
75221    */
75222    if( p->pSelect==0 ){
75223      /* A regular table */
75224      zType = "table";
75225      zType2 = "TABLE";
75226#ifndef SQLITE_OMIT_VIEW
75227    }else{
75228      /* A view */
75229      zType = "view";
75230      zType2 = "VIEW";
75231#endif
75232    }
75233
75234    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
75235    ** statement to populate the new table. The root-page number for the
75236    ** new table is in register pParse->regRoot.
75237    **
75238    ** Once the SELECT has been coded by sqlite3Select(), it is in a
75239    ** suitable state to query for the column names and types to be used
75240    ** by the new table.
75241    **
75242    ** A shared-cache write-lock is not required to write to the new table,
75243    ** as a schema-lock must have already been obtained to create it. Since
75244    ** a schema-lock excludes all other database users, the write-lock would
75245    ** be redundant.
75246    */
75247    if( pSelect ){
75248      SelectDest dest;
75249      Table *pSelTab;
75250
75251      assert(pParse->nTab==1);
75252      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
75253      sqlite3VdbeChangeP5(v, 1);
75254      pParse->nTab = 2;
75255      sqlite3SelectDestInit(&dest, SRT_Table, 1);
75256      sqlite3Select(pParse, pSelect, &dest);
75257      sqlite3VdbeAddOp1(v, OP_Close, 1);
75258      if( pParse->nErr==0 ){
75259        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
75260        if( pSelTab==0 ) return;
75261        assert( p->aCol==0 );
75262        p->nCol = pSelTab->nCol;
75263        p->aCol = pSelTab->aCol;
75264        pSelTab->nCol = 0;
75265        pSelTab->aCol = 0;
75266        sqlite3DeleteTable(db, pSelTab);
75267      }
75268    }
75269
75270    /* Compute the complete text of the CREATE statement */
75271    if( pSelect ){
75272      zStmt = createTableStmt(db, p);
75273    }else{
75274      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
75275      zStmt = sqlite3MPrintf(db,
75276          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
75277      );
75278    }
75279
75280    /* A slot for the record has already been allocated in the
75281    ** SQLITE_MASTER table.  We just need to update that slot with all
75282    ** the information we've collected.
75283    */
75284    sqlite3NestedParse(pParse,
75285      "UPDATE %Q.%s "
75286         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
75287       "WHERE rowid=#%d",
75288      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
75289      zType,
75290      p->zName,
75291      p->zName,
75292      pParse->regRoot,
75293      zStmt,
75294      pParse->regRowid
75295    );
75296    sqlite3DbFree(db, zStmt);
75297    sqlite3ChangeCookie(pParse, iDb);
75298
75299#ifndef SQLITE_OMIT_AUTOINCREMENT
75300    /* Check to see if we need to create an sqlite_sequence table for
75301    ** keeping track of autoincrement keys.
75302    */
75303    if( p->tabFlags & TF_Autoincrement ){
75304      Db *pDb = &db->aDb[iDb];
75305      if( pDb->pSchema->pSeqTab==0 ){
75306        sqlite3NestedParse(pParse,
75307          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
75308          pDb->zName
75309        );
75310      }
75311    }
75312#endif
75313
75314    /* Reparse everything to update our internal data structures */
75315    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
75316        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
75317  }
75318
75319
75320  /* Add the table to the in-memory representation of the database.
75321  */
75322  if( db->init.busy ){
75323    Table *pOld;
75324    Schema *pSchema = p->pSchema;
75325    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
75326                             sqlite3Strlen30(p->zName),p);
75327    if( pOld ){
75328      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
75329      db->mallocFailed = 1;
75330      return;
75331    }
75332    pParse->pNewTable = 0;
75333    db->nTable++;
75334    db->flags |= SQLITE_InternChanges;
75335
75336#ifndef SQLITE_OMIT_ALTERTABLE
75337    if( !p->pSelect ){
75338      const char *zName = (const char *)pParse->sNameToken.z;
75339      int nName;
75340      assert( !pSelect && pCons && pEnd );
75341      if( pCons->z==0 ){
75342        pCons = pEnd;
75343      }
75344      nName = (int)((const char *)pCons->z - zName);
75345      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
75346    }
75347#endif
75348  }
75349}
75350
75351#ifndef SQLITE_OMIT_VIEW
75352/*
75353** The parser calls this routine in order to create a new VIEW
75354*/
75355SQLITE_PRIVATE void sqlite3CreateView(
75356  Parse *pParse,     /* The parsing context */
75357  Token *pBegin,     /* The CREATE token that begins the statement */
75358  Token *pName1,     /* The token that holds the name of the view */
75359  Token *pName2,     /* The token that holds the name of the view */
75360  Select *pSelect,   /* A SELECT statement that will become the new view */
75361  int isTemp,        /* TRUE for a TEMPORARY view */
75362  int noErr          /* Suppress error messages if VIEW already exists */
75363){
75364  Table *p;
75365  int n;
75366  const char *z;
75367  Token sEnd;
75368  DbFixer sFix;
75369  Token *pName;
75370  int iDb;
75371  sqlite3 *db = pParse->db;
75372
75373  if( pParse->nVar>0 ){
75374    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
75375    sqlite3SelectDelete(db, pSelect);
75376    return;
75377  }
75378  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
75379  p = pParse->pNewTable;
75380  if( p==0 ){
75381    sqlite3SelectDelete(db, pSelect);
75382    return;
75383  }
75384  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
75385                             ** there could not have been an error */
75386  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75387  iDb = sqlite3SchemaToIndex(db, p->pSchema);
75388  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
75389    && sqlite3FixSelect(&sFix, pSelect)
75390  ){
75391    sqlite3SelectDelete(db, pSelect);
75392    return;
75393  }
75394
75395  /* Make a copy of the entire SELECT statement that defines the view.
75396  ** This will force all the Expr.token.z values to be dynamically
75397  ** allocated rather than point to the input string - which means that
75398  ** they will persist after the current sqlite3_exec() call returns.
75399  */
75400  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
75401  sqlite3SelectDelete(db, pSelect);
75402  if( db->mallocFailed ){
75403    return;
75404  }
75405  if( !db->init.busy ){
75406    sqlite3ViewGetColumnNames(pParse, p);
75407  }
75408
75409  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
75410  ** the end.
75411  */
75412  sEnd = pParse->sLastToken;
75413  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
75414    sEnd.z += sEnd.n;
75415  }
75416  sEnd.n = 0;
75417  n = (int)(sEnd.z - pBegin->z);
75418  z = pBegin->z;
75419  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
75420  sEnd.z = &z[n-1];
75421  sEnd.n = 1;
75422
75423  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
75424  sqlite3EndTable(pParse, 0, &sEnd, 0);
75425  return;
75426}
75427#endif /* SQLITE_OMIT_VIEW */
75428
75429#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
75430/*
75431** The Table structure pTable is really a VIEW.  Fill in the names of
75432** the columns of the view in the pTable structure.  Return the number
75433** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
75434*/
75435SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
75436  Table *pSelTab;   /* A fake table from which we get the result set */
75437  Select *pSel;     /* Copy of the SELECT that implements the view */
75438  int nErr = 0;     /* Number of errors encountered */
75439  int n;            /* Temporarily holds the number of cursors assigned */
75440  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
75441  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
75442
75443  assert( pTable );
75444
75445#ifndef SQLITE_OMIT_VIRTUALTABLE
75446  if( sqlite3VtabCallConnect(pParse, pTable) ){
75447    return SQLITE_ERROR;
75448  }
75449  if( IsVirtual(pTable) ) return 0;
75450#endif
75451
75452#ifndef SQLITE_OMIT_VIEW
75453  /* A positive nCol means the columns names for this view are
75454  ** already known.
75455  */
75456  if( pTable->nCol>0 ) return 0;
75457
75458  /* A negative nCol is a special marker meaning that we are currently
75459  ** trying to compute the column names.  If we enter this routine with
75460  ** a negative nCol, it means two or more views form a loop, like this:
75461  **
75462  **     CREATE VIEW one AS SELECT * FROM two;
75463  **     CREATE VIEW two AS SELECT * FROM one;
75464  **
75465  ** Actually, the error above is now caught prior to reaching this point.
75466  ** But the following test is still important as it does come up
75467  ** in the following:
75468  **
75469  **     CREATE TABLE main.ex1(a);
75470  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
75471  **     SELECT * FROM temp.ex1;
75472  */
75473  if( pTable->nCol<0 ){
75474    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
75475    return 1;
75476  }
75477  assert( pTable->nCol>=0 );
75478
75479  /* If we get this far, it means we need to compute the table names.
75480  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
75481  ** "*" elements in the results set of the view and will assign cursors
75482  ** to the elements of the FROM clause.  But we do not want these changes
75483  ** to be permanent.  So the computation is done on a copy of the SELECT
75484  ** statement that defines the view.
75485  */
75486  assert( pTable->pSelect );
75487  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
75488  if( pSel ){
75489    u8 enableLookaside = db->lookaside.bEnabled;
75490    n = pParse->nTab;
75491    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
75492    pTable->nCol = -1;
75493    db->lookaside.bEnabled = 0;
75494#ifndef SQLITE_OMIT_AUTHORIZATION
75495    xAuth = db->xAuth;
75496    db->xAuth = 0;
75497    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
75498    db->xAuth = xAuth;
75499#else
75500    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
75501#endif
75502    db->lookaside.bEnabled = enableLookaside;
75503    pParse->nTab = n;
75504    if( pSelTab ){
75505      assert( pTable->aCol==0 );
75506      pTable->nCol = pSelTab->nCol;
75507      pTable->aCol = pSelTab->aCol;
75508      pSelTab->nCol = 0;
75509      pSelTab->aCol = 0;
75510      sqlite3DeleteTable(db, pSelTab);
75511      pTable->pSchema->flags |= DB_UnresetViews;
75512    }else{
75513      pTable->nCol = 0;
75514      nErr++;
75515    }
75516    sqlite3SelectDelete(db, pSel);
75517  } else {
75518    nErr++;
75519  }
75520#endif /* SQLITE_OMIT_VIEW */
75521  return nErr;
75522}
75523#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
75524
75525#ifndef SQLITE_OMIT_VIEW
75526/*
75527** Clear the column names from every VIEW in database idx.
75528*/
75529static void sqliteViewResetAll(sqlite3 *db, int idx){
75530  HashElem *i;
75531  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
75532  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
75533    Table *pTab = sqliteHashData(i);
75534    if( pTab->pSelect ){
75535      sqliteDeleteColumnNames(db, pTab);
75536      pTab->aCol = 0;
75537      pTab->nCol = 0;
75538    }
75539  }
75540  DbClearProperty(db, idx, DB_UnresetViews);
75541}
75542#else
75543# define sqliteViewResetAll(A,B)
75544#endif /* SQLITE_OMIT_VIEW */
75545
75546/*
75547** This function is called by the VDBE to adjust the internal schema
75548** used by SQLite when the btree layer moves a table root page. The
75549** root-page of a table or index in database iDb has changed from iFrom
75550** to iTo.
75551**
75552** Ticket #1728:  The symbol table might still contain information
75553** on tables and/or indices that are the process of being deleted.
75554** If you are unlucky, one of those deleted indices or tables might
75555** have the same rootpage number as the real table or index that is
75556** being moved.  So we cannot stop searching after the first match
75557** because the first match might be for one of the deleted indices
75558** or tables and not the table/index that is actually being moved.
75559** We must continue looping until all tables and indices with
75560** rootpage==iFrom have been converted to have a rootpage of iTo
75561** in order to be certain that we got the right one.
75562*/
75563#ifndef SQLITE_OMIT_AUTOVACUUM
75564SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
75565  HashElem *pElem;
75566  Hash *pHash;
75567
75568  pHash = &pDb->pSchema->tblHash;
75569  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
75570    Table *pTab = sqliteHashData(pElem);
75571    if( pTab->tnum==iFrom ){
75572      pTab->tnum = iTo;
75573    }
75574  }
75575  pHash = &pDb->pSchema->idxHash;
75576  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
75577    Index *pIdx = sqliteHashData(pElem);
75578    if( pIdx->tnum==iFrom ){
75579      pIdx->tnum = iTo;
75580    }
75581  }
75582}
75583#endif
75584
75585/*
75586** Write code to erase the table with root-page iTable from database iDb.
75587** Also write code to modify the sqlite_master table and internal schema
75588** if a root-page of another table is moved by the btree-layer whilst
75589** erasing iTable (this can happen with an auto-vacuum database).
75590*/
75591static void destroyRootPage(Parse *pParse, int iTable, int iDb){
75592  Vdbe *v = sqlite3GetVdbe(pParse);
75593  int r1 = sqlite3GetTempReg(pParse);
75594  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
75595  sqlite3MayAbort(pParse);
75596#ifndef SQLITE_OMIT_AUTOVACUUM
75597  /* OP_Destroy stores an in integer r1. If this integer
75598  ** is non-zero, then it is the root page number of a table moved to
75599  ** location iTable. The following code modifies the sqlite_master table to
75600  ** reflect this.
75601  **
75602  ** The "#NNN" in the SQL is a special constant that means whatever value
75603  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
75604  ** token for additional information.
75605  */
75606  sqlite3NestedParse(pParse,
75607     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
75608     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
75609#endif
75610  sqlite3ReleaseTempReg(pParse, r1);
75611}
75612
75613/*
75614** Write VDBE code to erase table pTab and all associated indices on disk.
75615** Code to update the sqlite_master tables and internal schema definitions
75616** in case a root-page belonging to another table is moved by the btree layer
75617** is also added (this can happen with an auto-vacuum database).
75618*/
75619static void destroyTable(Parse *pParse, Table *pTab){
75620#ifdef SQLITE_OMIT_AUTOVACUUM
75621  Index *pIdx;
75622  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75623  destroyRootPage(pParse, pTab->tnum, iDb);
75624  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75625    destroyRootPage(pParse, pIdx->tnum, iDb);
75626  }
75627#else
75628  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
75629  ** is not defined), then it is important to call OP_Destroy on the
75630  ** table and index root-pages in order, starting with the numerically
75631  ** largest root-page number. This guarantees that none of the root-pages
75632  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
75633  ** following were coded:
75634  **
75635  ** OP_Destroy 4 0
75636  ** ...
75637  ** OP_Destroy 5 0
75638  **
75639  ** and root page 5 happened to be the largest root-page number in the
75640  ** database, then root page 5 would be moved to page 4 by the
75641  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
75642  ** a free-list page.
75643  */
75644  int iTab = pTab->tnum;
75645  int iDestroyed = 0;
75646
75647  while( 1 ){
75648    Index *pIdx;
75649    int iLargest = 0;
75650
75651    if( iDestroyed==0 || iTab<iDestroyed ){
75652      iLargest = iTab;
75653    }
75654    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75655      int iIdx = pIdx->tnum;
75656      assert( pIdx->pSchema==pTab->pSchema );
75657      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
75658        iLargest = iIdx;
75659      }
75660    }
75661    if( iLargest==0 ){
75662      return;
75663    }else{
75664      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75665      destroyRootPage(pParse, iLargest, iDb);
75666      iDestroyed = iLargest;
75667    }
75668  }
75669#endif
75670}
75671
75672/*
75673** This routine is called to do the work of a DROP TABLE statement.
75674** pName is the name of the table to be dropped.
75675*/
75676SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
75677  Table *pTab;
75678  Vdbe *v;
75679  sqlite3 *db = pParse->db;
75680  int iDb;
75681
75682  if( db->mallocFailed ){
75683    goto exit_drop_table;
75684  }
75685  assert( pParse->nErr==0 );
75686  assert( pName->nSrc==1 );
75687  if( noErr ) db->suppressErr++;
75688  pTab = sqlite3LocateTable(pParse, isView,
75689                            pName->a[0].zName, pName->a[0].zDatabase);
75690  if( noErr ) db->suppressErr--;
75691
75692  if( pTab==0 ){
75693    goto exit_drop_table;
75694  }
75695  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75696  assert( iDb>=0 && iDb<db->nDb );
75697
75698  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
75699  ** it is initialized.
75700  */
75701  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
75702    goto exit_drop_table;
75703  }
75704#ifndef SQLITE_OMIT_AUTHORIZATION
75705  {
75706    int code;
75707    const char *zTab = SCHEMA_TABLE(iDb);
75708    const char *zDb = db->aDb[iDb].zName;
75709    const char *zArg2 = 0;
75710    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
75711      goto exit_drop_table;
75712    }
75713    if( isView ){
75714      if( !OMIT_TEMPDB && iDb==1 ){
75715        code = SQLITE_DROP_TEMP_VIEW;
75716      }else{
75717        code = SQLITE_DROP_VIEW;
75718      }
75719#ifndef SQLITE_OMIT_VIRTUALTABLE
75720    }else if( IsVirtual(pTab) ){
75721      code = SQLITE_DROP_VTABLE;
75722      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
75723#endif
75724    }else{
75725      if( !OMIT_TEMPDB && iDb==1 ){
75726        code = SQLITE_DROP_TEMP_TABLE;
75727      }else{
75728        code = SQLITE_DROP_TABLE;
75729      }
75730    }
75731    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
75732      goto exit_drop_table;
75733    }
75734    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
75735      goto exit_drop_table;
75736    }
75737  }
75738#endif
75739  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
75740    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
75741    goto exit_drop_table;
75742  }
75743
75744#ifndef SQLITE_OMIT_VIEW
75745  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
75746  ** on a table.
75747  */
75748  if( isView && pTab->pSelect==0 ){
75749    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
75750    goto exit_drop_table;
75751  }
75752  if( !isView && pTab->pSelect ){
75753    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
75754    goto exit_drop_table;
75755  }
75756#endif
75757
75758  /* Generate code to remove the table from the master table
75759  ** on disk.
75760  */
75761  v = sqlite3GetVdbe(pParse);
75762  if( v ){
75763    Trigger *pTrigger;
75764    Db *pDb = &db->aDb[iDb];
75765    sqlite3BeginWriteOperation(pParse, 1, iDb);
75766
75767#ifndef SQLITE_OMIT_VIRTUALTABLE
75768    if( IsVirtual(pTab) ){
75769      sqlite3VdbeAddOp0(v, OP_VBegin);
75770    }
75771#endif
75772    sqlite3FkDropTable(pParse, pName, pTab);
75773
75774    /* Drop all triggers associated with the table being dropped. Code
75775    ** is generated to remove entries from sqlite_master and/or
75776    ** sqlite_temp_master if required.
75777    */
75778    pTrigger = sqlite3TriggerList(pParse, pTab);
75779    while( pTrigger ){
75780      assert( pTrigger->pSchema==pTab->pSchema ||
75781          pTrigger->pSchema==db->aDb[1].pSchema );
75782      sqlite3DropTriggerPtr(pParse, pTrigger);
75783      pTrigger = pTrigger->pNext;
75784    }
75785
75786#ifndef SQLITE_OMIT_AUTOINCREMENT
75787    /* Remove any entries of the sqlite_sequence table associated with
75788    ** the table being dropped. This is done before the table is dropped
75789    ** at the btree level, in case the sqlite_sequence table needs to
75790    ** move as a result of the drop (can happen in auto-vacuum mode).
75791    */
75792    if( pTab->tabFlags & TF_Autoincrement ){
75793      sqlite3NestedParse(pParse,
75794        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
75795        pDb->zName, pTab->zName
75796      );
75797    }
75798#endif
75799
75800    /* Drop all SQLITE_MASTER table and index entries that refer to the
75801    ** table. The program name loops through the master table and deletes
75802    ** every row that refers to a table of the same name as the one being
75803    ** dropped. Triggers are handled seperately because a trigger can be
75804    ** created in the temp database that refers to a table in another
75805    ** database.
75806    */
75807    sqlite3NestedParse(pParse,
75808        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
75809        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
75810
75811    /* Drop any statistics from the sqlite_stat1 table, if it exists */
75812    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
75813      sqlite3NestedParse(pParse,
75814        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
75815      );
75816    }
75817
75818    if( !isView && !IsVirtual(pTab) ){
75819      destroyTable(pParse, pTab);
75820    }
75821
75822    /* Remove the table entry from SQLite's internal schema and modify
75823    ** the schema cookie.
75824    */
75825    if( IsVirtual(pTab) ){
75826      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
75827    }
75828    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
75829    sqlite3ChangeCookie(pParse, iDb);
75830  }
75831  sqliteViewResetAll(db, iDb);
75832
75833exit_drop_table:
75834  sqlite3SrcListDelete(db, pName);
75835}
75836
75837/*
75838** This routine is called to create a new foreign key on the table
75839** currently under construction.  pFromCol determines which columns
75840** in the current table point to the foreign key.  If pFromCol==0 then
75841** connect the key to the last column inserted.  pTo is the name of
75842** the table referred to.  pToCol is a list of tables in the other
75843** pTo table that the foreign key points to.  flags contains all
75844** information about the conflict resolution algorithms specified
75845** in the ON DELETE, ON UPDATE and ON INSERT clauses.
75846**
75847** An FKey structure is created and added to the table currently
75848** under construction in the pParse->pNewTable field.
75849**
75850** The foreign key is set for IMMEDIATE processing.  A subsequent call
75851** to sqlite3DeferForeignKey() might change this to DEFERRED.
75852*/
75853SQLITE_PRIVATE void sqlite3CreateForeignKey(
75854  Parse *pParse,       /* Parsing context */
75855  ExprList *pFromCol,  /* Columns in this table that point to other table */
75856  Token *pTo,          /* Name of the other table */
75857  ExprList *pToCol,    /* Columns in the other table */
75858  int flags            /* Conflict resolution algorithms. */
75859){
75860  sqlite3 *db = pParse->db;
75861#ifndef SQLITE_OMIT_FOREIGN_KEY
75862  FKey *pFKey = 0;
75863  FKey *pNextTo;
75864  Table *p = pParse->pNewTable;
75865  int nByte;
75866  int i;
75867  int nCol;
75868  char *z;
75869
75870  assert( pTo!=0 );
75871  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
75872  if( pFromCol==0 ){
75873    int iCol = p->nCol-1;
75874    if( NEVER(iCol<0) ) goto fk_end;
75875    if( pToCol && pToCol->nExpr!=1 ){
75876      sqlite3ErrorMsg(pParse, "foreign key on %s"
75877         " should reference only one column of table %T",
75878         p->aCol[iCol].zName, pTo);
75879      goto fk_end;
75880    }
75881    nCol = 1;
75882  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
75883    sqlite3ErrorMsg(pParse,
75884        "number of columns in foreign key does not match the number of "
75885        "columns in the referenced table");
75886    goto fk_end;
75887  }else{
75888    nCol = pFromCol->nExpr;
75889  }
75890  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
75891  if( pToCol ){
75892    for(i=0; i<pToCol->nExpr; i++){
75893      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
75894    }
75895  }
75896  pFKey = sqlite3DbMallocZero(db, nByte );
75897  if( pFKey==0 ){
75898    goto fk_end;
75899  }
75900  pFKey->pFrom = p;
75901  pFKey->pNextFrom = p->pFKey;
75902  z = (char*)&pFKey->aCol[nCol];
75903  pFKey->zTo = z;
75904  memcpy(z, pTo->z, pTo->n);
75905  z[pTo->n] = 0;
75906  sqlite3Dequote(z);
75907  z += pTo->n+1;
75908  pFKey->nCol = nCol;
75909  if( pFromCol==0 ){
75910    pFKey->aCol[0].iFrom = p->nCol-1;
75911  }else{
75912    for(i=0; i<nCol; i++){
75913      int j;
75914      for(j=0; j<p->nCol; j++){
75915        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
75916          pFKey->aCol[i].iFrom = j;
75917          break;
75918        }
75919      }
75920      if( j>=p->nCol ){
75921        sqlite3ErrorMsg(pParse,
75922          "unknown column \"%s\" in foreign key definition",
75923          pFromCol->a[i].zName);
75924        goto fk_end;
75925      }
75926    }
75927  }
75928  if( pToCol ){
75929    for(i=0; i<nCol; i++){
75930      int n = sqlite3Strlen30(pToCol->a[i].zName);
75931      pFKey->aCol[i].zCol = z;
75932      memcpy(z, pToCol->a[i].zName, n);
75933      z[n] = 0;
75934      z += n+1;
75935    }
75936  }
75937  pFKey->isDeferred = 0;
75938  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
75939  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
75940
75941  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
75942      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
75943  );
75944  if( pNextTo==pFKey ){
75945    db->mallocFailed = 1;
75946    goto fk_end;
75947  }
75948  if( pNextTo ){
75949    assert( pNextTo->pPrevTo==0 );
75950    pFKey->pNextTo = pNextTo;
75951    pNextTo->pPrevTo = pFKey;
75952  }
75953
75954  /* Link the foreign key to the table as the last step.
75955  */
75956  p->pFKey = pFKey;
75957  pFKey = 0;
75958
75959fk_end:
75960  sqlite3DbFree(db, pFKey);
75961#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
75962  sqlite3ExprListDelete(db, pFromCol);
75963  sqlite3ExprListDelete(db, pToCol);
75964}
75965
75966/*
75967** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
75968** clause is seen as part of a foreign key definition.  The isDeferred
75969** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
75970** The behavior of the most recently created foreign key is adjusted
75971** accordingly.
75972*/
75973SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
75974#ifndef SQLITE_OMIT_FOREIGN_KEY
75975  Table *pTab;
75976  FKey *pFKey;
75977  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
75978  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
75979  pFKey->isDeferred = (u8)isDeferred;
75980#endif
75981}
75982
75983/*
75984** Generate code that will erase and refill index *pIdx.  This is
75985** used to initialize a newly created index or to recompute the
75986** content of an index in response to a REINDEX command.
75987**
75988** if memRootPage is not negative, it means that the index is newly
75989** created.  The register specified by memRootPage contains the
75990** root page number of the index.  If memRootPage is negative, then
75991** the index already exists and must be cleared before being refilled and
75992** the root page number of the index is taken from pIndex->tnum.
75993*/
75994static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
75995  Table *pTab = pIndex->pTable;  /* The table that is indexed */
75996  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
75997  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
75998  int addr1;                     /* Address of top of loop */
75999  int tnum;                      /* Root page of index */
76000  Vdbe *v;                       /* Generate code into this virtual machine */
76001  KeyInfo *pKey;                 /* KeyInfo for index */
76002  int regIdxKey;                 /* Registers containing the index key */
76003  int regRecord;                 /* Register holding assemblied index record */
76004  sqlite3 *db = pParse->db;      /* The database connection */
76005  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
76006
76007#ifndef SQLITE_OMIT_AUTHORIZATION
76008  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
76009      db->aDb[iDb].zName ) ){
76010    return;
76011  }
76012#endif
76013
76014  /* Require a write-lock on the table to perform this operation */
76015  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
76016
76017  v = sqlite3GetVdbe(pParse);
76018  if( v==0 ) return;
76019  if( memRootPage>=0 ){
76020    tnum = memRootPage;
76021  }else{
76022    tnum = pIndex->tnum;
76023    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
76024  }
76025  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
76026  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
76027                    (char *)pKey, P4_KEYINFO_HANDOFF);
76028  if( memRootPage>=0 ){
76029    sqlite3VdbeChangeP5(v, 1);
76030  }
76031  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
76032  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
76033  regRecord = sqlite3GetTempReg(pParse);
76034  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
76035  if( pIndex->onError!=OE_None ){
76036    const int regRowid = regIdxKey + pIndex->nColumn;
76037    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
76038    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
76039
76040    /* The registers accessed by the OP_IsUnique opcode were allocated
76041    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
76042    ** call above. Just before that function was freed they were released
76043    ** (made available to the compiler for reuse) using
76044    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
76045    ** opcode use the values stored within seems dangerous. However, since
76046    ** we can be sure that no other temp registers have been allocated
76047    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
76048    */
76049    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
76050    sqlite3HaltConstraint(
76051        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
76052  }
76053  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
76054  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
76055  sqlite3ReleaseTempReg(pParse, regRecord);
76056  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
76057  sqlite3VdbeJumpHere(v, addr1);
76058  sqlite3VdbeAddOp1(v, OP_Close, iTab);
76059  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
76060}
76061
76062/*
76063** Create a new index for an SQL table.  pName1.pName2 is the name of the index
76064** and pTblList is the name of the table that is to be indexed.  Both will
76065** be NULL for a primary key or an index that is created to satisfy a
76066** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
76067** as the table to be indexed.  pParse->pNewTable is a table that is
76068** currently being constructed by a CREATE TABLE statement.
76069**
76070** pList is a list of columns to be indexed.  pList will be NULL if this
76071** is a primary key or unique-constraint on the most recent column added
76072** to the table currently under construction.
76073**
76074** If the index is created successfully, return a pointer to the new Index
76075** structure. This is used by sqlite3AddPrimaryKey() to mark the index
76076** as the tables primary key (Index.autoIndex==2).
76077*/
76078SQLITE_PRIVATE Index *sqlite3CreateIndex(
76079  Parse *pParse,     /* All information about this parse */
76080  Token *pName1,     /* First part of index name. May be NULL */
76081  Token *pName2,     /* Second part of index name. May be NULL */
76082  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
76083  ExprList *pList,   /* A list of columns to be indexed */
76084  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
76085  Token *pStart,     /* The CREATE token that begins this statement */
76086  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
76087  int sortOrder,     /* Sort order of primary key when pList==NULL */
76088  int ifNotExist     /* Omit error if index already exists */
76089){
76090  Index *pRet = 0;     /* Pointer to return */
76091  Table *pTab = 0;     /* Table to be indexed */
76092  Index *pIndex = 0;   /* The index to be created */
76093  char *zName = 0;     /* Name of the index */
76094  int nName;           /* Number of characters in zName */
76095  int i, j;
76096  Token nullId;        /* Fake token for an empty ID list */
76097  DbFixer sFix;        /* For assigning database names to pTable */
76098  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
76099  sqlite3 *db = pParse->db;
76100  Db *pDb;             /* The specific table containing the indexed database */
76101  int iDb;             /* Index of the database that is being written */
76102  Token *pName = 0;    /* Unqualified name of the index to create */
76103  struct ExprList_item *pListItem; /* For looping over pList */
76104  int nCol;
76105  int nExtra = 0;
76106  char *zExtra;
76107
76108  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
76109  assert( pParse->nErr==0 );      /* Never called with prior errors */
76110  if( db->mallocFailed || IN_DECLARE_VTAB ){
76111    goto exit_create_index;
76112  }
76113  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76114    goto exit_create_index;
76115  }
76116
76117  /*
76118  ** Find the table that is to be indexed.  Return early if not found.
76119  */
76120  if( pTblName!=0 ){
76121
76122    /* Use the two-part index name to determine the database
76123    ** to search for the table. 'Fix' the table name to this db
76124    ** before looking up the table.
76125    */
76126    assert( pName1 && pName2 );
76127    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
76128    if( iDb<0 ) goto exit_create_index;
76129
76130#ifndef SQLITE_OMIT_TEMPDB
76131    /* If the index name was unqualified, check if the the table
76132    ** is a temp table. If so, set the database to 1. Do not do this
76133    ** if initialising a database schema.
76134    */
76135    if( !db->init.busy ){
76136      pTab = sqlite3SrcListLookup(pParse, pTblName);
76137      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
76138        iDb = 1;
76139      }
76140    }
76141#endif
76142
76143    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
76144        sqlite3FixSrcList(&sFix, pTblName)
76145    ){
76146      /* Because the parser constructs pTblName from a single identifier,
76147      ** sqlite3FixSrcList can never fail. */
76148      assert(0);
76149    }
76150    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
76151        pTblName->a[0].zDatabase);
76152    if( !pTab || db->mallocFailed ) goto exit_create_index;
76153    assert( db->aDb[iDb].pSchema==pTab->pSchema );
76154  }else{
76155    assert( pName==0 );
76156    pTab = pParse->pNewTable;
76157    if( !pTab ) goto exit_create_index;
76158    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76159  }
76160  pDb = &db->aDb[iDb];
76161
76162  assert( pTab!=0 );
76163  assert( pParse->nErr==0 );
76164  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
76165       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
76166    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
76167    goto exit_create_index;
76168  }
76169#ifndef SQLITE_OMIT_VIEW
76170  if( pTab->pSelect ){
76171    sqlite3ErrorMsg(pParse, "views may not be indexed");
76172    goto exit_create_index;
76173  }
76174#endif
76175#ifndef SQLITE_OMIT_VIRTUALTABLE
76176  if( IsVirtual(pTab) ){
76177    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
76178    goto exit_create_index;
76179  }
76180#endif
76181
76182  /*
76183  ** Find the name of the index.  Make sure there is not already another
76184  ** index or table with the same name.
76185  **
76186  ** Exception:  If we are reading the names of permanent indices from the
76187  ** sqlite_master table (because some other process changed the schema) and
76188  ** one of the index names collides with the name of a temporary table or
76189  ** index, then we will continue to process this index.
76190  **
76191  ** If pName==0 it means that we are
76192  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
76193  ** own name.
76194  */
76195  if( pName ){
76196    zName = sqlite3NameFromToken(db, pName);
76197    if( zName==0 ) goto exit_create_index;
76198    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
76199      goto exit_create_index;
76200    }
76201    if( !db->init.busy ){
76202      if( sqlite3FindTable(db, zName, 0)!=0 ){
76203        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
76204        goto exit_create_index;
76205      }
76206    }
76207    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
76208      if( !ifNotExist ){
76209        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
76210      }
76211      goto exit_create_index;
76212    }
76213  }else{
76214    int n;
76215    Index *pLoop;
76216    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
76217    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
76218    if( zName==0 ){
76219      goto exit_create_index;
76220    }
76221  }
76222
76223  /* Check for authorization to create an index.
76224  */
76225#ifndef SQLITE_OMIT_AUTHORIZATION
76226  {
76227    const char *zDb = pDb->zName;
76228    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
76229      goto exit_create_index;
76230    }
76231    i = SQLITE_CREATE_INDEX;
76232    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
76233    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
76234      goto exit_create_index;
76235    }
76236  }
76237#endif
76238
76239  /* If pList==0, it means this routine was called to make a primary
76240  ** key out of the last column added to the table under construction.
76241  ** So create a fake list to simulate this.
76242  */
76243  if( pList==0 ){
76244    nullId.z = pTab->aCol[pTab->nCol-1].zName;
76245    nullId.n = sqlite3Strlen30((char*)nullId.z);
76246    pList = sqlite3ExprListAppend(pParse, 0, 0);
76247    if( pList==0 ) goto exit_create_index;
76248    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
76249    pList->a[0].sortOrder = (u8)sortOrder;
76250  }
76251
76252  /* Figure out how many bytes of space are required to store explicitly
76253  ** specified collation sequence names.
76254  */
76255  for(i=0; i<pList->nExpr; i++){
76256    Expr *pExpr = pList->a[i].pExpr;
76257    if( pExpr ){
76258      CollSeq *pColl = pExpr->pColl;
76259      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
76260      ** failure we have quit before reaching this point. */
76261      if( ALWAYS(pColl) ){
76262        nExtra += (1 + sqlite3Strlen30(pColl->zName));
76263      }
76264    }
76265  }
76266
76267  /*
76268  ** Allocate the index structure.
76269  */
76270  nName = sqlite3Strlen30(zName);
76271  nCol = pList->nExpr;
76272  pIndex = sqlite3DbMallocZero(db,
76273      sizeof(Index) +              /* Index structure  */
76274      sizeof(int)*nCol +           /* Index.aiColumn   */
76275      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
76276      sizeof(char *)*nCol +        /* Index.azColl     */
76277      sizeof(u8)*nCol +            /* Index.aSortOrder */
76278      nName + 1 +                  /* Index.zName      */
76279      nExtra                       /* Collation sequence names */
76280  );
76281  if( db->mallocFailed ){
76282    goto exit_create_index;
76283  }
76284  pIndex->azColl = (char**)(&pIndex[1]);
76285  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
76286  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
76287  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
76288  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
76289  zExtra = (char *)(&pIndex->zName[nName+1]);
76290  memcpy(pIndex->zName, zName, nName+1);
76291  pIndex->pTable = pTab;
76292  pIndex->nColumn = pList->nExpr;
76293  pIndex->onError = (u8)onError;
76294  pIndex->autoIndex = (u8)(pName==0);
76295  pIndex->pSchema = db->aDb[iDb].pSchema;
76296
76297  /* Check to see if we should honor DESC requests on index columns
76298  */
76299  if( pDb->pSchema->file_format>=4 ){
76300    sortOrderMask = -1;   /* Honor DESC */
76301  }else{
76302    sortOrderMask = 0;    /* Ignore DESC */
76303  }
76304
76305  /* Scan the names of the columns of the table to be indexed and
76306  ** load the column indices into the Index structure.  Report an error
76307  ** if any column is not found.
76308  **
76309  ** TODO:  Add a test to make sure that the same column is not named
76310  ** more than once within the same index.  Only the first instance of
76311  ** the column will ever be used by the optimizer.  Note that using the
76312  ** same column more than once cannot be an error because that would
76313  ** break backwards compatibility - it needs to be a warning.
76314  */
76315  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
76316    const char *zColName = pListItem->zName;
76317    Column *pTabCol;
76318    int requestedSortOrder;
76319    char *zColl;                   /* Collation sequence name */
76320
76321    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
76322      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
76323    }
76324    if( j>=pTab->nCol ){
76325      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
76326        pTab->zName, zColName);
76327      pParse->checkSchema = 1;
76328      goto exit_create_index;
76329    }
76330    pIndex->aiColumn[i] = j;
76331    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
76332    ** the way the "idxlist" non-terminal is constructed by the parser,
76333    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
76334    ** must exist or else there must have been an OOM error.  But if there
76335    ** was an OOM error, we would never reach this point. */
76336    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
76337      int nColl;
76338      zColl = pListItem->pExpr->pColl->zName;
76339      nColl = sqlite3Strlen30(zColl) + 1;
76340      assert( nExtra>=nColl );
76341      memcpy(zExtra, zColl, nColl);
76342      zColl = zExtra;
76343      zExtra += nColl;
76344      nExtra -= nColl;
76345    }else{
76346      zColl = pTab->aCol[j].zColl;
76347      if( !zColl ){
76348        zColl = db->pDfltColl->zName;
76349      }
76350    }
76351    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
76352      goto exit_create_index;
76353    }
76354    pIndex->azColl[i] = zColl;
76355    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
76356    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
76357  }
76358  sqlite3DefaultRowEst(pIndex);
76359
76360  if( pTab==pParse->pNewTable ){
76361    /* This routine has been called to create an automatic index as a
76362    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
76363    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
76364    ** i.e. one of:
76365    **
76366    ** CREATE TABLE t(x PRIMARY KEY, y);
76367    ** CREATE TABLE t(x, y, UNIQUE(x, y));
76368    **
76369    ** Either way, check to see if the table already has such an index. If
76370    ** so, don't bother creating this one. This only applies to
76371    ** automatically created indices. Users can do as they wish with
76372    ** explicit indices.
76373    **
76374    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
76375    ** (and thus suppressing the second one) even if they have different
76376    ** sort orders.
76377    **
76378    ** If there are different collating sequences or if the columns of
76379    ** the constraint occur in different orders, then the constraints are
76380    ** considered distinct and both result in separate indices.
76381    */
76382    Index *pIdx;
76383    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76384      int k;
76385      assert( pIdx->onError!=OE_None );
76386      assert( pIdx->autoIndex );
76387      assert( pIndex->onError!=OE_None );
76388
76389      if( pIdx->nColumn!=pIndex->nColumn ) continue;
76390      for(k=0; k<pIdx->nColumn; k++){
76391        const char *z1;
76392        const char *z2;
76393        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
76394        z1 = pIdx->azColl[k];
76395        z2 = pIndex->azColl[k];
76396        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
76397      }
76398      if( k==pIdx->nColumn ){
76399        if( pIdx->onError!=pIndex->onError ){
76400          /* This constraint creates the same index as a previous
76401          ** constraint specified somewhere in the CREATE TABLE statement.
76402          ** However the ON CONFLICT clauses are different. If both this
76403          ** constraint and the previous equivalent constraint have explicit
76404          ** ON CONFLICT clauses this is an error. Otherwise, use the
76405          ** explicitly specified behaviour for the index.
76406          */
76407          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
76408            sqlite3ErrorMsg(pParse,
76409                "conflicting ON CONFLICT clauses specified", 0);
76410          }
76411          if( pIdx->onError==OE_Default ){
76412            pIdx->onError = pIndex->onError;
76413          }
76414        }
76415        goto exit_create_index;
76416      }
76417    }
76418  }
76419
76420  /* Link the new Index structure to its table and to the other
76421  ** in-memory database structures.
76422  */
76423  if( db->init.busy ){
76424    Index *p;
76425    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
76426                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
76427                          pIndex);
76428    if( p ){
76429      assert( p==pIndex );  /* Malloc must have failed */
76430      db->mallocFailed = 1;
76431      goto exit_create_index;
76432    }
76433    db->flags |= SQLITE_InternChanges;
76434    if( pTblName!=0 ){
76435      pIndex->tnum = db->init.newTnum;
76436    }
76437  }
76438
76439  /* If the db->init.busy is 0 then create the index on disk.  This
76440  ** involves writing the index into the master table and filling in the
76441  ** index with the current table contents.
76442  **
76443  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
76444  ** command.  db->init.busy is 1 when a database is opened and
76445  ** CREATE INDEX statements are read out of the master table.  In
76446  ** the latter case the index already exists on disk, which is why
76447  ** we don't want to recreate it.
76448  **
76449  ** If pTblName==0 it means this index is generated as a primary key
76450  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
76451  ** has just been created, it contains no data and the index initialization
76452  ** step can be skipped.
76453  */
76454  else{ /* if( db->init.busy==0 ) */
76455    Vdbe *v;
76456    char *zStmt;
76457    int iMem = ++pParse->nMem;
76458
76459    v = sqlite3GetVdbe(pParse);
76460    if( v==0 ) goto exit_create_index;
76461
76462
76463    /* Create the rootpage for the index
76464    */
76465    sqlite3BeginWriteOperation(pParse, 1, iDb);
76466    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
76467
76468    /* Gather the complete text of the CREATE INDEX statement into
76469    ** the zStmt variable
76470    */
76471    if( pStart ){
76472      assert( pEnd!=0 );
76473      /* A named index with an explicit CREATE INDEX statement */
76474      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
76475        onError==OE_None ? "" : " UNIQUE",
76476        pEnd->z - pName->z + 1,
76477        pName->z);
76478    }else{
76479      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
76480      /* zStmt = sqlite3MPrintf(""); */
76481      zStmt = 0;
76482    }
76483
76484    /* Add an entry in sqlite_master for this index
76485    */
76486    sqlite3NestedParse(pParse,
76487        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
76488        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
76489        pIndex->zName,
76490        pTab->zName,
76491        iMem,
76492        zStmt
76493    );
76494    sqlite3DbFree(db, zStmt);
76495
76496    /* Fill the index with data and reparse the schema. Code an OP_Expire
76497    ** to invalidate all pre-compiled statements.
76498    */
76499    if( pTblName ){
76500      sqlite3RefillIndex(pParse, pIndex, iMem);
76501      sqlite3ChangeCookie(pParse, iDb);
76502      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
76503         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
76504      sqlite3VdbeAddOp1(v, OP_Expire, 0);
76505    }
76506  }
76507
76508  /* When adding an index to the list of indices for a table, make
76509  ** sure all indices labeled OE_Replace come after all those labeled
76510  ** OE_Ignore.  This is necessary for the correct constraint check
76511  ** processing (in sqlite3GenerateConstraintChecks()) as part of
76512  ** UPDATE and INSERT statements.
76513  */
76514  if( db->init.busy || pTblName==0 ){
76515    if( onError!=OE_Replace || pTab->pIndex==0
76516         || pTab->pIndex->onError==OE_Replace){
76517      pIndex->pNext = pTab->pIndex;
76518      pTab->pIndex = pIndex;
76519    }else{
76520      Index *pOther = pTab->pIndex;
76521      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
76522        pOther = pOther->pNext;
76523      }
76524      pIndex->pNext = pOther->pNext;
76525      pOther->pNext = pIndex;
76526    }
76527    pRet = pIndex;
76528    pIndex = 0;
76529  }
76530
76531  /* Clean up before exiting */
76532exit_create_index:
76533  if( pIndex ){
76534    sqlite3DbFree(db, pIndex->zColAff);
76535    sqlite3DbFree(db, pIndex);
76536  }
76537  sqlite3ExprListDelete(db, pList);
76538  sqlite3SrcListDelete(db, pTblName);
76539  sqlite3DbFree(db, zName);
76540  return pRet;
76541}
76542
76543/*
76544** Fill the Index.aiRowEst[] array with default information - information
76545** to be used when we have not run the ANALYZE command.
76546**
76547** aiRowEst[0] is suppose to contain the number of elements in the index.
76548** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
76549** number of rows in the table that match any particular value of the
76550** first column of the index.  aiRowEst[2] is an estimate of the number
76551** of rows that match any particular combiniation of the first 2 columns
76552** of the index.  And so forth.  It must always be the case that
76553*
76554**           aiRowEst[N]<=aiRowEst[N-1]
76555**           aiRowEst[N]>=1
76556**
76557** Apart from that, we have little to go on besides intuition as to
76558** how aiRowEst[] should be initialized.  The numbers generated here
76559** are based on typical values found in actual indices.
76560*/
76561SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
76562  unsigned *a = pIdx->aiRowEst;
76563  int i;
76564  assert( a!=0 );
76565  a[0] = 1000000;
76566  for(i=pIdx->nColumn; i>=5; i--){
76567    a[i] = 5;
76568  }
76569  while( i>=1 ){
76570    a[i] = 11 - i;
76571    i--;
76572  }
76573  if( pIdx->onError!=OE_None ){
76574    a[pIdx->nColumn] = 1;
76575  }
76576}
76577
76578/*
76579** This routine will drop an existing named index.  This routine
76580** implements the DROP INDEX statement.
76581*/
76582SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
76583  Index *pIndex;
76584  Vdbe *v;
76585  sqlite3 *db = pParse->db;
76586  int iDb;
76587
76588  assert( pParse->nErr==0 );   /* Never called with prior errors */
76589  if( db->mallocFailed ){
76590    goto exit_drop_index;
76591  }
76592  assert( pName->nSrc==1 );
76593  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76594    goto exit_drop_index;
76595  }
76596  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
76597  if( pIndex==0 ){
76598    if( !ifExists ){
76599      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
76600    }
76601    pParse->checkSchema = 1;
76602    goto exit_drop_index;
76603  }
76604  if( pIndex->autoIndex ){
76605    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
76606      "or PRIMARY KEY constraint cannot be dropped", 0);
76607    goto exit_drop_index;
76608  }
76609  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
76610#ifndef SQLITE_OMIT_AUTHORIZATION
76611  {
76612    int code = SQLITE_DROP_INDEX;
76613    Table *pTab = pIndex->pTable;
76614    const char *zDb = db->aDb[iDb].zName;
76615    const char *zTab = SCHEMA_TABLE(iDb);
76616    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
76617      goto exit_drop_index;
76618    }
76619    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
76620    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
76621      goto exit_drop_index;
76622    }
76623  }
76624#endif
76625
76626  /* Generate code to remove the index and from the master table */
76627  v = sqlite3GetVdbe(pParse);
76628  if( v ){
76629    sqlite3BeginWriteOperation(pParse, 1, iDb);
76630    sqlite3NestedParse(pParse,
76631       "DELETE FROM %Q.%s WHERE name=%Q",
76632       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
76633       pIndex->zName
76634    );
76635    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
76636      sqlite3NestedParse(pParse,
76637        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
76638        db->aDb[iDb].zName, pIndex->zName
76639      );
76640    }
76641    sqlite3ChangeCookie(pParse, iDb);
76642    destroyRootPage(pParse, pIndex->tnum, iDb);
76643    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
76644  }
76645
76646exit_drop_index:
76647  sqlite3SrcListDelete(db, pName);
76648}
76649
76650/*
76651** pArray is a pointer to an array of objects.  Each object in the
76652** array is szEntry bytes in size.  This routine allocates a new
76653** object on the end of the array.
76654**
76655** *pnEntry is the number of entries already in use.  *pnAlloc is
76656** the previously allocated size of the array.  initSize is the
76657** suggested initial array size allocation.
76658**
76659** The index of the new entry is returned in *pIdx.
76660**
76661** This routine returns a pointer to the array of objects.  This
76662** might be the same as the pArray parameter or it might be a different
76663** pointer if the array was resized.
76664*/
76665SQLITE_PRIVATE void *sqlite3ArrayAllocate(
76666  sqlite3 *db,      /* Connection to notify of malloc failures */
76667  void *pArray,     /* Array of objects.  Might be reallocated */
76668  int szEntry,      /* Size of each object in the array */
76669  int initSize,     /* Suggested initial allocation, in elements */
76670  int *pnEntry,     /* Number of objects currently in use */
76671  int *pnAlloc,     /* Current size of the allocation, in elements */
76672  int *pIdx         /* Write the index of a new slot here */
76673){
76674  char *z;
76675  if( *pnEntry >= *pnAlloc ){
76676    void *pNew;
76677    int newSize;
76678    newSize = (*pnAlloc)*2 + initSize;
76679    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
76680    if( pNew==0 ){
76681      *pIdx = -1;
76682      return pArray;
76683    }
76684    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
76685    pArray = pNew;
76686  }
76687  z = (char*)pArray;
76688  memset(&z[*pnEntry * szEntry], 0, szEntry);
76689  *pIdx = *pnEntry;
76690  ++*pnEntry;
76691  return pArray;
76692}
76693
76694/*
76695** Append a new element to the given IdList.  Create a new IdList if
76696** need be.
76697**
76698** A new IdList is returned, or NULL if malloc() fails.
76699*/
76700SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
76701  int i;
76702  if( pList==0 ){
76703    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
76704    if( pList==0 ) return 0;
76705    pList->nAlloc = 0;
76706  }
76707  pList->a = sqlite3ArrayAllocate(
76708      db,
76709      pList->a,
76710      sizeof(pList->a[0]),
76711      5,
76712      &pList->nId,
76713      &pList->nAlloc,
76714      &i
76715  );
76716  if( i<0 ){
76717    sqlite3IdListDelete(db, pList);
76718    return 0;
76719  }
76720  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
76721  return pList;
76722}
76723
76724/*
76725** Delete an IdList.
76726*/
76727SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
76728  int i;
76729  if( pList==0 ) return;
76730  for(i=0; i<pList->nId; i++){
76731    sqlite3DbFree(db, pList->a[i].zName);
76732  }
76733  sqlite3DbFree(db, pList->a);
76734  sqlite3DbFree(db, pList);
76735}
76736
76737/*
76738** Return the index in pList of the identifier named zId.  Return -1
76739** if not found.
76740*/
76741SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
76742  int i;
76743  if( pList==0 ) return -1;
76744  for(i=0; i<pList->nId; i++){
76745    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
76746  }
76747  return -1;
76748}
76749
76750/*
76751** Expand the space allocated for the given SrcList object by
76752** creating nExtra new slots beginning at iStart.  iStart is zero based.
76753** New slots are zeroed.
76754**
76755** For example, suppose a SrcList initially contains two entries: A,B.
76756** To append 3 new entries onto the end, do this:
76757**
76758**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
76759**
76760** After the call above it would contain:  A, B, nil, nil, nil.
76761** If the iStart argument had been 1 instead of 2, then the result
76762** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
76763** the iStart value would be 0.  The result then would
76764** be: nil, nil, nil, A, B.
76765**
76766** If a memory allocation fails the SrcList is unchanged.  The
76767** db->mallocFailed flag will be set to true.
76768*/
76769SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
76770  sqlite3 *db,       /* Database connection to notify of OOM errors */
76771  SrcList *pSrc,     /* The SrcList to be enlarged */
76772  int nExtra,        /* Number of new slots to add to pSrc->a[] */
76773  int iStart         /* Index in pSrc->a[] of first new slot */
76774){
76775  int i;
76776
76777  /* Sanity checking on calling parameters */
76778  assert( iStart>=0 );
76779  assert( nExtra>=1 );
76780  assert( pSrc!=0 );
76781  assert( iStart<=pSrc->nSrc );
76782
76783  /* Allocate additional space if needed */
76784  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
76785    SrcList *pNew;
76786    int nAlloc = pSrc->nSrc+nExtra;
76787    int nGot;
76788    pNew = sqlite3DbRealloc(db, pSrc,
76789               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
76790    if( pNew==0 ){
76791      assert( db->mallocFailed );
76792      return pSrc;
76793    }
76794    pSrc = pNew;
76795    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
76796    pSrc->nAlloc = (u16)nGot;
76797  }
76798
76799  /* Move existing slots that come after the newly inserted slots
76800  ** out of the way */
76801  for(i=pSrc->nSrc-1; i>=iStart; i--){
76802    pSrc->a[i+nExtra] = pSrc->a[i];
76803  }
76804  pSrc->nSrc += (i16)nExtra;
76805
76806  /* Zero the newly allocated slots */
76807  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
76808  for(i=iStart; i<iStart+nExtra; i++){
76809    pSrc->a[i].iCursor = -1;
76810  }
76811
76812  /* Return a pointer to the enlarged SrcList */
76813  return pSrc;
76814}
76815
76816
76817/*
76818** Append a new table name to the given SrcList.  Create a new SrcList if
76819** need be.  A new entry is created in the SrcList even if pTable is NULL.
76820**
76821** A SrcList is returned, or NULL if there is an OOM error.  The returned
76822** SrcList might be the same as the SrcList that was input or it might be
76823** a new one.  If an OOM error does occurs, then the prior value of pList
76824** that is input to this routine is automatically freed.
76825**
76826** If pDatabase is not null, it means that the table has an optional
76827** database name prefix.  Like this:  "database.table".  The pDatabase
76828** points to the table name and the pTable points to the database name.
76829** The SrcList.a[].zName field is filled with the table name which might
76830** come from pTable (if pDatabase is NULL) or from pDatabase.
76831** SrcList.a[].zDatabase is filled with the database name from pTable,
76832** or with NULL if no database is specified.
76833**
76834** In other words, if call like this:
76835**
76836**         sqlite3SrcListAppend(D,A,B,0);
76837**
76838** Then B is a table name and the database name is unspecified.  If called
76839** like this:
76840**
76841**         sqlite3SrcListAppend(D,A,B,C);
76842**
76843** Then C is the table name and B is the database name.  If C is defined
76844** then so is B.  In other words, we never have a case where:
76845**
76846**         sqlite3SrcListAppend(D,A,0,C);
76847**
76848** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
76849** before being added to the SrcList.
76850*/
76851SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
76852  sqlite3 *db,        /* Connection to notify of malloc failures */
76853  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
76854  Token *pTable,      /* Table to append */
76855  Token *pDatabase    /* Database of the table */
76856){
76857  struct SrcList_item *pItem;
76858  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
76859  if( pList==0 ){
76860    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
76861    if( pList==0 ) return 0;
76862    pList->nAlloc = 1;
76863  }
76864  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
76865  if( db->mallocFailed ){
76866    sqlite3SrcListDelete(db, pList);
76867    return 0;
76868  }
76869  pItem = &pList->a[pList->nSrc-1];
76870  if( pDatabase && pDatabase->z==0 ){
76871    pDatabase = 0;
76872  }
76873  if( pDatabase ){
76874    Token *pTemp = pDatabase;
76875    pDatabase = pTable;
76876    pTable = pTemp;
76877  }
76878  pItem->zName = sqlite3NameFromToken(db, pTable);
76879  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
76880  return pList;
76881}
76882
76883/*
76884** Assign VdbeCursor index numbers to all tables in a SrcList
76885*/
76886SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
76887  int i;
76888  struct SrcList_item *pItem;
76889  assert(pList || pParse->db->mallocFailed );
76890  if( pList ){
76891    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76892      if( pItem->iCursor>=0 ) break;
76893      pItem->iCursor = pParse->nTab++;
76894      if( pItem->pSelect ){
76895        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
76896      }
76897    }
76898  }
76899}
76900
76901/*
76902** Delete an entire SrcList including all its substructure.
76903*/
76904SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
76905  int i;
76906  struct SrcList_item *pItem;
76907  if( pList==0 ) return;
76908  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
76909    sqlite3DbFree(db, pItem->zDatabase);
76910    sqlite3DbFree(db, pItem->zName);
76911    sqlite3DbFree(db, pItem->zAlias);
76912    sqlite3DbFree(db, pItem->zIndex);
76913    sqlite3DeleteTable(db, pItem->pTab);
76914    sqlite3SelectDelete(db, pItem->pSelect);
76915    sqlite3ExprDelete(db, pItem->pOn);
76916    sqlite3IdListDelete(db, pItem->pUsing);
76917  }
76918  sqlite3DbFree(db, pList);
76919}
76920
76921/*
76922** This routine is called by the parser to add a new term to the
76923** end of a growing FROM clause.  The "p" parameter is the part of
76924** the FROM clause that has already been constructed.  "p" is NULL
76925** if this is the first term of the FROM clause.  pTable and pDatabase
76926** are the name of the table and database named in the FROM clause term.
76927** pDatabase is NULL if the database name qualifier is missing - the
76928** usual case.  If the term has a alias, then pAlias points to the
76929** alias token.  If the term is a subquery, then pSubquery is the
76930** SELECT statement that the subquery encodes.  The pTable and
76931** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
76932** parameters are the content of the ON and USING clauses.
76933**
76934** Return a new SrcList which encodes is the FROM with the new
76935** term added.
76936*/
76937SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
76938  Parse *pParse,          /* Parsing context */
76939  SrcList *p,             /* The left part of the FROM clause already seen */
76940  Token *pTable,          /* Name of the table to add to the FROM clause */
76941  Token *pDatabase,       /* Name of the database containing pTable */
76942  Token *pAlias,          /* The right-hand side of the AS subexpression */
76943  Select *pSubquery,      /* A subquery used in place of a table name */
76944  Expr *pOn,              /* The ON clause of a join */
76945  IdList *pUsing          /* The USING clause of a join */
76946){
76947  struct SrcList_item *pItem;
76948  sqlite3 *db = pParse->db;
76949  if( !p && (pOn || pUsing) ){
76950    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
76951      (pOn ? "ON" : "USING")
76952    );
76953    goto append_from_error;
76954  }
76955  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
76956  if( p==0 || NEVER(p->nSrc==0) ){
76957    goto append_from_error;
76958  }
76959  pItem = &p->a[p->nSrc-1];
76960  assert( pAlias!=0 );
76961  if( pAlias->n ){
76962    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
76963  }
76964  pItem->pSelect = pSubquery;
76965  pItem->pOn = pOn;
76966  pItem->pUsing = pUsing;
76967  return p;
76968
76969 append_from_error:
76970  assert( p==0 );
76971  sqlite3ExprDelete(db, pOn);
76972  sqlite3IdListDelete(db, pUsing);
76973  sqlite3SelectDelete(db, pSubquery);
76974  return 0;
76975}
76976
76977/*
76978** Add an INDEXED BY or NOT INDEXED clause to the most recently added
76979** element of the source-list passed as the second argument.
76980*/
76981SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
76982  assert( pIndexedBy!=0 );
76983  if( p && ALWAYS(p->nSrc>0) ){
76984    struct SrcList_item *pItem = &p->a[p->nSrc-1];
76985    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
76986    if( pIndexedBy->n==1 && !pIndexedBy->z ){
76987      /* A "NOT INDEXED" clause was supplied. See parse.y
76988      ** construct "indexed_opt" for details. */
76989      pItem->notIndexed = 1;
76990    }else{
76991      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
76992    }
76993  }
76994}
76995
76996/*
76997** When building up a FROM clause in the parser, the join operator
76998** is initially attached to the left operand.  But the code generator
76999** expects the join operator to be on the right operand.  This routine
77000** Shifts all join operators from left to right for an entire FROM
77001** clause.
77002**
77003** Example: Suppose the join is like this:
77004**
77005**           A natural cross join B
77006**
77007** The operator is "natural cross join".  The A and B operands are stored
77008** in p->a[0] and p->a[1], respectively.  The parser initially stores the
77009** operator with A.  This routine shifts that operator over to B.
77010*/
77011SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
77012  if( p && p->a ){
77013    int i;
77014    for(i=p->nSrc-1; i>0; i--){
77015      p->a[i].jointype = p->a[i-1].jointype;
77016    }
77017    p->a[0].jointype = 0;
77018  }
77019}
77020
77021/*
77022** Begin a transaction
77023*/
77024SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
77025  sqlite3 *db;
77026  Vdbe *v;
77027  int i;
77028
77029  assert( pParse!=0 );
77030  db = pParse->db;
77031  assert( db!=0 );
77032/*  if( db->aDb[0].pBt==0 ) return; */
77033  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
77034    return;
77035  }
77036  v = sqlite3GetVdbe(pParse);
77037  if( !v ) return;
77038  if( type!=TK_DEFERRED ){
77039    for(i=0; i<db->nDb; i++){
77040      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
77041      sqlite3VdbeUsesBtree(v, i);
77042    }
77043  }
77044  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
77045}
77046
77047/*
77048** Commit a transaction
77049*/
77050SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
77051  sqlite3 *db;
77052  Vdbe *v;
77053
77054  assert( pParse!=0 );
77055  db = pParse->db;
77056  assert( db!=0 );
77057/*  if( db->aDb[0].pBt==0 ) return; */
77058  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
77059    return;
77060  }
77061  v = sqlite3GetVdbe(pParse);
77062  if( v ){
77063    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
77064  }
77065}
77066
77067/*
77068** Rollback a transaction
77069*/
77070SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
77071  sqlite3 *db;
77072  Vdbe *v;
77073
77074  assert( pParse!=0 );
77075  db = pParse->db;
77076  assert( db!=0 );
77077/*  if( db->aDb[0].pBt==0 ) return; */
77078  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
77079    return;
77080  }
77081  v = sqlite3GetVdbe(pParse);
77082  if( v ){
77083    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
77084  }
77085}
77086
77087/*
77088** This function is called by the parser when it parses a command to create,
77089** release or rollback an SQL savepoint.
77090*/
77091SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
77092  char *zName = sqlite3NameFromToken(pParse->db, pName);
77093  if( zName ){
77094    Vdbe *v = sqlite3GetVdbe(pParse);
77095#ifndef SQLITE_OMIT_AUTHORIZATION
77096    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
77097    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
77098#endif
77099    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
77100      sqlite3DbFree(pParse->db, zName);
77101      return;
77102    }
77103    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
77104  }
77105}
77106
77107/*
77108** Make sure the TEMP database is open and available for use.  Return
77109** the number of errors.  Leave any error messages in the pParse structure.
77110*/
77111SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
77112  sqlite3 *db = pParse->db;
77113  if( db->aDb[1].pBt==0 && !pParse->explain ){
77114    int rc;
77115    Btree *pBt;
77116    static const int flags =
77117          SQLITE_OPEN_READWRITE |
77118          SQLITE_OPEN_CREATE |
77119          SQLITE_OPEN_EXCLUSIVE |
77120          SQLITE_OPEN_DELETEONCLOSE |
77121          SQLITE_OPEN_TEMP_DB;
77122
77123    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
77124    if( rc!=SQLITE_OK ){
77125      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
77126        "file for storing temporary tables");
77127      pParse->rc = rc;
77128      return 1;
77129    }
77130    db->aDb[1].pBt = pBt;
77131    assert( db->aDb[1].pSchema );
77132    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77133      db->mallocFailed = 1;
77134      return 1;
77135    }
77136  }
77137  return 0;
77138}
77139
77140/*
77141** Generate VDBE code that will verify the schema cookie and start
77142** a read-transaction for all named database files.
77143**
77144** It is important that all schema cookies be verified and all
77145** read transactions be started before anything else happens in
77146** the VDBE program.  But this routine can be called after much other
77147** code has been generated.  So here is what we do:
77148**
77149** The first time this routine is called, we code an OP_Goto that
77150** will jump to a subroutine at the end of the program.  Then we
77151** record every database that needs its schema verified in the
77152** pParse->cookieMask field.  Later, after all other code has been
77153** generated, the subroutine that does the cookie verifications and
77154** starts the transactions will be coded and the OP_Goto P2 value
77155** will be made to point to that subroutine.  The generation of the
77156** cookie verification subroutine code happens in sqlite3FinishCoding().
77157**
77158** If iDb<0 then code the OP_Goto only - don't set flag to verify the
77159** schema on any databases.  This can be used to position the OP_Goto
77160** early in the code, before we know if any database tables will be used.
77161*/
77162SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
77163  Parse *pToplevel = sqlite3ParseToplevel(pParse);
77164
77165  if( pToplevel->cookieGoto==0 ){
77166    Vdbe *v = sqlite3GetVdbe(pToplevel);
77167    if( v==0 ) return;  /* This only happens if there was a prior error */
77168    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
77169  }
77170  if( iDb>=0 ){
77171    sqlite3 *db = pToplevel->db;
77172    int mask;
77173
77174    assert( iDb<db->nDb );
77175    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
77176    assert( iDb<SQLITE_MAX_ATTACHED+2 );
77177    mask = 1<<iDb;
77178    if( (pToplevel->cookieMask & mask)==0 ){
77179      pToplevel->cookieMask |= mask;
77180      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
77181      if( !OMIT_TEMPDB && iDb==1 ){
77182        sqlite3OpenTempDatabase(pToplevel);
77183      }
77184    }
77185  }
77186}
77187
77188/*
77189** Generate VDBE code that prepares for doing an operation that
77190** might change the database.
77191**
77192** This routine starts a new transaction if we are not already within
77193** a transaction.  If we are already within a transaction, then a checkpoint
77194** is set if the setStatement parameter is true.  A checkpoint should
77195** be set for operations that might fail (due to a constraint) part of
77196** the way through and which will need to undo some writes without having to
77197** rollback the whole transaction.  For operations where all constraints
77198** can be checked before any changes are made to the database, it is never
77199** necessary to undo a write and the checkpoint should not be set.
77200*/
77201SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
77202  Parse *pToplevel = sqlite3ParseToplevel(pParse);
77203  sqlite3CodeVerifySchema(pParse, iDb);
77204  pToplevel->writeMask |= 1<<iDb;
77205  pToplevel->isMultiWrite |= setStatement;
77206}
77207
77208/*
77209** Indicate that the statement currently under construction might write
77210** more than one entry (example: deleting one row then inserting another,
77211** inserting multiple rows in a table, or inserting a row and index entries.)
77212** If an abort occurs after some of these writes have completed, then it will
77213** be necessary to undo the completed writes.
77214*/
77215SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
77216  Parse *pToplevel = sqlite3ParseToplevel(pParse);
77217  pToplevel->isMultiWrite = 1;
77218}
77219
77220/*
77221** The code generator calls this routine if is discovers that it is
77222** possible to abort a statement prior to completion.  In order to
77223** perform this abort without corrupting the database, we need to make
77224** sure that the statement is protected by a statement transaction.
77225**
77226** Technically, we only need to set the mayAbort flag if the
77227** isMultiWrite flag was previously set.  There is a time dependency
77228** such that the abort must occur after the multiwrite.  This makes
77229** some statements involving the REPLACE conflict resolution algorithm
77230** go a little faster.  But taking advantage of this time dependency
77231** makes it more difficult to prove that the code is correct (in
77232** particular, it prevents us from writing an effective
77233** implementation of sqlite3AssertMayAbort()) and so we have chosen
77234** to take the safe route and skip the optimization.
77235*/
77236SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
77237  Parse *pToplevel = sqlite3ParseToplevel(pParse);
77238  pToplevel->mayAbort = 1;
77239}
77240
77241/*
77242** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
77243** error. The onError parameter determines which (if any) of the statement
77244** and/or current transaction is rolled back.
77245*/
77246SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
77247  Vdbe *v = sqlite3GetVdbe(pParse);
77248  if( onError==OE_Abort ){
77249    sqlite3MayAbort(pParse);
77250  }
77251  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
77252}
77253
77254/*
77255** Check to see if pIndex uses the collating sequence pColl.  Return
77256** true if it does and false if it does not.
77257*/
77258#ifndef SQLITE_OMIT_REINDEX
77259static int collationMatch(const char *zColl, Index *pIndex){
77260  int i;
77261  assert( zColl!=0 );
77262  for(i=0; i<pIndex->nColumn; i++){
77263    const char *z = pIndex->azColl[i];
77264    assert( z!=0 );
77265    if( 0==sqlite3StrICmp(z, zColl) ){
77266      return 1;
77267    }
77268  }
77269  return 0;
77270}
77271#endif
77272
77273/*
77274** Recompute all indices of pTab that use the collating sequence pColl.
77275** If pColl==0 then recompute all indices of pTab.
77276*/
77277#ifndef SQLITE_OMIT_REINDEX
77278static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
77279  Index *pIndex;              /* An index associated with pTab */
77280
77281  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
77282    if( zColl==0 || collationMatch(zColl, pIndex) ){
77283      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77284      sqlite3BeginWriteOperation(pParse, 0, iDb);
77285      sqlite3RefillIndex(pParse, pIndex, -1);
77286    }
77287  }
77288}
77289#endif
77290
77291/*
77292** Recompute all indices of all tables in all databases where the
77293** indices use the collating sequence pColl.  If pColl==0 then recompute
77294** all indices everywhere.
77295*/
77296#ifndef SQLITE_OMIT_REINDEX
77297static void reindexDatabases(Parse *pParse, char const *zColl){
77298  Db *pDb;                    /* A single database */
77299  int iDb;                    /* The database index number */
77300  sqlite3 *db = pParse->db;   /* The database connection */
77301  HashElem *k;                /* For looping over tables in pDb */
77302  Table *pTab;                /* A table in the database */
77303
77304  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
77305    assert( pDb!=0 );
77306    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
77307      pTab = (Table*)sqliteHashData(k);
77308      reindexTable(pParse, pTab, zColl);
77309    }
77310  }
77311}
77312#endif
77313
77314/*
77315** Generate code for the REINDEX command.
77316**
77317**        REINDEX                            -- 1
77318**        REINDEX  <collation>               -- 2
77319**        REINDEX  ?<database>.?<tablename>  -- 3
77320**        REINDEX  ?<database>.?<indexname>  -- 4
77321**
77322** Form 1 causes all indices in all attached databases to be rebuilt.
77323** Form 2 rebuilds all indices in all databases that use the named
77324** collating function.  Forms 3 and 4 rebuild the named index or all
77325** indices associated with the named table.
77326*/
77327#ifndef SQLITE_OMIT_REINDEX
77328SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
77329  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
77330  char *z;                    /* Name of a table or index */
77331  const char *zDb;            /* Name of the database */
77332  Table *pTab;                /* A table in the database */
77333  Index *pIndex;              /* An index associated with pTab */
77334  int iDb;                    /* The database index number */
77335  sqlite3 *db = pParse->db;   /* The database connection */
77336  Token *pObjName;            /* Name of the table or index to be reindexed */
77337
77338  /* Read the database schema. If an error occurs, leave an error message
77339  ** and code in pParse and return NULL. */
77340  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77341    return;
77342  }
77343
77344  if( pName1==0 ){
77345    reindexDatabases(pParse, 0);
77346    return;
77347  }else if( NEVER(pName2==0) || pName2->z==0 ){
77348    char *zColl;
77349    assert( pName1->z );
77350    zColl = sqlite3NameFromToken(pParse->db, pName1);
77351    if( !zColl ) return;
77352    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
77353    if( pColl ){
77354      reindexDatabases(pParse, zColl);
77355      sqlite3DbFree(db, zColl);
77356      return;
77357    }
77358    sqlite3DbFree(db, zColl);
77359  }
77360  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
77361  if( iDb<0 ) return;
77362  z = sqlite3NameFromToken(db, pObjName);
77363  if( z==0 ) return;
77364  zDb = db->aDb[iDb].zName;
77365  pTab = sqlite3FindTable(db, z, zDb);
77366  if( pTab ){
77367    reindexTable(pParse, pTab, 0);
77368    sqlite3DbFree(db, z);
77369    return;
77370  }
77371  pIndex = sqlite3FindIndex(db, z, zDb);
77372  sqlite3DbFree(db, z);
77373  if( pIndex ){
77374    sqlite3BeginWriteOperation(pParse, 0, iDb);
77375    sqlite3RefillIndex(pParse, pIndex, -1);
77376    return;
77377  }
77378  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
77379}
77380#endif
77381
77382/*
77383** Return a dynamicly allocated KeyInfo structure that can be used
77384** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
77385**
77386** If successful, a pointer to the new structure is returned. In this case
77387** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
77388** pointer. If an error occurs (out of memory or missing collation
77389** sequence), NULL is returned and the state of pParse updated to reflect
77390** the error.
77391*/
77392SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
77393  int i;
77394  int nCol = pIdx->nColumn;
77395  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
77396  sqlite3 *db = pParse->db;
77397  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
77398
77399  if( pKey ){
77400    pKey->db = pParse->db;
77401    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
77402    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
77403    for(i=0; i<nCol; i++){
77404      char *zColl = pIdx->azColl[i];
77405      assert( zColl );
77406      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
77407      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
77408    }
77409    pKey->nField = (u16)nCol;
77410  }
77411
77412  if( pParse->nErr ){
77413    sqlite3DbFree(db, pKey);
77414    pKey = 0;
77415  }
77416  return pKey;
77417}
77418
77419/************** End of build.c ***********************************************/
77420/************** Begin file callback.c ****************************************/
77421/*
77422** 2005 May 23
77423**
77424** The author disclaims copyright to this source code.  In place of
77425** a legal notice, here is a blessing:
77426**
77427**    May you do good and not evil.
77428**    May you find forgiveness for yourself and forgive others.
77429**    May you share freely, never taking more than you give.
77430**
77431*************************************************************************
77432**
77433** This file contains functions used to access the internal hash tables
77434** of user defined functions and collation sequences.
77435*/
77436
77437
77438/*
77439** Invoke the 'collation needed' callback to request a collation sequence
77440** in the encoding enc of name zName, length nName.
77441*/
77442static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
77443  assert( !db->xCollNeeded || !db->xCollNeeded16 );
77444  if( db->xCollNeeded ){
77445    char *zExternal = sqlite3DbStrDup(db, zName);
77446    if( !zExternal ) return;
77447    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
77448    sqlite3DbFree(db, zExternal);
77449  }
77450#ifndef SQLITE_OMIT_UTF16
77451  if( db->xCollNeeded16 ){
77452    char const *zExternal;
77453    sqlite3_value *pTmp = sqlite3ValueNew(db);
77454    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
77455    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
77456    if( zExternal ){
77457      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
77458    }
77459    sqlite3ValueFree(pTmp);
77460  }
77461#endif
77462}
77463
77464/*
77465** This routine is called if the collation factory fails to deliver a
77466** collation function in the best encoding but there may be other versions
77467** of this collation function (for other text encodings) available. Use one
77468** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
77469** possible.
77470*/
77471static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
77472  CollSeq *pColl2;
77473  char *z = pColl->zName;
77474  int i;
77475  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
77476  for(i=0; i<3; i++){
77477    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
77478    if( pColl2->xCmp!=0 ){
77479      memcpy(pColl, pColl2, sizeof(CollSeq));
77480      pColl->xDel = 0;         /* Do not copy the destructor */
77481      return SQLITE_OK;
77482    }
77483  }
77484  return SQLITE_ERROR;
77485}
77486
77487/*
77488** This function is responsible for invoking the collation factory callback
77489** or substituting a collation sequence of a different encoding when the
77490** requested collation sequence is not available in the desired encoding.
77491**
77492** If it is not NULL, then pColl must point to the database native encoding
77493** collation sequence with name zName, length nName.
77494**
77495** The return value is either the collation sequence to be used in database
77496** db for collation type name zName, length nName, or NULL, if no collation
77497** sequence can be found.
77498**
77499** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
77500*/
77501SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
77502  sqlite3* db,          /* The database connection */
77503  u8 enc,               /* The desired encoding for the collating sequence */
77504  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
77505  const char *zName     /* Collating sequence name */
77506){
77507  CollSeq *p;
77508
77509  p = pColl;
77510  if( !p ){
77511    p = sqlite3FindCollSeq(db, enc, zName, 0);
77512  }
77513  if( !p || !p->xCmp ){
77514    /* No collation sequence of this type for this encoding is registered.
77515    ** Call the collation factory to see if it can supply us with one.
77516    */
77517    callCollNeeded(db, enc, zName);
77518    p = sqlite3FindCollSeq(db, enc, zName, 0);
77519  }
77520  if( p && !p->xCmp && synthCollSeq(db, p) ){
77521    p = 0;
77522  }
77523  assert( !p || p->xCmp );
77524  return p;
77525}
77526
77527/*
77528** This routine is called on a collation sequence before it is used to
77529** check that it is defined. An undefined collation sequence exists when
77530** a database is loaded that contains references to collation sequences
77531** that have not been defined by sqlite3_create_collation() etc.
77532**
77533** If required, this routine calls the 'collation needed' callback to
77534** request a definition of the collating sequence. If this doesn't work,
77535** an equivalent collating sequence that uses a text encoding different
77536** from the main database is substituted, if one is available.
77537*/
77538SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
77539  if( pColl ){
77540    const char *zName = pColl->zName;
77541    sqlite3 *db = pParse->db;
77542    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
77543    if( !p ){
77544      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
77545      pParse->nErr++;
77546      return SQLITE_ERROR;
77547    }
77548    assert( p==pColl );
77549  }
77550  return SQLITE_OK;
77551}
77552
77553
77554
77555/*
77556** Locate and return an entry from the db.aCollSeq hash table. If the entry
77557** specified by zName and nName is not found and parameter 'create' is
77558** true, then create a new entry. Otherwise return NULL.
77559**
77560** Each pointer stored in the sqlite3.aCollSeq hash table contains an
77561** array of three CollSeq structures. The first is the collation sequence
77562** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
77563**
77564** Stored immediately after the three collation sequences is a copy of
77565** the collation sequence name. A pointer to this string is stored in
77566** each collation sequence structure.
77567*/
77568static CollSeq *findCollSeqEntry(
77569  sqlite3 *db,          /* Database connection */
77570  const char *zName,    /* Name of the collating sequence */
77571  int create            /* Create a new entry if true */
77572){
77573  CollSeq *pColl;
77574  int nName = sqlite3Strlen30(zName);
77575  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
77576
77577  if( 0==pColl && create ){
77578    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
77579    if( pColl ){
77580      CollSeq *pDel = 0;
77581      pColl[0].zName = (char*)&pColl[3];
77582      pColl[0].enc = SQLITE_UTF8;
77583      pColl[1].zName = (char*)&pColl[3];
77584      pColl[1].enc = SQLITE_UTF16LE;
77585      pColl[2].zName = (char*)&pColl[3];
77586      pColl[2].enc = SQLITE_UTF16BE;
77587      memcpy(pColl[0].zName, zName, nName);
77588      pColl[0].zName[nName] = 0;
77589      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
77590
77591      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
77592      ** return the pColl pointer to be deleted (because it wasn't added
77593      ** to the hash table).
77594      */
77595      assert( pDel==0 || pDel==pColl );
77596      if( pDel!=0 ){
77597        db->mallocFailed = 1;
77598        sqlite3DbFree(db, pDel);
77599        pColl = 0;
77600      }
77601    }
77602  }
77603  return pColl;
77604}
77605
77606/*
77607** Parameter zName points to a UTF-8 encoded string nName bytes long.
77608** Return the CollSeq* pointer for the collation sequence named zName
77609** for the encoding 'enc' from the database 'db'.
77610**
77611** If the entry specified is not found and 'create' is true, then create a
77612** new entry.  Otherwise return NULL.
77613**
77614** A separate function sqlite3LocateCollSeq() is a wrapper around
77615** this routine.  sqlite3LocateCollSeq() invokes the collation factory
77616** if necessary and generates an error message if the collating sequence
77617** cannot be found.
77618**
77619** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
77620*/
77621SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
77622  sqlite3 *db,
77623  u8 enc,
77624  const char *zName,
77625  int create
77626){
77627  CollSeq *pColl;
77628  if( zName ){
77629    pColl = findCollSeqEntry(db, zName, create);
77630  }else{
77631    pColl = db->pDfltColl;
77632  }
77633  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
77634  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
77635  if( pColl ) pColl += enc-1;
77636  return pColl;
77637}
77638
77639/* During the search for the best function definition, this procedure
77640** is called to test how well the function passed as the first argument
77641** matches the request for a function with nArg arguments in a system
77642** that uses encoding enc. The value returned indicates how well the
77643** request is matched. A higher value indicates a better match.
77644**
77645** The returned value is always between 0 and 6, as follows:
77646**
77647** 0: Not a match, or if nArg<0 and the function is has no implementation.
77648** 1: A variable arguments function that prefers UTF-8 when a UTF-16
77649**    encoding is requested, or vice versa.
77650** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
77651**    requested, or vice versa.
77652** 3: A variable arguments function using the same text encoding.
77653** 4: A function with the exact number of arguments requested that
77654**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
77655** 5: A function with the exact number of arguments requested that
77656**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
77657** 6: An exact match.
77658**
77659*/
77660static int matchQuality(FuncDef *p, int nArg, u8 enc){
77661  int match = 0;
77662  if( p->nArg==-1 || p->nArg==nArg
77663   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
77664  ){
77665    match = 1;
77666    if( p->nArg==nArg || nArg==-1 ){
77667      match = 4;
77668    }
77669    if( enc==p->iPrefEnc ){
77670      match += 2;
77671    }
77672    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
77673             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
77674      match += 1;
77675    }
77676  }
77677  return match;
77678}
77679
77680/*
77681** Search a FuncDefHash for a function with the given name.  Return
77682** a pointer to the matching FuncDef if found, or 0 if there is no match.
77683*/
77684static FuncDef *functionSearch(
77685  FuncDefHash *pHash,  /* Hash table to search */
77686  int h,               /* Hash of the name */
77687  const char *zFunc,   /* Name of function */
77688  int nFunc            /* Number of bytes in zFunc */
77689){
77690  FuncDef *p;
77691  for(p=pHash->a[h]; p; p=p->pHash){
77692    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
77693      return p;
77694    }
77695  }
77696  return 0;
77697}
77698
77699/*
77700** Insert a new FuncDef into a FuncDefHash hash table.
77701*/
77702SQLITE_PRIVATE void sqlite3FuncDefInsert(
77703  FuncDefHash *pHash,  /* The hash table into which to insert */
77704  FuncDef *pDef        /* The function definition to insert */
77705){
77706  FuncDef *pOther;
77707  int nName = sqlite3Strlen30(pDef->zName);
77708  u8 c1 = (u8)pDef->zName[0];
77709  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
77710  pOther = functionSearch(pHash, h, pDef->zName, nName);
77711  if( pOther ){
77712    assert( pOther!=pDef && pOther->pNext!=pDef );
77713    pDef->pNext = pOther->pNext;
77714    pOther->pNext = pDef;
77715  }else{
77716    pDef->pNext = 0;
77717    pDef->pHash = pHash->a[h];
77718    pHash->a[h] = pDef;
77719  }
77720}
77721
77722
77723
77724/*
77725** Locate a user function given a name, a number of arguments and a flag
77726** indicating whether the function prefers UTF-16 over UTF-8.  Return a
77727** pointer to the FuncDef structure that defines that function, or return
77728** NULL if the function does not exist.
77729**
77730** If the createFlag argument is true, then a new (blank) FuncDef
77731** structure is created and liked into the "db" structure if a
77732** no matching function previously existed.  When createFlag is true
77733** and the nArg parameter is -1, then only a function that accepts
77734** any number of arguments will be returned.
77735**
77736** If createFlag is false and nArg is -1, then the first valid
77737** function found is returned.  A function is valid if either xFunc
77738** or xStep is non-zero.
77739**
77740** If createFlag is false, then a function with the required name and
77741** number of arguments may be returned even if the eTextRep flag does not
77742** match that requested.
77743*/
77744SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
77745  sqlite3 *db,       /* An open database */
77746  const char *zName, /* Name of the function.  Not null-terminated */
77747  int nName,         /* Number of characters in the name */
77748  int nArg,          /* Number of arguments.  -1 means any number */
77749  u8 enc,            /* Preferred text encoding */
77750  int createFlag     /* Create new entry if true and does not otherwise exist */
77751){
77752  FuncDef *p;         /* Iterator variable */
77753  FuncDef *pBest = 0; /* Best match found so far */
77754  int bestScore = 0;  /* Score of best match */
77755  int h;              /* Hash value */
77756
77757
77758  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
77759  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
77760
77761  /* First search for a match amongst the application-defined functions.
77762  */
77763  p = functionSearch(&db->aFunc, h, zName, nName);
77764  while( p ){
77765    int score = matchQuality(p, nArg, enc);
77766    if( score>bestScore ){
77767      pBest = p;
77768      bestScore = score;
77769    }
77770    p = p->pNext;
77771  }
77772
77773  /* If no match is found, search the built-in functions.
77774  **
77775  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
77776  ** functions even if a prior app-defined function was found.  And give
77777  ** priority to built-in functions.
77778  **
77779  ** Except, if createFlag is true, that means that we are trying to
77780  ** install a new function.  Whatever FuncDef structure is returned will
77781  ** have fields overwritten with new information appropriate for the
77782  ** new function.  But the FuncDefs for built-in functions are read-only.
77783  ** So we must not search for built-ins when creating a new function.
77784  */
77785  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
77786    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
77787    bestScore = 0;
77788    p = functionSearch(pHash, h, zName, nName);
77789    while( p ){
77790      int score = matchQuality(p, nArg, enc);
77791      if( score>bestScore ){
77792        pBest = p;
77793        bestScore = score;
77794      }
77795      p = p->pNext;
77796    }
77797  }
77798
77799  /* If the createFlag parameter is true and the search did not reveal an
77800  ** exact match for the name, number of arguments and encoding, then add a
77801  ** new entry to the hash table and return it.
77802  */
77803  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
77804      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
77805    pBest->zName = (char *)&pBest[1];
77806    pBest->nArg = (u16)nArg;
77807    pBest->iPrefEnc = enc;
77808    memcpy(pBest->zName, zName, nName);
77809    pBest->zName[nName] = 0;
77810    sqlite3FuncDefInsert(&db->aFunc, pBest);
77811  }
77812
77813  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
77814    return pBest;
77815  }
77816  return 0;
77817}
77818
77819/*
77820** Free all resources held by the schema structure. The void* argument points
77821** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
77822** pointer itself, it just cleans up subsiduary resources (i.e. the contents
77823** of the schema hash tables).
77824**
77825** The Schema.cache_size variable is not cleared.
77826*/
77827SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
77828  Hash temp1;
77829  Hash temp2;
77830  HashElem *pElem;
77831  Schema *pSchema = (Schema *)p;
77832
77833  temp1 = pSchema->tblHash;
77834  temp2 = pSchema->trigHash;
77835  sqlite3HashInit(&pSchema->trigHash);
77836  sqlite3HashClear(&pSchema->idxHash);
77837  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
77838    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
77839  }
77840  sqlite3HashClear(&temp2);
77841  sqlite3HashInit(&pSchema->tblHash);
77842  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
77843    Table *pTab = sqliteHashData(pElem);
77844    sqlite3DeleteTable(0, pTab);
77845  }
77846  sqlite3HashClear(&temp1);
77847  sqlite3HashClear(&pSchema->fkeyHash);
77848  pSchema->pSeqTab = 0;
77849  pSchema->flags &= ~DB_SchemaLoaded;
77850}
77851
77852/*
77853** Find and return the schema associated with a BTree.  Create
77854** a new one if necessary.
77855*/
77856SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
77857  Schema * p;
77858  if( pBt ){
77859    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
77860  }else{
77861    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
77862  }
77863  if( !p ){
77864    db->mallocFailed = 1;
77865  }else if ( 0==p->file_format ){
77866    sqlite3HashInit(&p->tblHash);
77867    sqlite3HashInit(&p->idxHash);
77868    sqlite3HashInit(&p->trigHash);
77869    sqlite3HashInit(&p->fkeyHash);
77870    p->enc = SQLITE_UTF8;
77871  }
77872  return p;
77873}
77874
77875/************** End of callback.c ********************************************/
77876/************** Begin file delete.c ******************************************/
77877/*
77878** 2001 September 15
77879**
77880** The author disclaims copyright to this source code.  In place of
77881** a legal notice, here is a blessing:
77882**
77883**    May you do good and not evil.
77884**    May you find forgiveness for yourself and forgive others.
77885**    May you share freely, never taking more than you give.
77886**
77887*************************************************************************
77888** This file contains C code routines that are called by the parser
77889** in order to generate code for DELETE FROM statements.
77890*/
77891
77892/*
77893** Look up every table that is named in pSrc.  If any table is not found,
77894** add an error message to pParse->zErrMsg and return NULL.  If all tables
77895** are found, return a pointer to the last table.
77896*/
77897SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
77898  struct SrcList_item *pItem = pSrc->a;
77899  Table *pTab;
77900  assert( pItem && pSrc->nSrc==1 );
77901  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
77902  sqlite3DeleteTable(pParse->db, pItem->pTab);
77903  pItem->pTab = pTab;
77904  if( pTab ){
77905    pTab->nRef++;
77906  }
77907  if( sqlite3IndexedByLookup(pParse, pItem) ){
77908    pTab = 0;
77909  }
77910  return pTab;
77911}
77912
77913/*
77914** Check to make sure the given table is writable.  If it is not
77915** writable, generate an error message and return 1.  If it is
77916** writable return 0;
77917*/
77918SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
77919  /* A table is not writable under the following circumstances:
77920  **
77921  **   1) It is a virtual table and no implementation of the xUpdate method
77922  **      has been provided, or
77923  **   2) It is a system table (i.e. sqlite_master), this call is not
77924  **      part of a nested parse and writable_schema pragma has not
77925  **      been specified.
77926  **
77927  ** In either case leave an error message in pParse and return non-zero.
77928  */
77929  if( ( IsVirtual(pTab)
77930     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
77931   || ( (pTab->tabFlags & TF_Readonly)!=0
77932     && (pParse->db->flags & SQLITE_WriteSchema)==0
77933     && pParse->nested==0 )
77934  ){
77935    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
77936    return 1;
77937  }
77938
77939#ifndef SQLITE_OMIT_VIEW
77940  if( !viewOk && pTab->pSelect ){
77941    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
77942    return 1;
77943  }
77944#endif
77945  return 0;
77946}
77947
77948
77949#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
77950/*
77951** Evaluate a view and store its result in an ephemeral table.  The
77952** pWhere argument is an optional WHERE clause that restricts the
77953** set of rows in the view that are to be added to the ephemeral table.
77954*/
77955SQLITE_PRIVATE void sqlite3MaterializeView(
77956  Parse *pParse,       /* Parsing context */
77957  Table *pView,        /* View definition */
77958  Expr *pWhere,        /* Optional WHERE clause to be added */
77959  int iCur             /* Cursor number for ephemerial table */
77960){
77961  SelectDest dest;
77962  Select *pDup;
77963  sqlite3 *db = pParse->db;
77964
77965  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
77966  if( pWhere ){
77967    SrcList *pFrom;
77968
77969    pWhere = sqlite3ExprDup(db, pWhere, 0);
77970    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
77971    if( pFrom ){
77972      assert( pFrom->nSrc==1 );
77973      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
77974      pFrom->a[0].pSelect = pDup;
77975      assert( pFrom->a[0].pOn==0 );
77976      assert( pFrom->a[0].pUsing==0 );
77977    }else{
77978      sqlite3SelectDelete(db, pDup);
77979    }
77980    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
77981  }
77982  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
77983  sqlite3Select(pParse, pDup, &dest);
77984  sqlite3SelectDelete(db, pDup);
77985}
77986#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
77987
77988#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
77989/*
77990** Generate an expression tree to implement the WHERE, ORDER BY,
77991** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
77992**
77993**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
77994**                            \__________________________/
77995**                               pLimitWhere (pInClause)
77996*/
77997SQLITE_PRIVATE Expr *sqlite3LimitWhere(
77998  Parse *pParse,               /* The parser context */
77999  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
78000  Expr *pWhere,                /* The WHERE clause.  May be null */
78001  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
78002  Expr *pLimit,                /* The LIMIT clause.  May be null */
78003  Expr *pOffset,               /* The OFFSET clause.  May be null */
78004  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
78005){
78006  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
78007  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
78008  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
78009  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
78010  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
78011  Select *pSelect = NULL;      /* Complete SELECT tree */
78012
78013  /* Check that there isn't an ORDER BY without a LIMIT clause.
78014  */
78015  if( pOrderBy && (pLimit == 0) ) {
78016    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
78017    pParse->parseError = 1;
78018    goto limit_where_cleanup_2;
78019  }
78020
78021  /* We only need to generate a select expression if there
78022  ** is a limit/offset term to enforce.
78023  */
78024  if( pLimit == 0 ) {
78025    /* if pLimit is null, pOffset will always be null as well. */
78026    assert( pOffset == 0 );
78027    return pWhere;
78028  }
78029
78030  /* Generate a select expression tree to enforce the limit/offset
78031  ** term for the DELETE or UPDATE statement.  For example:
78032  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
78033  ** becomes:
78034  **   DELETE FROM table_a WHERE rowid IN (
78035  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
78036  **   );
78037  */
78038
78039  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
78040  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
78041  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
78042  if( pEList == 0 ) goto limit_where_cleanup_2;
78043
78044  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
78045  ** and the SELECT subtree. */
78046  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
78047  if( pSelectSrc == 0 ) {
78048    sqlite3ExprListDelete(pParse->db, pEList);
78049    goto limit_where_cleanup_2;
78050  }
78051
78052  /* generate the SELECT expression tree. */
78053  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
78054                             pOrderBy,0,pLimit,pOffset);
78055  if( pSelect == 0 ) return 0;
78056
78057  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
78058  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
78059  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
78060  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
78061  if( pInClause == 0 ) goto limit_where_cleanup_1;
78062
78063  pInClause->x.pSelect = pSelect;
78064  pInClause->flags |= EP_xIsSelect;
78065  sqlite3ExprSetHeight(pParse, pInClause);
78066  return pInClause;
78067
78068  /* something went wrong. clean up anything allocated. */
78069limit_where_cleanup_1:
78070  sqlite3SelectDelete(pParse->db, pSelect);
78071  return 0;
78072
78073limit_where_cleanup_2:
78074  sqlite3ExprDelete(pParse->db, pWhere);
78075  sqlite3ExprListDelete(pParse->db, pOrderBy);
78076  sqlite3ExprDelete(pParse->db, pLimit);
78077  sqlite3ExprDelete(pParse->db, pOffset);
78078  return 0;
78079}
78080#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
78081
78082/*
78083** Generate code for a DELETE FROM statement.
78084**
78085**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
78086**                 \________/       \________________/
78087**                  pTabList              pWhere
78088*/
78089SQLITE_PRIVATE void sqlite3DeleteFrom(
78090  Parse *pParse,         /* The parser context */
78091  SrcList *pTabList,     /* The table from which we should delete things */
78092  Expr *pWhere           /* The WHERE clause.  May be null */
78093){
78094  Vdbe *v;               /* The virtual database engine */
78095  Table *pTab;           /* The table from which records will be deleted */
78096  const char *zDb;       /* Name of database holding pTab */
78097  int end, addr = 0;     /* A couple addresses of generated code */
78098  int i;                 /* Loop counter */
78099  WhereInfo *pWInfo;     /* Information about the WHERE clause */
78100  Index *pIdx;           /* For looping over indices of the table */
78101  int iCur;              /* VDBE Cursor number for pTab */
78102  sqlite3 *db;           /* Main database structure */
78103  AuthContext sContext;  /* Authorization context */
78104  NameContext sNC;       /* Name context to resolve expressions in */
78105  int iDb;               /* Database number */
78106  int memCnt = -1;       /* Memory cell used for change counting */
78107  int rcauth;            /* Value returned by authorization callback */
78108
78109#ifndef SQLITE_OMIT_TRIGGER
78110  int isView;                  /* True if attempting to delete from a view */
78111  Trigger *pTrigger;           /* List of table triggers, if required */
78112#endif
78113
78114  memset(&sContext, 0, sizeof(sContext));
78115  db = pParse->db;
78116  if( pParse->nErr || db->mallocFailed ){
78117    goto delete_from_cleanup;
78118  }
78119  assert( pTabList->nSrc==1 );
78120
78121  /* Locate the table which we want to delete.  This table has to be
78122  ** put in an SrcList structure because some of the subroutines we
78123  ** will be calling are designed to work with multiple tables and expect
78124  ** an SrcList* parameter instead of just a Table* parameter.
78125  */
78126  pTab = sqlite3SrcListLookup(pParse, pTabList);
78127  if( pTab==0 )  goto delete_from_cleanup;
78128
78129  /* Figure out if we have any triggers and if the table being
78130  ** deleted from is a view
78131  */
78132#ifndef SQLITE_OMIT_TRIGGER
78133  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
78134  isView = pTab->pSelect!=0;
78135#else
78136# define pTrigger 0
78137# define isView 0
78138#endif
78139#ifdef SQLITE_OMIT_VIEW
78140# undef isView
78141# define isView 0
78142#endif
78143
78144  /* If pTab is really a view, make sure it has been initialized.
78145  */
78146  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78147    goto delete_from_cleanup;
78148  }
78149
78150  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
78151    goto delete_from_cleanup;
78152  }
78153  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78154  assert( iDb<db->nDb );
78155  zDb = db->aDb[iDb].zName;
78156  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
78157  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
78158  if( rcauth==SQLITE_DENY ){
78159    goto delete_from_cleanup;
78160  }
78161  assert(!isView || pTrigger);
78162
78163  /* Assign  cursor number to the table and all its indices.
78164  */
78165  assert( pTabList->nSrc==1 );
78166  iCur = pTabList->a[0].iCursor = pParse->nTab++;
78167  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78168    pParse->nTab++;
78169  }
78170
78171  /* Start the view context
78172  */
78173  if( isView ){
78174    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
78175  }
78176
78177  /* Begin generating code.
78178  */
78179  v = sqlite3GetVdbe(pParse);
78180  if( v==0 ){
78181    goto delete_from_cleanup;
78182  }
78183  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
78184  sqlite3BeginWriteOperation(pParse, 1, iDb);
78185
78186  /* If we are trying to delete from a view, realize that view into
78187  ** a ephemeral table.
78188  */
78189#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
78190  if( isView ){
78191    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
78192  }
78193#endif
78194
78195  /* Resolve the column names in the WHERE clause.
78196  */
78197  memset(&sNC, 0, sizeof(sNC));
78198  sNC.pParse = pParse;
78199  sNC.pSrcList = pTabList;
78200  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
78201    goto delete_from_cleanup;
78202  }
78203
78204  /* Initialize the counter of the number of rows deleted, if
78205  ** we are counting rows.
78206  */
78207  if( db->flags & SQLITE_CountRows ){
78208    memCnt = ++pParse->nMem;
78209    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
78210  }
78211
78212#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
78213  /* Special case: A DELETE without a WHERE clause deletes everything.
78214  ** It is easier just to erase the whole table. Prior to version 3.6.5,
78215  ** this optimization caused the row change count (the value returned by
78216  ** API function sqlite3_count_changes) to be set incorrectly.  */
78217  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
78218   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
78219  ){
78220    assert( !isView );
78221    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
78222                      pTab->zName, P4_STATIC);
78223    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78224      assert( pIdx->pSchema==pTab->pSchema );
78225      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
78226    }
78227  }else
78228#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
78229  /* The usual case: There is a WHERE clause so we have to scan through
78230  ** the table and pick which records to delete.
78231  */
78232  {
78233    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
78234    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
78235    int regRowid;                   /* Actual register containing rowids */
78236
78237    /* Collect rowids of every row to be deleted.
78238    */
78239    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
78240    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
78241    if( pWInfo==0 ) goto delete_from_cleanup;
78242    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
78243    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
78244    if( db->flags & SQLITE_CountRows ){
78245      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
78246    }
78247    sqlite3WhereEnd(pWInfo);
78248
78249    /* Delete every item whose key was written to the list during the
78250    ** database scan.  We have to delete items after the scan is complete
78251    ** because deleting an item can change the scan order.  */
78252    end = sqlite3VdbeMakeLabel(v);
78253
78254    /* Unless this is a view, open cursors for the table we are
78255    ** deleting from and all its indices. If this is a view, then the
78256    ** only effect this statement has is to fire the INSTEAD OF
78257    ** triggers.  */
78258    if( !isView ){
78259      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
78260    }
78261
78262    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
78263
78264    /* Delete the row */
78265#ifndef SQLITE_OMIT_VIRTUALTABLE
78266    if( IsVirtual(pTab) ){
78267      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
78268      sqlite3VtabMakeWritable(pParse, pTab);
78269      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
78270      sqlite3MayAbort(pParse);
78271    }else
78272#endif
78273    {
78274      int count = (pParse->nested==0);    /* True to count changes */
78275      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
78276    }
78277
78278    /* End of the delete loop */
78279    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
78280    sqlite3VdbeResolveLabel(v, end);
78281
78282    /* Close the cursors open on the table and its indexes. */
78283    if( !isView && !IsVirtual(pTab) ){
78284      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
78285        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
78286      }
78287      sqlite3VdbeAddOp1(v, OP_Close, iCur);
78288    }
78289  }
78290
78291  /* Update the sqlite_sequence table by storing the content of the
78292  ** maximum rowid counter values recorded while inserting into
78293  ** autoincrement tables.
78294  */
78295  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
78296    sqlite3AutoincrementEnd(pParse);
78297  }
78298
78299  /* Return the number of rows that were deleted. If this routine is
78300  ** generating code because of a call to sqlite3NestedParse(), do not
78301  ** invoke the callback function.
78302  */
78303  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
78304    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
78305    sqlite3VdbeSetNumCols(v, 1);
78306    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
78307  }
78308
78309delete_from_cleanup:
78310  sqlite3AuthContextPop(&sContext);
78311  sqlite3SrcListDelete(db, pTabList);
78312  sqlite3ExprDelete(db, pWhere);
78313  return;
78314}
78315/* Make sure "isView" and other macros defined above are undefined. Otherwise
78316** thely may interfere with compilation of other functions in this file
78317** (or in another file, if this file becomes part of the amalgamation).  */
78318#ifdef isView
78319 #undef isView
78320#endif
78321#ifdef pTrigger
78322 #undef pTrigger
78323#endif
78324
78325/*
78326** This routine generates VDBE code that causes a single row of a
78327** single table to be deleted.
78328**
78329** The VDBE must be in a particular state when this routine is called.
78330** These are the requirements:
78331**
78332**   1.  A read/write cursor pointing to pTab, the table containing the row
78333**       to be deleted, must be opened as cursor number $iCur.
78334**
78335**   2.  Read/write cursors for all indices of pTab must be open as
78336**       cursor number base+i for the i-th index.
78337**
78338**   3.  The record number of the row to be deleted must be stored in
78339**       memory cell iRowid.
78340**
78341** This routine generates code to remove both the table record and all
78342** index entries that point to that record.
78343*/
78344SQLITE_PRIVATE void sqlite3GenerateRowDelete(
78345  Parse *pParse,     /* Parsing context */
78346  Table *pTab,       /* Table containing the row to be deleted */
78347  int iCur,          /* Cursor number for the table */
78348  int iRowid,        /* Memory cell that contains the rowid to delete */
78349  int count,         /* If non-zero, increment the row change counter */
78350  Trigger *pTrigger, /* List of triggers to (potentially) fire */
78351  int onconf         /* Default ON CONFLICT policy for triggers */
78352){
78353  Vdbe *v = pParse->pVdbe;        /* Vdbe */
78354  int iOld = 0;                   /* First register in OLD.* array */
78355  int iLabel;                     /* Label resolved to end of generated code */
78356
78357  /* Vdbe is guaranteed to have been allocated by this stage. */
78358  assert( v );
78359
78360  /* Seek cursor iCur to the row to delete. If this row no longer exists
78361  ** (this can happen if a trigger program has already deleted it), do
78362  ** not attempt to delete it or fire any DELETE triggers.  */
78363  iLabel = sqlite3VdbeMakeLabel(v);
78364  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
78365
78366  /* If there are any triggers to fire, allocate a range of registers to
78367  ** use for the old.* references in the triggers.  */
78368  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
78369    u32 mask;                     /* Mask of OLD.* columns in use */
78370    int iCol;                     /* Iterator used while populating OLD.* */
78371
78372    /* TODO: Could use temporary registers here. Also could attempt to
78373    ** avoid copying the contents of the rowid register.  */
78374    mask = sqlite3TriggerColmask(
78375        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
78376    );
78377    mask |= sqlite3FkOldmask(pParse, pTab);
78378    iOld = pParse->nMem+1;
78379    pParse->nMem += (1 + pTab->nCol);
78380
78381    /* Populate the OLD.* pseudo-table register array. These values will be
78382    ** used by any BEFORE and AFTER triggers that exist.  */
78383    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
78384    for(iCol=0; iCol<pTab->nCol; iCol++){
78385      if( mask==0xffffffff || mask&(1<<iCol) ){
78386        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
78387      }
78388    }
78389
78390    /* Invoke BEFORE DELETE trigger programs. */
78391    sqlite3CodeRowTrigger(pParse, pTrigger,
78392        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
78393    );
78394
78395    /* Seek the cursor to the row to be deleted again. It may be that
78396    ** the BEFORE triggers coded above have already removed the row
78397    ** being deleted. Do not attempt to delete the row a second time, and
78398    ** do not fire AFTER triggers.  */
78399    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
78400
78401    /* Do FK processing. This call checks that any FK constraints that
78402    ** refer to this table (i.e. constraints attached to other tables)
78403    ** are not violated by deleting this row.  */
78404    sqlite3FkCheck(pParse, pTab, iOld, 0);
78405  }
78406
78407  /* Delete the index and table entries. Skip this step if pTab is really
78408  ** a view (in which case the only effect of the DELETE statement is to
78409  ** fire the INSTEAD OF triggers).  */
78410  if( pTab->pSelect==0 ){
78411    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
78412    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
78413    if( count ){
78414      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
78415    }
78416  }
78417
78418  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
78419  ** handle rows (possibly in other tables) that refer via a foreign key
78420  ** to the row just deleted. */
78421  sqlite3FkActions(pParse, pTab, 0, iOld);
78422
78423  /* Invoke AFTER DELETE trigger programs. */
78424  sqlite3CodeRowTrigger(pParse, pTrigger,
78425      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
78426  );
78427
78428  /* Jump here if the row had already been deleted before any BEFORE
78429  ** trigger programs were invoked. Or if a trigger program throws a
78430  ** RAISE(IGNORE) exception.  */
78431  sqlite3VdbeResolveLabel(v, iLabel);
78432}
78433
78434/*
78435** This routine generates VDBE code that causes the deletion of all
78436** index entries associated with a single row of a single table.
78437**
78438** The VDBE must be in a particular state when this routine is called.
78439** These are the requirements:
78440**
78441**   1.  A read/write cursor pointing to pTab, the table containing the row
78442**       to be deleted, must be opened as cursor number "iCur".
78443**
78444**   2.  Read/write cursors for all indices of pTab must be open as
78445**       cursor number iCur+i for the i-th index.
78446**
78447**   3.  The "iCur" cursor must be pointing to the row that is to be
78448**       deleted.
78449*/
78450SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
78451  Parse *pParse,     /* Parsing and code generating context */
78452  Table *pTab,       /* Table containing the row to be deleted */
78453  int iCur,          /* Cursor number for the table */
78454  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
78455){
78456  int i;
78457  Index *pIdx;
78458  int r1;
78459
78460  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
78461    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
78462    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
78463    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
78464  }
78465}
78466
78467/*
78468** Generate code that will assemble an index key and put it in register
78469** regOut.  The key with be for index pIdx which is an index on pTab.
78470** iCur is the index of a cursor open on the pTab table and pointing to
78471** the entry that needs indexing.
78472**
78473** Return a register number which is the first in a block of
78474** registers that holds the elements of the index key.  The
78475** block of registers has already been deallocated by the time
78476** this routine returns.
78477*/
78478SQLITE_PRIVATE int sqlite3GenerateIndexKey(
78479  Parse *pParse,     /* Parsing context */
78480  Index *pIdx,       /* The index for which to generate a key */
78481  int iCur,          /* Cursor number for the pIdx->pTable table */
78482  int regOut,        /* Write the new index key to this register */
78483  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
78484){
78485  Vdbe *v = pParse->pVdbe;
78486  int j;
78487  Table *pTab = pIdx->pTable;
78488  int regBase;
78489  int nCol;
78490
78491  nCol = pIdx->nColumn;
78492  regBase = sqlite3GetTempRange(pParse, nCol+1);
78493  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
78494  for(j=0; j<nCol; j++){
78495    int idx = pIdx->aiColumn[j];
78496    if( idx==pTab->iPKey ){
78497      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
78498    }else{
78499      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
78500      sqlite3ColumnDefault(v, pTab, idx, -1);
78501    }
78502  }
78503  if( doMakeRec ){
78504    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
78505    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
78506  }
78507  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
78508  return regBase;
78509}
78510
78511/************** End of delete.c **********************************************/
78512/************** Begin file func.c ********************************************/
78513/*
78514** 2002 February 23
78515**
78516** The author disclaims copyright to this source code.  In place of
78517** a legal notice, here is a blessing:
78518**
78519**    May you do good and not evil.
78520**    May you find forgiveness for yourself and forgive others.
78521**    May you share freely, never taking more than you give.
78522**
78523*************************************************************************
78524** This file contains the C functions that implement various SQL
78525** functions of SQLite.
78526**
78527** There is only one exported symbol in this file - the function
78528** sqliteRegisterBuildinFunctions() found at the bottom of the file.
78529** All other code has file scope.
78530*/
78531
78532/*
78533** Return the collating function associated with a function.
78534*/
78535static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
78536  return context->pColl;
78537}
78538
78539/*
78540** Implementation of the non-aggregate min() and max() functions
78541*/
78542static void minmaxFunc(
78543  sqlite3_context *context,
78544  int argc,
78545  sqlite3_value **argv
78546){
78547  int i;
78548  int mask;    /* 0 for min() or 0xffffffff for max() */
78549  int iBest;
78550  CollSeq *pColl;
78551
78552  assert( argc>1 );
78553  mask = sqlite3_user_data(context)==0 ? 0 : -1;
78554  pColl = sqlite3GetFuncCollSeq(context);
78555  assert( pColl );
78556  assert( mask==-1 || mask==0 );
78557  iBest = 0;
78558  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78559  for(i=1; i<argc; i++){
78560    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
78561    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
78562      testcase( mask==0 );
78563      iBest = i;
78564    }
78565  }
78566  sqlite3_result_value(context, argv[iBest]);
78567}
78568
78569/*
78570** Return the type of the argument.
78571*/
78572static void typeofFunc(
78573  sqlite3_context *context,
78574  int NotUsed,
78575  sqlite3_value **argv
78576){
78577  const char *z = 0;
78578  UNUSED_PARAMETER(NotUsed);
78579  switch( sqlite3_value_type(argv[0]) ){
78580    case SQLITE_INTEGER: z = "integer"; break;
78581    case SQLITE_TEXT:    z = "text";    break;
78582    case SQLITE_FLOAT:   z = "real";    break;
78583    case SQLITE_BLOB:    z = "blob";    break;
78584    default:             z = "null";    break;
78585  }
78586  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
78587}
78588
78589
78590/*
78591** Implementation of the length() function
78592*/
78593static void lengthFunc(
78594  sqlite3_context *context,
78595  int argc,
78596  sqlite3_value **argv
78597){
78598  int len;
78599
78600  assert( argc==1 );
78601  UNUSED_PARAMETER(argc);
78602  switch( sqlite3_value_type(argv[0]) ){
78603    case SQLITE_BLOB:
78604    case SQLITE_INTEGER:
78605    case SQLITE_FLOAT: {
78606      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
78607      break;
78608    }
78609    case SQLITE_TEXT: {
78610      const unsigned char *z = sqlite3_value_text(argv[0]);
78611      if( z==0 ) return;
78612      len = 0;
78613      while( *z ){
78614        len++;
78615        SQLITE_SKIP_UTF8(z);
78616      }
78617      sqlite3_result_int(context, len);
78618      break;
78619    }
78620    default: {
78621      sqlite3_result_null(context);
78622      break;
78623    }
78624  }
78625}
78626
78627/*
78628** Implementation of the abs() function.
78629**
78630** IMP: R-23979-26855 The abs(X) function returns the absolute value of
78631** the numeric argument X.
78632*/
78633static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78634  assert( argc==1 );
78635  UNUSED_PARAMETER(argc);
78636  switch( sqlite3_value_type(argv[0]) ){
78637    case SQLITE_INTEGER: {
78638      i64 iVal = sqlite3_value_int64(argv[0]);
78639      if( iVal<0 ){
78640        if( (iVal<<1)==0 ){
78641          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
78642          ** abs(X) throws an integer overflow error since there is no
78643          ** equivalent positive 64-bit two complement value. */
78644          sqlite3_result_error(context, "integer overflow", -1);
78645          return;
78646        }
78647        iVal = -iVal;
78648      }
78649      sqlite3_result_int64(context, iVal);
78650      break;
78651    }
78652    case SQLITE_NULL: {
78653      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
78654      sqlite3_result_null(context);
78655      break;
78656    }
78657    default: {
78658      /* Because sqlite3_value_double() returns 0.0 if the argument is not
78659      ** something that can be converted into a number, we have:
78660      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
78661      ** cannot be converted to a numeric value.
78662      */
78663      double rVal = sqlite3_value_double(argv[0]);
78664      if( rVal<0 ) rVal = -rVal;
78665      sqlite3_result_double(context, rVal);
78666      break;
78667    }
78668  }
78669}
78670
78671/*
78672** Implementation of the substr() function.
78673**
78674** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
78675** p1 is 1-indexed.  So substr(x,1,1) returns the first character
78676** of x.  If x is text, then we actually count UTF-8 characters.
78677** If x is a blob, then we count bytes.
78678**
78679** If p1 is negative, then we begin abs(p1) from the end of x[].
78680**
78681** If p2 is negative, return the p2 characters preceeding p1.
78682*/
78683static void substrFunc(
78684  sqlite3_context *context,
78685  int argc,
78686  sqlite3_value **argv
78687){
78688  const unsigned char *z;
78689  const unsigned char *z2;
78690  int len;
78691  int p0type;
78692  i64 p1, p2;
78693  int negP2 = 0;
78694
78695  assert( argc==3 || argc==2 );
78696  if( sqlite3_value_type(argv[1])==SQLITE_NULL
78697   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
78698  ){
78699    return;
78700  }
78701  p0type = sqlite3_value_type(argv[0]);
78702  p1 = sqlite3_value_int(argv[1]);
78703  if( p0type==SQLITE_BLOB ){
78704    len = sqlite3_value_bytes(argv[0]);
78705    z = sqlite3_value_blob(argv[0]);
78706    if( z==0 ) return;
78707    assert( len==sqlite3_value_bytes(argv[0]) );
78708  }else{
78709    z = sqlite3_value_text(argv[0]);
78710    if( z==0 ) return;
78711    len = 0;
78712    if( p1<0 ){
78713      for(z2=z; *z2; len++){
78714        SQLITE_SKIP_UTF8(z2);
78715      }
78716    }
78717  }
78718  if( argc==3 ){
78719    p2 = sqlite3_value_int(argv[2]);
78720    if( p2<0 ){
78721      p2 = -p2;
78722      negP2 = 1;
78723    }
78724  }else{
78725    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
78726  }
78727  if( p1<0 ){
78728    p1 += len;
78729    if( p1<0 ){
78730      p2 += p1;
78731      if( p2<0 ) p2 = 0;
78732      p1 = 0;
78733    }
78734  }else if( p1>0 ){
78735    p1--;
78736  }else if( p2>0 ){
78737    p2--;
78738  }
78739  if( negP2 ){
78740    p1 -= p2;
78741    if( p1<0 ){
78742      p2 += p1;
78743      p1 = 0;
78744    }
78745  }
78746  assert( p1>=0 && p2>=0 );
78747  if( p0type!=SQLITE_BLOB ){
78748    while( *z && p1 ){
78749      SQLITE_SKIP_UTF8(z);
78750      p1--;
78751    }
78752    for(z2=z; *z2 && p2; p2--){
78753      SQLITE_SKIP_UTF8(z2);
78754    }
78755    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
78756  }else{
78757    if( p1+p2>len ){
78758      p2 = len-p1;
78759      if( p2<0 ) p2 = 0;
78760    }
78761    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
78762  }
78763}
78764
78765/*
78766** Implementation of the round() function
78767*/
78768#ifndef SQLITE_OMIT_FLOATING_POINT
78769static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78770  int n = 0;
78771  double r;
78772  char *zBuf;
78773  assert( argc==1 || argc==2 );
78774  if( argc==2 ){
78775    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
78776    n = sqlite3_value_int(argv[1]);
78777    if( n>30 ) n = 30;
78778    if( n<0 ) n = 0;
78779  }
78780  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
78781  r = sqlite3_value_double(argv[0]);
78782  /* If Y==0 and X will fit in a 64-bit int,
78783  ** handle the rounding directly,
78784  ** otherwise use printf.
78785  */
78786  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
78787    r = (double)((sqlite_int64)(r+0.5));
78788  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
78789    r = -(double)((sqlite_int64)((-r)+0.5));
78790  }else{
78791    zBuf = sqlite3_mprintf("%.*f",n,r);
78792    if( zBuf==0 ){
78793      sqlite3_result_error_nomem(context);
78794      return;
78795    }
78796    sqlite3AtoF(zBuf, &r);
78797    sqlite3_free(zBuf);
78798  }
78799  sqlite3_result_double(context, r);
78800}
78801#endif
78802
78803/*
78804** Allocate nByte bytes of space using sqlite3_malloc(). If the
78805** allocation fails, call sqlite3_result_error_nomem() to notify
78806** the database handle that malloc() has failed and return NULL.
78807** If nByte is larger than the maximum string or blob length, then
78808** raise an SQLITE_TOOBIG exception and return NULL.
78809*/
78810static void *contextMalloc(sqlite3_context *context, i64 nByte){
78811  char *z;
78812  sqlite3 *db = sqlite3_context_db_handle(context);
78813  assert( nByte>0 );
78814  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
78815  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
78816  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78817    sqlite3_result_error_toobig(context);
78818    z = 0;
78819  }else{
78820    z = sqlite3Malloc((int)nByte);
78821    if( !z ){
78822      sqlite3_result_error_nomem(context);
78823    }
78824  }
78825  return z;
78826}
78827
78828/*
78829** Implementation of the upper() and lower() SQL functions.
78830*/
78831static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78832  char *z1;
78833  const char *z2;
78834  int i, n;
78835  UNUSED_PARAMETER(argc);
78836  z2 = (char*)sqlite3_value_text(argv[0]);
78837  n = sqlite3_value_bytes(argv[0]);
78838  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
78839  assert( z2==(char*)sqlite3_value_text(argv[0]) );
78840  if( z2 ){
78841    z1 = contextMalloc(context, ((i64)n)+1);
78842    if( z1 ){
78843      memcpy(z1, z2, n+1);
78844      for(i=0; z1[i]; i++){
78845        z1[i] = (char)sqlite3Toupper(z1[i]);
78846      }
78847      sqlite3_result_text(context, z1, -1, sqlite3_free);
78848    }
78849  }
78850}
78851static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
78852  u8 *z1;
78853  const char *z2;
78854  int i, n;
78855  UNUSED_PARAMETER(argc);
78856  z2 = (char*)sqlite3_value_text(argv[0]);
78857  n = sqlite3_value_bytes(argv[0]);
78858  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
78859  assert( z2==(char*)sqlite3_value_text(argv[0]) );
78860  if( z2 ){
78861    z1 = contextMalloc(context, ((i64)n)+1);
78862    if( z1 ){
78863      memcpy(z1, z2, n+1);
78864      for(i=0; z1[i]; i++){
78865        z1[i] = sqlite3Tolower(z1[i]);
78866      }
78867      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
78868    }
78869  }
78870}
78871
78872
78873#if 0  /* This function is never used. */
78874/*
78875** The COALESCE() and IFNULL() functions used to be implemented as shown
78876** here.  But now they are implemented as VDBE code so that unused arguments
78877** do not have to be computed.  This legacy implementation is retained as
78878** comment.
78879*/
78880/*
78881** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
78882** All three do the same thing.  They return the first non-NULL
78883** argument.
78884*/
78885static void ifnullFunc(
78886  sqlite3_context *context,
78887  int argc,
78888  sqlite3_value **argv
78889){
78890  int i;
78891  for(i=0; i<argc; i++){
78892    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
78893      sqlite3_result_value(context, argv[i]);
78894      break;
78895    }
78896  }
78897}
78898#endif /* NOT USED */
78899#define ifnullFunc versionFunc   /* Substitute function - never called */
78900
78901/*
78902** Implementation of random().  Return a random integer.
78903*/
78904static void randomFunc(
78905  sqlite3_context *context,
78906  int NotUsed,
78907  sqlite3_value **NotUsed2
78908){
78909  sqlite_int64 r;
78910  UNUSED_PARAMETER2(NotUsed, NotUsed2);
78911  sqlite3_randomness(sizeof(r), &r);
78912  if( r<0 ){
78913    /* We need to prevent a random number of 0x8000000000000000
78914    ** (or -9223372036854775808) since when you do abs() of that
78915    ** number of you get the same value back again.  To do this
78916    ** in a way that is testable, mask the sign bit off of negative
78917    ** values, resulting in a positive value.  Then take the
78918    ** 2s complement of that positive value.  The end result can
78919    ** therefore be no less than -9223372036854775807.
78920    */
78921    r = -(r ^ (((sqlite3_int64)1)<<63));
78922  }
78923  sqlite3_result_int64(context, r);
78924}
78925
78926/*
78927** Implementation of randomblob(N).  Return a random blob
78928** that is N bytes long.
78929*/
78930static void randomBlob(
78931  sqlite3_context *context,
78932  int argc,
78933  sqlite3_value **argv
78934){
78935  int n;
78936  unsigned char *p;
78937  assert( argc==1 );
78938  UNUSED_PARAMETER(argc);
78939  n = sqlite3_value_int(argv[0]);
78940  if( n<1 ){
78941    n = 1;
78942  }
78943  p = contextMalloc(context, n);
78944  if( p ){
78945    sqlite3_randomness(n, p);
78946    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
78947  }
78948}
78949
78950/*
78951** Implementation of the last_insert_rowid() SQL function.  The return
78952** value is the same as the sqlite3_last_insert_rowid() API function.
78953*/
78954static void last_insert_rowid(
78955  sqlite3_context *context,
78956  int NotUsed,
78957  sqlite3_value **NotUsed2
78958){
78959  sqlite3 *db = sqlite3_context_db_handle(context);
78960  UNUSED_PARAMETER2(NotUsed, NotUsed2);
78961  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
78962  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
78963  ** function. */
78964  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
78965}
78966
78967/*
78968** Implementation of the changes() SQL function.
78969**
78970** IMP: R-62073-11209 The changes() SQL function is a wrapper
78971** around the sqlite3_changes() C/C++ function and hence follows the same
78972** rules for counting changes.
78973*/
78974static void changes(
78975  sqlite3_context *context,
78976  int NotUsed,
78977  sqlite3_value **NotUsed2
78978){
78979  sqlite3 *db = sqlite3_context_db_handle(context);
78980  UNUSED_PARAMETER2(NotUsed, NotUsed2);
78981  sqlite3_result_int(context, sqlite3_changes(db));
78982}
78983
78984/*
78985** Implementation of the total_changes() SQL function.  The return value is
78986** the same as the sqlite3_total_changes() API function.
78987*/
78988static void total_changes(
78989  sqlite3_context *context,
78990  int NotUsed,
78991  sqlite3_value **NotUsed2
78992){
78993  sqlite3 *db = sqlite3_context_db_handle(context);
78994  UNUSED_PARAMETER2(NotUsed, NotUsed2);
78995  /* IMP: R-52756-41993 This function is a wrapper around the
78996  ** sqlite3_total_changes() C/C++ interface. */
78997  sqlite3_result_int(context, sqlite3_total_changes(db));
78998}
78999
79000/*
79001** A structure defining how to do GLOB-style comparisons.
79002*/
79003struct compareInfo {
79004  u8 matchAll;
79005  u8 matchOne;
79006  u8 matchSet;
79007  u8 noCase;
79008};
79009
79010/*
79011** For LIKE and GLOB matching on EBCDIC machines, assume that every
79012** character is exactly one byte in size.  Also, all characters are
79013** able to participate in upper-case-to-lower-case mappings in EBCDIC
79014** whereas only characters less than 0x80 do in ASCII.
79015*/
79016#if defined(SQLITE_EBCDIC)
79017# define sqlite3Utf8Read(A,C)    (*(A++))
79018# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
79019#else
79020# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
79021#endif
79022
79023static const struct compareInfo globInfo = { '*', '?', '[', 0 };
79024/* The correct SQL-92 behavior is for the LIKE operator to ignore
79025** case.  Thus  'a' LIKE 'A' would be true. */
79026static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
79027/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
79028** is case sensitive causing 'a' LIKE 'A' to be false */
79029static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
79030
79031/*
79032** Compare two UTF-8 strings for equality where the first string can
79033** potentially be a "glob" expression.  Return true (1) if they
79034** are the same and false (0) if they are different.
79035**
79036** Globbing rules:
79037**
79038**      '*'       Matches any sequence of zero or more characters.
79039**
79040**      '?'       Matches exactly one character.
79041**
79042**     [...]      Matches one character from the enclosed list of
79043**                characters.
79044**
79045**     [^...]     Matches one character not in the enclosed list.
79046**
79047** With the [...] and [^...] matching, a ']' character can be included
79048** in the list by making it the first character after '[' or '^'.  A
79049** range of characters can be specified using '-'.  Example:
79050** "[a-z]" matches any single lower-case letter.  To match a '-', make
79051** it the last character in the list.
79052**
79053** This routine is usually quick, but can be N**2 in the worst case.
79054**
79055** Hints: to match '*' or '?', put them in "[]".  Like this:
79056**
79057**         abc[*]xyz        Matches "abc*xyz" only
79058*/
79059static int patternCompare(
79060  const u8 *zPattern,              /* The glob pattern */
79061  const u8 *zString,               /* The string to compare against the glob */
79062  const struct compareInfo *pInfo, /* Information about how to do the compare */
79063  const int esc                    /* The escape character */
79064){
79065  int c, c2;
79066  int invert;
79067  int seen;
79068  u8 matchOne = pInfo->matchOne;
79069  u8 matchAll = pInfo->matchAll;
79070  u8 matchSet = pInfo->matchSet;
79071  u8 noCase = pInfo->noCase;
79072  int prevEscape = 0;     /* True if the previous character was 'escape' */
79073
79074  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
79075    if( !prevEscape && c==matchAll ){
79076      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
79077               || c == matchOne ){
79078        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
79079          return 0;
79080        }
79081      }
79082      if( c==0 ){
79083        return 1;
79084      }else if( c==esc ){
79085        c = sqlite3Utf8Read(zPattern, &zPattern);
79086        if( c==0 ){
79087          return 0;
79088        }
79089      }else if( c==matchSet ){
79090        assert( esc==0 );         /* This is GLOB, not LIKE */
79091        assert( matchSet<0x80 );  /* '[' is a single-byte character */
79092        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
79093          SQLITE_SKIP_UTF8(zString);
79094        }
79095        return *zString!=0;
79096      }
79097      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
79098        if( noCase ){
79099          GlogUpperToLower(c2);
79100          GlogUpperToLower(c);
79101          while( c2 != 0 && c2 != c ){
79102            c2 = sqlite3Utf8Read(zString, &zString);
79103            GlogUpperToLower(c2);
79104          }
79105        }else{
79106          while( c2 != 0 && c2 != c ){
79107            c2 = sqlite3Utf8Read(zString, &zString);
79108          }
79109        }
79110        if( c2==0 ) return 0;
79111        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
79112      }
79113      return 0;
79114    }else if( !prevEscape && c==matchOne ){
79115      if( sqlite3Utf8Read(zString, &zString)==0 ){
79116        return 0;
79117      }
79118    }else if( c==matchSet ){
79119      int prior_c = 0;
79120      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
79121      seen = 0;
79122      invert = 0;
79123      c = sqlite3Utf8Read(zString, &zString);
79124      if( c==0 ) return 0;
79125      c2 = sqlite3Utf8Read(zPattern, &zPattern);
79126      if( c2=='^' ){
79127        invert = 1;
79128        c2 = sqlite3Utf8Read(zPattern, &zPattern);
79129      }
79130      if( c2==']' ){
79131        if( c==']' ) seen = 1;
79132        c2 = sqlite3Utf8Read(zPattern, &zPattern);
79133      }
79134      while( c2 && c2!=']' ){
79135        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
79136          c2 = sqlite3Utf8Read(zPattern, &zPattern);
79137          if( c>=prior_c && c<=c2 ) seen = 1;
79138          prior_c = 0;
79139        }else{
79140          if( c==c2 ){
79141            seen = 1;
79142          }
79143          prior_c = c2;
79144        }
79145        c2 = sqlite3Utf8Read(zPattern, &zPattern);
79146      }
79147      if( c2==0 || (seen ^ invert)==0 ){
79148        return 0;
79149      }
79150    }else if( esc==c && !prevEscape ){
79151      prevEscape = 1;
79152    }else{
79153      c2 = sqlite3Utf8Read(zString, &zString);
79154      if( noCase ){
79155        GlogUpperToLower(c);
79156        GlogUpperToLower(c2);
79157      }
79158      if( c!=c2 ){
79159        return 0;
79160      }
79161      prevEscape = 0;
79162    }
79163  }
79164  return *zString==0;
79165}
79166
79167/*
79168** Count the number of times that the LIKE operator (or GLOB which is
79169** just a variation of LIKE) gets called.  This is used for testing
79170** only.
79171*/
79172#ifdef SQLITE_TEST
79173SQLITE_API int sqlite3_like_count = 0;
79174#endif
79175
79176
79177/*
79178** Implementation of the like() SQL function.  This function implements
79179** the build-in LIKE operator.  The first argument to the function is the
79180** pattern and the second argument is the string.  So, the SQL statements:
79181**
79182**       A LIKE B
79183**
79184** is implemented as like(B,A).
79185**
79186** This same function (with a different compareInfo structure) computes
79187** the GLOB operator.
79188*/
79189static void likeFunc(
79190  sqlite3_context *context,
79191  int argc,
79192  sqlite3_value **argv
79193){
79194  const unsigned char *zA, *zB;
79195  int escape = 0;
79196  int nPat;
79197  sqlite3 *db = sqlite3_context_db_handle(context);
79198
79199  zB = sqlite3_value_text(argv[0]);
79200  zA = sqlite3_value_text(argv[1]);
79201
79202  /* Limit the length of the LIKE or GLOB pattern to avoid problems
79203  ** of deep recursion and N*N behavior in patternCompare().
79204  */
79205  nPat = sqlite3_value_bytes(argv[0]);
79206  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
79207  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
79208  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
79209    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
79210    return;
79211  }
79212  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
79213
79214  if( argc==3 ){
79215    /* The escape character string must consist of a single UTF-8 character.
79216    ** Otherwise, return an error.
79217    */
79218    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
79219    if( zEsc==0 ) return;
79220    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
79221      sqlite3_result_error(context,
79222          "ESCAPE expression must be a single character", -1);
79223      return;
79224    }
79225    escape = sqlite3Utf8Read(zEsc, &zEsc);
79226  }
79227  if( zA && zB ){
79228    struct compareInfo *pInfo = sqlite3_user_data(context);
79229#ifdef SQLITE_TEST
79230    sqlite3_like_count++;
79231#endif
79232
79233    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
79234  }
79235}
79236
79237/*
79238** Implementation of the NULLIF(x,y) function.  The result is the first
79239** argument if the arguments are different.  The result is NULL if the
79240** arguments are equal to each other.
79241*/
79242static void nullifFunc(
79243  sqlite3_context *context,
79244  int NotUsed,
79245  sqlite3_value **argv
79246){
79247  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
79248  UNUSED_PARAMETER(NotUsed);
79249  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
79250    sqlite3_result_value(context, argv[0]);
79251  }
79252}
79253
79254/*
79255** Implementation of the sqlite_version() function.  The result is the version
79256** of the SQLite library that is running.
79257*/
79258static void versionFunc(
79259  sqlite3_context *context,
79260  int NotUsed,
79261  sqlite3_value **NotUsed2
79262){
79263  UNUSED_PARAMETER2(NotUsed, NotUsed2);
79264  /* IMP: R-48699-48617 This function is an SQL wrapper around the
79265  ** sqlite3_libversion() C-interface. */
79266  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
79267}
79268
79269/*
79270** Implementation of the sqlite_source_id() function. The result is a string
79271** that identifies the particular version of the source code used to build
79272** SQLite.
79273*/
79274static void sourceidFunc(
79275  sqlite3_context *context,
79276  int NotUsed,
79277  sqlite3_value **NotUsed2
79278){
79279  UNUSED_PARAMETER2(NotUsed, NotUsed2);
79280  /* IMP: R-24470-31136 This function is an SQL wrapper around the
79281  ** sqlite3_sourceid() C interface. */
79282  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
79283}
79284
79285/*
79286** Implementation of the sqlite_compileoption_used() function.
79287** The result is an integer that identifies if the compiler option
79288** was used to build SQLite.
79289*/
79290#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79291static void compileoptionusedFunc(
79292  sqlite3_context *context,
79293  int argc,
79294  sqlite3_value **argv
79295){
79296  const char *zOptName;
79297  assert( argc==1 );
79298  UNUSED_PARAMETER(argc);
79299  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
79300  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
79301  ** function.
79302  */
79303  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
79304    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
79305  }
79306}
79307#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79308
79309/*
79310** Implementation of the sqlite_compileoption_get() function.
79311** The result is a string that identifies the compiler options
79312** used to build SQLite.
79313*/
79314#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79315static void compileoptiongetFunc(
79316  sqlite3_context *context,
79317  int argc,
79318  sqlite3_value **argv
79319){
79320  int n;
79321  assert( argc==1 );
79322  UNUSED_PARAMETER(argc);
79323  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
79324  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
79325  */
79326  n = sqlite3_value_int(argv[0]);
79327  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
79328}
79329#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79330
79331/* Array for converting from half-bytes (nybbles) into ASCII hex
79332** digits. */
79333static const char hexdigits[] = {
79334  '0', '1', '2', '3', '4', '5', '6', '7',
79335  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
79336};
79337
79338/*
79339** EXPERIMENTAL - This is not an official function.  The interface may
79340** change.  This function may disappear.  Do not write code that depends
79341** on this function.
79342**
79343** Implementation of the QUOTE() function.  This function takes a single
79344** argument.  If the argument is numeric, the return value is the same as
79345** the argument.  If the argument is NULL, the return value is the string
79346** "NULL".  Otherwise, the argument is enclosed in single quotes with
79347** single-quote escapes.
79348*/
79349static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79350  assert( argc==1 );
79351  UNUSED_PARAMETER(argc);
79352  switch( sqlite3_value_type(argv[0]) ){
79353    case SQLITE_INTEGER:
79354    case SQLITE_FLOAT: {
79355      sqlite3_result_value(context, argv[0]);
79356      break;
79357    }
79358    case SQLITE_BLOB: {
79359      char *zText = 0;
79360      char const *zBlob = sqlite3_value_blob(argv[0]);
79361      int nBlob = sqlite3_value_bytes(argv[0]);
79362      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
79363      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
79364      if( zText ){
79365        int i;
79366        for(i=0; i<nBlob; i++){
79367          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
79368          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
79369        }
79370        zText[(nBlob*2)+2] = '\'';
79371        zText[(nBlob*2)+3] = '\0';
79372        zText[0] = 'X';
79373        zText[1] = '\'';
79374        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
79375        sqlite3_free(zText);
79376      }
79377      break;
79378    }
79379    case SQLITE_TEXT: {
79380      int i,j;
79381      u64 n;
79382      const unsigned char *zArg = sqlite3_value_text(argv[0]);
79383      char *z;
79384
79385      if( zArg==0 ) return;
79386      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
79387      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
79388      if( z ){
79389        z[0] = '\'';
79390        for(i=0, j=1; zArg[i]; i++){
79391          z[j++] = zArg[i];
79392          if( zArg[i]=='\'' ){
79393            z[j++] = '\'';
79394          }
79395        }
79396        z[j++] = '\'';
79397        z[j] = 0;
79398        sqlite3_result_text(context, z, j, sqlite3_free);
79399      }
79400      break;
79401    }
79402    default: {
79403      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
79404      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
79405      break;
79406    }
79407  }
79408}
79409
79410/*
79411** The hex() function.  Interpret the argument as a blob.  Return
79412** a hexadecimal rendering as text.
79413*/
79414static void hexFunc(
79415  sqlite3_context *context,
79416  int argc,
79417  sqlite3_value **argv
79418){
79419  int i, n;
79420  const unsigned char *pBlob;
79421  char *zHex, *z;
79422  assert( argc==1 );
79423  UNUSED_PARAMETER(argc);
79424  pBlob = sqlite3_value_blob(argv[0]);
79425  n = sqlite3_value_bytes(argv[0]);
79426  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
79427  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
79428  if( zHex ){
79429    for(i=0; i<n; i++, pBlob++){
79430      unsigned char c = *pBlob;
79431      *(z++) = hexdigits[(c>>4)&0xf];
79432      *(z++) = hexdigits[c&0xf];
79433    }
79434    *z = 0;
79435    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
79436  }
79437}
79438
79439/*
79440** The zeroblob(N) function returns a zero-filled blob of size N bytes.
79441*/
79442static void zeroblobFunc(
79443  sqlite3_context *context,
79444  int argc,
79445  sqlite3_value **argv
79446){
79447  i64 n;
79448  sqlite3 *db = sqlite3_context_db_handle(context);
79449  assert( argc==1 );
79450  UNUSED_PARAMETER(argc);
79451  n = sqlite3_value_int64(argv[0]);
79452  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
79453  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
79454  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79455    sqlite3_result_error_toobig(context);
79456  }else{
79457    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
79458  }
79459}
79460
79461/*
79462** The replace() function.  Three arguments are all strings: call
79463** them A, B, and C. The result is also a string which is derived
79464** from A by replacing every occurance of B with C.  The match
79465** must be exact.  Collating sequences are not used.
79466*/
79467static void replaceFunc(
79468  sqlite3_context *context,
79469  int argc,
79470  sqlite3_value **argv
79471){
79472  const unsigned char *zStr;        /* The input string A */
79473  const unsigned char *zPattern;    /* The pattern string B */
79474  const unsigned char *zRep;        /* The replacement string C */
79475  unsigned char *zOut;              /* The output */
79476  int nStr;                /* Size of zStr */
79477  int nPattern;            /* Size of zPattern */
79478  int nRep;                /* Size of zRep */
79479  i64 nOut;                /* Maximum size of zOut */
79480  int loopLimit;           /* Last zStr[] that might match zPattern[] */
79481  int i, j;                /* Loop counters */
79482
79483  assert( argc==3 );
79484  UNUSED_PARAMETER(argc);
79485  zStr = sqlite3_value_text(argv[0]);
79486  if( zStr==0 ) return;
79487  nStr = sqlite3_value_bytes(argv[0]);
79488  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
79489  zPattern = sqlite3_value_text(argv[1]);
79490  if( zPattern==0 ){
79491    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
79492            || sqlite3_context_db_handle(context)->mallocFailed );
79493    return;
79494  }
79495  if( zPattern[0]==0 ){
79496    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
79497    sqlite3_result_value(context, argv[0]);
79498    return;
79499  }
79500  nPattern = sqlite3_value_bytes(argv[1]);
79501  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
79502  zRep = sqlite3_value_text(argv[2]);
79503  if( zRep==0 ) return;
79504  nRep = sqlite3_value_bytes(argv[2]);
79505  assert( zRep==sqlite3_value_text(argv[2]) );
79506  nOut = nStr + 1;
79507  assert( nOut<SQLITE_MAX_LENGTH );
79508  zOut = contextMalloc(context, (i64)nOut);
79509  if( zOut==0 ){
79510    return;
79511  }
79512  loopLimit = nStr - nPattern;
79513  for(i=j=0; i<=loopLimit; i++){
79514    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
79515      zOut[j++] = zStr[i];
79516    }else{
79517      u8 *zOld;
79518      sqlite3 *db = sqlite3_context_db_handle(context);
79519      nOut += nRep - nPattern;
79520      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
79521      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
79522      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79523        sqlite3_result_error_toobig(context);
79524        sqlite3_free(zOut);
79525        return;
79526      }
79527      zOld = zOut;
79528      zOut = sqlite3_realloc(zOut, (int)nOut);
79529      if( zOut==0 ){
79530        sqlite3_result_error_nomem(context);
79531        sqlite3_free(zOld);
79532        return;
79533      }
79534      memcpy(&zOut[j], zRep, nRep);
79535      j += nRep;
79536      i += nPattern-1;
79537    }
79538  }
79539  assert( j+nStr-i+1==nOut );
79540  memcpy(&zOut[j], &zStr[i], nStr-i);
79541  j += nStr - i;
79542  assert( j<=nOut );
79543  zOut[j] = 0;
79544  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
79545}
79546
79547/*
79548** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
79549** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
79550*/
79551static void trimFunc(
79552  sqlite3_context *context,
79553  int argc,
79554  sqlite3_value **argv
79555){
79556  const unsigned char *zIn;         /* Input string */
79557  const unsigned char *zCharSet;    /* Set of characters to trim */
79558  int nIn;                          /* Number of bytes in input */
79559  int flags;                        /* 1: trimleft  2: trimright  3: trim */
79560  int i;                            /* Loop counter */
79561  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
79562  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
79563  int nChar;                        /* Number of characters in zCharSet */
79564
79565  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
79566    return;
79567  }
79568  zIn = sqlite3_value_text(argv[0]);
79569  if( zIn==0 ) return;
79570  nIn = sqlite3_value_bytes(argv[0]);
79571  assert( zIn==sqlite3_value_text(argv[0]) );
79572  if( argc==1 ){
79573    static const unsigned char lenOne[] = { 1 };
79574    static unsigned char * const azOne[] = { (u8*)" " };
79575    nChar = 1;
79576    aLen = (u8*)lenOne;
79577    azChar = (unsigned char **)azOne;
79578    zCharSet = 0;
79579  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
79580    return;
79581  }else{
79582    const unsigned char *z;
79583    for(z=zCharSet, nChar=0; *z; nChar++){
79584      SQLITE_SKIP_UTF8(z);
79585    }
79586    if( nChar>0 ){
79587      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
79588      if( azChar==0 ){
79589        return;
79590      }
79591      aLen = (unsigned char*)&azChar[nChar];
79592      for(z=zCharSet, nChar=0; *z; nChar++){
79593        azChar[nChar] = (unsigned char *)z;
79594        SQLITE_SKIP_UTF8(z);
79595        aLen[nChar] = (u8)(z - azChar[nChar]);
79596      }
79597    }
79598  }
79599  if( nChar>0 ){
79600    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
79601    if( flags & 1 ){
79602      while( nIn>0 ){
79603        int len = 0;
79604        for(i=0; i<nChar; i++){
79605          len = aLen[i];
79606          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
79607        }
79608        if( i>=nChar ) break;
79609        zIn += len;
79610        nIn -= len;
79611      }
79612    }
79613    if( flags & 2 ){
79614      while( nIn>0 ){
79615        int len = 0;
79616        for(i=0; i<nChar; i++){
79617          len = aLen[i];
79618          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
79619        }
79620        if( i>=nChar ) break;
79621        nIn -= len;
79622      }
79623    }
79624    if( zCharSet ){
79625      sqlite3_free(azChar);
79626    }
79627  }
79628  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
79629}
79630
79631
79632/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
79633** is only available if the SQLITE_SOUNDEX compile-time option is used
79634** when SQLite is built.
79635*/
79636#ifdef SQLITE_SOUNDEX
79637/*
79638** Compute the soundex encoding of a word.
79639**
79640** IMP: R-59782-00072 The soundex(X) function returns a string that is the
79641** soundex encoding of the string X.
79642*/
79643static void soundexFunc(
79644  sqlite3_context *context,
79645  int argc,
79646  sqlite3_value **argv
79647){
79648  char zResult[8];
79649  const u8 *zIn;
79650  int i, j;
79651  static const unsigned char iCode[] = {
79652    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79653    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79654    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79655    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79656    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
79657    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
79658    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
79659    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
79660  };
79661  assert( argc==1 );
79662  zIn = (u8*)sqlite3_value_text(argv[0]);
79663  if( zIn==0 ) zIn = (u8*)"";
79664  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
79665  if( zIn[i] ){
79666    u8 prevcode = iCode[zIn[i]&0x7f];
79667    zResult[0] = sqlite3Toupper(zIn[i]);
79668    for(j=1; j<4 && zIn[i]; i++){
79669      int code = iCode[zIn[i]&0x7f];
79670      if( code>0 ){
79671        if( code!=prevcode ){
79672          prevcode = code;
79673          zResult[j++] = code + '0';
79674        }
79675      }else{
79676        prevcode = 0;
79677      }
79678    }
79679    while( j<4 ){
79680      zResult[j++] = '0';
79681    }
79682    zResult[j] = 0;
79683    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
79684  }else{
79685    /* IMP: R-64894-50321 The string "?000" is returned if the argument
79686    ** is NULL or contains no ASCII alphabetic characters. */
79687    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
79688  }
79689}
79690#endif /* SQLITE_SOUNDEX */
79691
79692#ifndef SQLITE_OMIT_LOAD_EXTENSION
79693/*
79694** A function that loads a shared-library extension then returns NULL.
79695*/
79696static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
79697  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
79698  const char *zProc;
79699  sqlite3 *db = sqlite3_context_db_handle(context);
79700  char *zErrMsg = 0;
79701
79702  if( argc==2 ){
79703    zProc = (const char *)sqlite3_value_text(argv[1]);
79704  }else{
79705    zProc = 0;
79706  }
79707  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
79708    sqlite3_result_error(context, zErrMsg, -1);
79709    sqlite3_free(zErrMsg);
79710  }
79711}
79712#endif
79713
79714
79715/*
79716** An instance of the following structure holds the context of a
79717** sum() or avg() aggregate computation.
79718*/
79719typedef struct SumCtx SumCtx;
79720struct SumCtx {
79721  double rSum;      /* Floating point sum */
79722  i64 iSum;         /* Integer sum */
79723  i64 cnt;          /* Number of elements summed */
79724  u8 overflow;      /* True if integer overflow seen */
79725  u8 approx;        /* True if non-integer value was input to the sum */
79726};
79727
79728/*
79729** Routines used to compute the sum, average, and total.
79730**
79731** The SUM() function follows the (broken) SQL standard which means
79732** that it returns NULL if it sums over no inputs.  TOTAL returns
79733** 0.0 in that case.  In addition, TOTAL always returns a float where
79734** SUM might return an integer if it never encounters a floating point
79735** value.  TOTAL never fails, but SUM might through an exception if
79736** it overflows an integer.
79737*/
79738static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
79739  SumCtx *p;
79740  int type;
79741  assert( argc==1 );
79742  UNUSED_PARAMETER(argc);
79743  p = sqlite3_aggregate_context(context, sizeof(*p));
79744  type = sqlite3_value_numeric_type(argv[0]);
79745  if( p && type!=SQLITE_NULL ){
79746    p->cnt++;
79747    if( type==SQLITE_INTEGER ){
79748      i64 v = sqlite3_value_int64(argv[0]);
79749      p->rSum += v;
79750      if( (p->approx|p->overflow)==0 ){
79751        i64 iNewSum = p->iSum + v;
79752        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
79753        int s2 = (int)(v       >> (sizeof(i64)*8-1));
79754        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
79755        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
79756        p->iSum = iNewSum;
79757      }
79758    }else{
79759      p->rSum += sqlite3_value_double(argv[0]);
79760      p->approx = 1;
79761    }
79762  }
79763}
79764static void sumFinalize(sqlite3_context *context){
79765  SumCtx *p;
79766  p = sqlite3_aggregate_context(context, 0);
79767  if( p && p->cnt>0 ){
79768    if( p->overflow ){
79769      sqlite3_result_error(context,"integer overflow",-1);
79770    }else if( p->approx ){
79771      sqlite3_result_double(context, p->rSum);
79772    }else{
79773      sqlite3_result_int64(context, p->iSum);
79774    }
79775  }
79776}
79777static void avgFinalize(sqlite3_context *context){
79778  SumCtx *p;
79779  p = sqlite3_aggregate_context(context, 0);
79780  if( p && p->cnt>0 ){
79781    sqlite3_result_double(context, p->rSum/(double)p->cnt);
79782  }
79783}
79784static void totalFinalize(sqlite3_context *context){
79785  SumCtx *p;
79786  p = sqlite3_aggregate_context(context, 0);
79787  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
79788  sqlite3_result_double(context, p ? p->rSum : (double)0);
79789}
79790
79791/*
79792** The following structure keeps track of state information for the
79793** count() aggregate function.
79794*/
79795typedef struct CountCtx CountCtx;
79796struct CountCtx {
79797  i64 n;
79798};
79799
79800/*
79801** Routines to implement the count() aggregate function.
79802*/
79803static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
79804  CountCtx *p;
79805  p = sqlite3_aggregate_context(context, sizeof(*p));
79806  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
79807    p->n++;
79808  }
79809
79810#ifndef SQLITE_OMIT_DEPRECATED
79811  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
79812  ** sure it still operates correctly, verify that its count agrees with our
79813  ** internal count when using count(*) and when the total count can be
79814  ** expressed as a 32-bit integer. */
79815  assert( argc==1 || p==0 || p->n>0x7fffffff
79816          || p->n==sqlite3_aggregate_count(context) );
79817#endif
79818}
79819static void countFinalize(sqlite3_context *context){
79820  CountCtx *p;
79821  p = sqlite3_aggregate_context(context, 0);
79822  sqlite3_result_int64(context, p ? p->n : 0);
79823}
79824
79825/*
79826** Routines to implement min() and max() aggregate functions.
79827*/
79828static void minmaxStep(
79829  sqlite3_context *context,
79830  int NotUsed,
79831  sqlite3_value **argv
79832){
79833  Mem *pArg  = (Mem *)argv[0];
79834  Mem *pBest;
79835  UNUSED_PARAMETER(NotUsed);
79836
79837  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79838  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
79839  if( !pBest ) return;
79840
79841  if( pBest->flags ){
79842    int max;
79843    int cmp;
79844    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
79845    /* This step function is used for both the min() and max() aggregates,
79846    ** the only difference between the two being that the sense of the
79847    ** comparison is inverted. For the max() aggregate, the
79848    ** sqlite3_user_data() function returns (void *)-1. For min() it
79849    ** returns (void *)db, where db is the sqlite3* database pointer.
79850    ** Therefore the next statement sets variable 'max' to 1 for the max()
79851    ** aggregate, or 0 for min().
79852    */
79853    max = sqlite3_user_data(context)!=0;
79854    cmp = sqlite3MemCompare(pBest, pArg, pColl);
79855    if( (max && cmp<0) || (!max && cmp>0) ){
79856      sqlite3VdbeMemCopy(pBest, pArg);
79857    }
79858  }else{
79859    sqlite3VdbeMemCopy(pBest, pArg);
79860  }
79861}
79862static void minMaxFinalize(sqlite3_context *context){
79863  sqlite3_value *pRes;
79864  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
79865  if( pRes ){
79866    if( ALWAYS(pRes->flags) ){
79867      sqlite3_result_value(context, pRes);
79868    }
79869    sqlite3VdbeMemRelease(pRes);
79870  }
79871}
79872
79873/*
79874** group_concat(EXPR, ?SEPARATOR?)
79875*/
79876static void groupConcatStep(
79877  sqlite3_context *context,
79878  int argc,
79879  sqlite3_value **argv
79880){
79881  const char *zVal;
79882  StrAccum *pAccum;
79883  const char *zSep;
79884  int nVal, nSep;
79885  assert( argc==1 || argc==2 );
79886  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79887  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
79888
79889  if( pAccum ){
79890    sqlite3 *db = sqlite3_context_db_handle(context);
79891    int firstTerm = pAccum->useMalloc==0;
79892    pAccum->useMalloc = 2;
79893    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
79894    if( !firstTerm ){
79895      if( argc==2 ){
79896        zSep = (char*)sqlite3_value_text(argv[1]);
79897        nSep = sqlite3_value_bytes(argv[1]);
79898      }else{
79899        zSep = ",";
79900        nSep = 1;
79901      }
79902      sqlite3StrAccumAppend(pAccum, zSep, nSep);
79903    }
79904    zVal = (char*)sqlite3_value_text(argv[0]);
79905    nVal = sqlite3_value_bytes(argv[0]);
79906    sqlite3StrAccumAppend(pAccum, zVal, nVal);
79907  }
79908}
79909static void groupConcatFinalize(sqlite3_context *context){
79910  StrAccum *pAccum;
79911  pAccum = sqlite3_aggregate_context(context, 0);
79912  if( pAccum ){
79913    if( pAccum->tooBig ){
79914      sqlite3_result_error_toobig(context);
79915    }else if( pAccum->mallocFailed ){
79916      sqlite3_result_error_nomem(context);
79917    }else{
79918      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
79919                          sqlite3_free);
79920    }
79921  }
79922}
79923
79924/*
79925** This routine does per-connection function registration.  Most
79926** of the built-in functions above are part of the global function set.
79927** This routine only deals with those that are not global.
79928*/
79929SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
79930  int rc = sqlite3_overload_function(db, "MATCH", 2);
79931  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
79932  if( rc==SQLITE_NOMEM ){
79933    db->mallocFailed = 1;
79934  }
79935}
79936
79937/*
79938** Set the LIKEOPT flag on the 2-argument function with the given name.
79939*/
79940static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
79941  FuncDef *pDef;
79942  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
79943                             2, SQLITE_UTF8, 0);
79944  if( ALWAYS(pDef) ){
79945    pDef->flags = flagVal;
79946  }
79947}
79948
79949/*
79950** Register the built-in LIKE and GLOB functions.  The caseSensitive
79951** parameter determines whether or not the LIKE operator is case
79952** sensitive.  GLOB is always case sensitive.
79953*/
79954SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
79955  struct compareInfo *pInfo;
79956  if( caseSensitive ){
79957    pInfo = (struct compareInfo*)&likeInfoAlt;
79958  }else{
79959    pInfo = (struct compareInfo*)&likeInfoNorm;
79960  }
79961  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79962  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79963  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
79964      (struct compareInfo*)&globInfo, likeFunc, 0,0);
79965  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
79966  setLikeOptFlag(db, "like",
79967      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
79968}
79969
79970/*
79971** pExpr points to an expression which implements a function.  If
79972** it is appropriate to apply the LIKE optimization to that function
79973** then set aWc[0] through aWc[2] to the wildcard characters and
79974** return TRUE.  If the function is not a LIKE-style function then
79975** return FALSE.
79976*/
79977SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
79978  FuncDef *pDef;
79979  if( pExpr->op!=TK_FUNCTION
79980   || !pExpr->x.pList
79981   || pExpr->x.pList->nExpr!=2
79982  ){
79983    return 0;
79984  }
79985  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79986  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
79987                             sqlite3Strlen30(pExpr->u.zToken),
79988                             2, SQLITE_UTF8, 0);
79989  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
79990    return 0;
79991  }
79992
79993  /* The memcpy() statement assumes that the wildcard characters are
79994  ** the first three statements in the compareInfo structure.  The
79995  ** asserts() that follow verify that assumption
79996  */
79997  memcpy(aWc, pDef->pUserData, 3);
79998  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
79999  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
80000  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
80001  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
80002  return 1;
80003}
80004
80005/*
80006** All all of the FuncDef structures in the aBuiltinFunc[] array above
80007** to the global function hash table.  This occurs at start-time (as
80008** a consequence of calling sqlite3_initialize()).
80009**
80010** After this routine runs
80011*/
80012SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
80013  /*
80014  ** The following array holds FuncDef structures for all of the functions
80015  ** defined in this file.
80016  **
80017  ** The array cannot be constant since changes are made to the
80018  ** FuncDef.pHash elements at start-time.  The elements of this array
80019  ** are read-only after initialization is complete.
80020  */
80021  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
80022    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
80023    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
80024    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
80025    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
80026    FUNCTION(trim,               1, 3, 0, trimFunc         ),
80027    FUNCTION(trim,               2, 3, 0, trimFunc         ),
80028    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
80029    FUNCTION(min,                0, 0, 1, 0                ),
80030    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
80031    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
80032    FUNCTION(max,                0, 1, 1, 0                ),
80033    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
80034    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
80035    FUNCTION(length,             1, 0, 0, lengthFunc       ),
80036    FUNCTION(substr,             2, 0, 0, substrFunc       ),
80037    FUNCTION(substr,             3, 0, 0, substrFunc       ),
80038    FUNCTION(abs,                1, 0, 0, absFunc          ),
80039#ifndef SQLITE_OMIT_FLOATING_POINT
80040    FUNCTION(round,              1, 0, 0, roundFunc        ),
80041    FUNCTION(round,              2, 0, 0, roundFunc        ),
80042#endif
80043    FUNCTION(upper,              1, 0, 0, upperFunc        ),
80044    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
80045    FUNCTION(coalesce,           1, 0, 0, 0                ),
80046    FUNCTION(coalesce,           0, 0, 0, 0                ),
80047/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
80048    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
80049    FUNCTION(hex,                1, 0, 0, hexFunc          ),
80050/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
80051    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
80052    FUNCTION(random,             0, 0, 0, randomFunc       ),
80053    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
80054    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
80055    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
80056    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
80057#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
80058    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
80059    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
80060#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
80061    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
80062    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
80063    FUNCTION(changes,            0, 0, 0, changes          ),
80064    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
80065    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
80066    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
80067  #ifdef SQLITE_SOUNDEX
80068    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
80069  #endif
80070  #ifndef SQLITE_OMIT_LOAD_EXTENSION
80071    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
80072    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
80073  #endif
80074    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
80075    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
80076    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
80077 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
80078    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
80079    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
80080    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
80081    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
80082
80083    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
80084  #ifdef SQLITE_CASE_SENSITIVE_LIKE
80085    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
80086    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
80087  #else
80088    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
80089    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
80090  #endif
80091  };
80092
80093  int i;
80094  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
80095  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
80096
80097  for(i=0; i<ArraySize(aBuiltinFunc); i++){
80098    sqlite3FuncDefInsert(pHash, &aFunc[i]);
80099  }
80100  sqlite3RegisterDateTimeFunctions();
80101#ifndef SQLITE_OMIT_ALTERTABLE
80102  sqlite3AlterFunctions();
80103#endif
80104}
80105
80106/************** End of func.c ************************************************/
80107/************** Begin file fkey.c ********************************************/
80108/*
80109**
80110** The author disclaims copyright to this source code.  In place of
80111** a legal notice, here is a blessing:
80112**
80113**    May you do good and not evil.
80114**    May you find forgiveness for yourself and forgive others.
80115**    May you share freely, never taking more than you give.
80116**
80117*************************************************************************
80118** This file contains code used by the compiler to add foreign key
80119** support to compiled SQL statements.
80120*/
80121
80122#ifndef SQLITE_OMIT_FOREIGN_KEY
80123#ifndef SQLITE_OMIT_TRIGGER
80124
80125/*
80126** Deferred and Immediate FKs
80127** --------------------------
80128**
80129** Foreign keys in SQLite come in two flavours: deferred and immediate.
80130** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
80131** is returned and the current statement transaction rolled back. If a
80132** deferred foreign key constraint is violated, no action is taken
80133** immediately. However if the application attempts to commit the
80134** transaction before fixing the constraint violation, the attempt fails.
80135**
80136** Deferred constraints are implemented using a simple counter associated
80137** with the database handle. The counter is set to zero each time a
80138** database transaction is opened. Each time a statement is executed
80139** that causes a foreign key violation, the counter is incremented. Each
80140** time a statement is executed that removes an existing violation from
80141** the database, the counter is decremented. When the transaction is
80142** committed, the commit fails if the current value of the counter is
80143** greater than zero. This scheme has two big drawbacks:
80144**
80145**   * When a commit fails due to a deferred foreign key constraint,
80146**     there is no way to tell which foreign constraint is not satisfied,
80147**     or which row it is not satisfied for.
80148**
80149**   * If the database contains foreign key violations when the
80150**     transaction is opened, this may cause the mechanism to malfunction.
80151**
80152** Despite these problems, this approach is adopted as it seems simpler
80153** than the alternatives.
80154**
80155** INSERT operations:
80156**
80157**   I.1) For each FK for which the table is the child table, search
80158**        the parent table for a match. If none is found increment the
80159**        constraint counter.
80160**
80161**   I.2) For each FK for which the table is the parent table,
80162**        search the child table for rows that correspond to the new
80163**        row in the parent table. Decrement the counter for each row
80164**        found (as the constraint is now satisfied).
80165**
80166** DELETE operations:
80167**
80168**   D.1) For each FK for which the table is the child table,
80169**        search the parent table for a row that corresponds to the
80170**        deleted row in the child table. If such a row is not found,
80171**        decrement the counter.
80172**
80173**   D.2) For each FK for which the table is the parent table, search
80174**        the child table for rows that correspond to the deleted row
80175**        in the parent table. For each found increment the counter.
80176**
80177** UPDATE operations:
80178**
80179**   An UPDATE command requires that all 4 steps above are taken, but only
80180**   for FK constraints for which the affected columns are actually
80181**   modified (values must be compared at runtime).
80182**
80183** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
80184** This simplifies the implementation a bit.
80185**
80186** For the purposes of immediate FK constraints, the OR REPLACE conflict
80187** resolution is considered to delete rows before the new row is inserted.
80188** If a delete caused by OR REPLACE violates an FK constraint, an exception
80189** is thrown, even if the FK constraint would be satisfied after the new
80190** row is inserted.
80191**
80192** Immediate constraints are usually handled similarly. The only difference
80193** is that the counter used is stored as part of each individual statement
80194** object (struct Vdbe). If, after the statement has run, its immediate
80195** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
80196** and the statement transaction is rolled back. An exception is an INSERT
80197** statement that inserts a single row only (no triggers). In this case,
80198** instead of using a counter, an exception is thrown immediately if the
80199** INSERT violates a foreign key constraint. This is necessary as such
80200** an INSERT does not open a statement transaction.
80201**
80202** TODO: How should dropping a table be handled? How should renaming a
80203** table be handled?
80204**
80205**
80206** Query API Notes
80207** ---------------
80208**
80209** Before coding an UPDATE or DELETE row operation, the code-generator
80210** for those two operations needs to know whether or not the operation
80211** requires any FK processing and, if so, which columns of the original
80212** row are required by the FK processing VDBE code (i.e. if FKs were
80213** implemented using triggers, which of the old.* columns would be
80214** accessed). No information is required by the code-generator before
80215** coding an INSERT operation. The functions used by the UPDATE/DELETE
80216** generation code to query for this information are:
80217**
80218**   sqlite3FkRequired() - Test to see if FK processing is required.
80219**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
80220**
80221**
80222** Externally accessible module functions
80223** --------------------------------------
80224**
80225**   sqlite3FkCheck()    - Check for foreign key violations.
80226**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
80227**   sqlite3FkDelete()   - Delete an FKey structure.
80228*/
80229
80230/*
80231** VDBE Calling Convention
80232** -----------------------
80233**
80234** Example:
80235**
80236**   For the following INSERT statement:
80237**
80238**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
80239**     INSERT INTO t1 VALUES(1, 2, 3.1);
80240**
80241**   Register (x):        2    (type integer)
80242**   Register (x+1):      1    (type integer)
80243**   Register (x+2):      NULL (type NULL)
80244**   Register (x+3):      3.1  (type real)
80245*/
80246
80247/*
80248** A foreign key constraint requires that the key columns in the parent
80249** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
80250** Given that pParent is the parent table for foreign key constraint pFKey,
80251** search the schema a unique index on the parent key columns.
80252**
80253** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
80254** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
80255** is set to point to the unique index.
80256**
80257** If the parent key consists of a single column (the foreign key constraint
80258** is not a composite foreign key), output variable *paiCol is set to NULL.
80259** Otherwise, it is set to point to an allocated array of size N, where
80260** N is the number of columns in the parent key. The first element of the
80261** array is the index of the child table column that is mapped by the FK
80262** constraint to the parent table column stored in the left-most column
80263** of index *ppIdx. The second element of the array is the index of the
80264** child table column that corresponds to the second left-most column of
80265** *ppIdx, and so on.
80266**
80267** If the required index cannot be found, either because:
80268**
80269**   1) The named parent key columns do not exist, or
80270**
80271**   2) The named parent key columns do exist, but are not subject to a
80272**      UNIQUE or PRIMARY KEY constraint, or
80273**
80274**   3) No parent key columns were provided explicitly as part of the
80275**      foreign key definition, and the parent table does not have a
80276**      PRIMARY KEY, or
80277**
80278**   4) No parent key columns were provided explicitly as part of the
80279**      foreign key definition, and the PRIMARY KEY of the parent table
80280**      consists of a a different number of columns to the child key in
80281**      the child table.
80282**
80283** then non-zero is returned, and a "foreign key mismatch" error loaded
80284** into pParse. If an OOM error occurs, non-zero is returned and the
80285** pParse->db->mallocFailed flag is set.
80286*/
80287static int locateFkeyIndex(
80288  Parse *pParse,                  /* Parse context to store any error in */
80289  Table *pParent,                 /* Parent table of FK constraint pFKey */
80290  FKey *pFKey,                    /* Foreign key to find index for */
80291  Index **ppIdx,                  /* OUT: Unique index on parent table */
80292  int **paiCol                    /* OUT: Map of index columns in pFKey */
80293){
80294  Index *pIdx = 0;                    /* Value to return via *ppIdx */
80295  int *aiCol = 0;                     /* Value to return via *paiCol */
80296  int nCol = pFKey->nCol;             /* Number of columns in parent key */
80297  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
80298
80299  /* The caller is responsible for zeroing output parameters. */
80300  assert( ppIdx && *ppIdx==0 );
80301  assert( !paiCol || *paiCol==0 );
80302  assert( pParse );
80303
80304  /* If this is a non-composite (single column) foreign key, check if it
80305  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
80306  ** and *paiCol set to zero and return early.
80307  **
80308  ** Otherwise, for a composite foreign key (more than one column), allocate
80309  ** space for the aiCol array (returned via output parameter *paiCol).
80310  ** Non-composite foreign keys do not require the aiCol array.
80311  */
80312  if( nCol==1 ){
80313    /* The FK maps to the IPK if any of the following are true:
80314    **
80315    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
80316    **      mapped to the primary key of table pParent, or
80317    **   2) The FK is explicitly mapped to a column declared as INTEGER
80318    **      PRIMARY KEY.
80319    */
80320    if( pParent->iPKey>=0 ){
80321      if( !zKey ) return 0;
80322      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
80323    }
80324  }else if( paiCol ){
80325    assert( nCol>1 );
80326    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
80327    if( !aiCol ) return 1;
80328    *paiCol = aiCol;
80329  }
80330
80331  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
80332    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
80333      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
80334      ** of columns. If each indexed column corresponds to a foreign key
80335      ** column of pFKey, then this index is a winner.  */
80336
80337      if( zKey==0 ){
80338        /* If zKey is NULL, then this foreign key is implicitly mapped to
80339        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
80340        ** identified by the test (Index.autoIndex==2).  */
80341        if( pIdx->autoIndex==2 ){
80342          if( aiCol ){
80343            int i;
80344            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
80345          }
80346          break;
80347        }
80348      }else{
80349        /* If zKey is non-NULL, then this foreign key was declared to
80350        ** map to an explicit list of columns in table pParent. Check if this
80351        ** index matches those columns. Also, check that the index uses
80352        ** the default collation sequences for each column. */
80353        int i, j;
80354        for(i=0; i<nCol; i++){
80355          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
80356          char *zDfltColl;                  /* Def. collation for column */
80357          char *zIdxCol;                    /* Name of indexed column */
80358
80359          /* If the index uses a collation sequence that is different from
80360          ** the default collation sequence for the column, this index is
80361          ** unusable. Bail out early in this case.  */
80362          zDfltColl = pParent->aCol[iCol].zColl;
80363          if( !zDfltColl ){
80364            zDfltColl = "BINARY";
80365          }
80366          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
80367
80368          zIdxCol = pParent->aCol[iCol].zName;
80369          for(j=0; j<nCol; j++){
80370            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
80371              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
80372              break;
80373            }
80374          }
80375          if( j==nCol ) break;
80376        }
80377        if( i==nCol ) break;      /* pIdx is usable */
80378      }
80379    }
80380  }
80381
80382  if( !pIdx ){
80383    if( !pParse->disableTriggers ){
80384      sqlite3ErrorMsg(pParse, "foreign key mismatch");
80385    }
80386    sqlite3DbFree(pParse->db, aiCol);
80387    return 1;
80388  }
80389
80390  *ppIdx = pIdx;
80391  return 0;
80392}
80393
80394/*
80395** This function is called when a row is inserted into or deleted from the
80396** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
80397** on the child table of pFKey, this function is invoked twice for each row
80398** affected - once to "delete" the old row, and then again to "insert" the
80399** new row.
80400**
80401** Each time it is called, this function generates VDBE code to locate the
80402** row in the parent table that corresponds to the row being inserted into
80403** or deleted from the child table. If the parent row can be found, no
80404** special action is taken. Otherwise, if the parent row can *not* be
80405** found in the parent table:
80406**
80407**   Operation | FK type   | Action taken
80408**   --------------------------------------------------------------------------
80409**   INSERT      immediate   Increment the "immediate constraint counter".
80410**
80411**   DELETE      immediate   Decrement the "immediate constraint counter".
80412**
80413**   INSERT      deferred    Increment the "deferred constraint counter".
80414**
80415**   DELETE      deferred    Decrement the "deferred constraint counter".
80416**
80417** These operations are identified in the comment at the top of this file
80418** (fkey.c) as "I.1" and "D.1".
80419*/
80420static void fkLookupParent(
80421  Parse *pParse,        /* Parse context */
80422  int iDb,              /* Index of database housing pTab */
80423  Table *pTab,          /* Parent table of FK pFKey */
80424  Index *pIdx,          /* Unique index on parent key columns in pTab */
80425  FKey *pFKey,          /* Foreign key constraint */
80426  int *aiCol,           /* Map from parent key columns to child table columns */
80427  int regData,          /* Address of array containing child table row */
80428  int nIncr,            /* Increment constraint counter by this */
80429  int isIgnore          /* If true, pretend pTab contains all NULL values */
80430){
80431  int i;                                    /* Iterator variable */
80432  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
80433  int iCur = pParse->nTab - 1;              /* Cursor number to use */
80434  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
80435
80436  /* If nIncr is less than zero, then check at runtime if there are any
80437  ** outstanding constraints to resolve. If there are not, there is no need
80438  ** to check if deleting this row resolves any outstanding violations.
80439  **
80440  ** Check if any of the key columns in the child table row are NULL. If
80441  ** any are, then the constraint is considered satisfied. No need to
80442  ** search for a matching row in the parent table.  */
80443  if( nIncr<0 ){
80444    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
80445  }
80446  for(i=0; i<pFKey->nCol; i++){
80447    int iReg = aiCol[i] + regData + 1;
80448    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
80449  }
80450
80451  if( isIgnore==0 ){
80452    if( pIdx==0 ){
80453      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
80454      ** column of the parent table (table pTab).  */
80455      int iMustBeInt;               /* Address of MustBeInt instruction */
80456      int regTemp = sqlite3GetTempReg(pParse);
80457
80458      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
80459      ** apply the affinity of the parent key). If this fails, then there
80460      ** is no matching parent key. Before using MustBeInt, make a copy of
80461      ** the value. Otherwise, the value inserted into the child key column
80462      ** will have INTEGER affinity applied to it, which may not be correct.  */
80463      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
80464      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
80465
80466      /* If the parent table is the same as the child table, and we are about
80467      ** to increment the constraint-counter (i.e. this is an INSERT operation),
80468      ** then check if the row being inserted matches itself. If so, do not
80469      ** increment the constraint-counter.  */
80470      if( pTab==pFKey->pFrom && nIncr==1 ){
80471        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
80472      }
80473
80474      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
80475      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
80476      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
80477      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
80478      sqlite3VdbeJumpHere(v, iMustBeInt);
80479      sqlite3ReleaseTempReg(pParse, regTemp);
80480    }else{
80481      int nCol = pFKey->nCol;
80482      int regTemp = sqlite3GetTempRange(pParse, nCol);
80483      int regRec = sqlite3GetTempReg(pParse);
80484      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
80485
80486      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
80487      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
80488      for(i=0; i<nCol; i++){
80489        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
80490      }
80491
80492      /* If the parent table is the same as the child table, and we are about
80493      ** to increment the constraint-counter (i.e. this is an INSERT operation),
80494      ** then check if the row being inserted matches itself. If so, do not
80495      ** increment the constraint-counter.  */
80496      if( pTab==pFKey->pFrom && nIncr==1 ){
80497        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
80498        for(i=0; i<nCol; i++){
80499          int iChild = aiCol[i]+1+regData;
80500          int iParent = pIdx->aiColumn[i]+1+regData;
80501          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
80502        }
80503        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
80504      }
80505
80506      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
80507      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
80508      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
80509
80510      sqlite3ReleaseTempReg(pParse, regRec);
80511      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
80512    }
80513  }
80514
80515  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
80516    /* Special case: If this is an INSERT statement that will insert exactly
80517    ** one row into the table, raise a constraint immediately instead of
80518    ** incrementing a counter. This is necessary as the VM code is being
80519    ** generated for will not open a statement transaction.  */
80520    assert( nIncr==1 );
80521    sqlite3HaltConstraint(
80522        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
80523    );
80524  }else{
80525    if( nIncr>0 && pFKey->isDeferred==0 ){
80526      sqlite3ParseToplevel(pParse)->mayAbort = 1;
80527    }
80528    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
80529  }
80530
80531  sqlite3VdbeResolveLabel(v, iOk);
80532  sqlite3VdbeAddOp1(v, OP_Close, iCur);
80533}
80534
80535/*
80536** This function is called to generate code executed when a row is deleted
80537** from the parent table of foreign key constraint pFKey and, if pFKey is
80538** deferred, when a row is inserted into the same table. When generating
80539** code for an SQL UPDATE operation, this function may be called twice -
80540** once to "delete" the old row and once to "insert" the new row.
80541**
80542** The code generated by this function scans through the rows in the child
80543** table that correspond to the parent table row being deleted or inserted.
80544** For each child row found, one of the following actions is taken:
80545**
80546**   Operation | FK type   | Action taken
80547**   --------------------------------------------------------------------------
80548**   DELETE      immediate   Increment the "immediate constraint counter".
80549**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
80550**                           throw a "foreign key constraint failed" exception.
80551**
80552**   INSERT      immediate   Decrement the "immediate constraint counter".
80553**
80554**   DELETE      deferred    Increment the "deferred constraint counter".
80555**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
80556**                           throw a "foreign key constraint failed" exception.
80557**
80558**   INSERT      deferred    Decrement the "deferred constraint counter".
80559**
80560** These operations are identified in the comment at the top of this file
80561** (fkey.c) as "I.2" and "D.2".
80562*/
80563static void fkScanChildren(
80564  Parse *pParse,                  /* Parse context */
80565  SrcList *pSrc,                  /* SrcList containing the table to scan */
80566  Table *pTab,
80567  Index *pIdx,                    /* Foreign key index */
80568  FKey *pFKey,                    /* Foreign key relationship */
80569  int *aiCol,                     /* Map from pIdx cols to child table cols */
80570  int regData,                    /* Referenced table data starts here */
80571  int nIncr                       /* Amount to increment deferred counter by */
80572){
80573  sqlite3 *db = pParse->db;       /* Database handle */
80574  int i;                          /* Iterator variable */
80575  Expr *pWhere = 0;               /* WHERE clause to scan with */
80576  NameContext sNameContext;       /* Context used to resolve WHERE clause */
80577  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
80578  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
80579  Vdbe *v = sqlite3GetVdbe(pParse);
80580
80581  assert( !pIdx || pIdx->pTable==pTab );
80582
80583  if( nIncr<0 ){
80584    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
80585  }
80586
80587  /* Create an Expr object representing an SQL expression like:
80588  **
80589  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
80590  **
80591  ** The collation sequence used for the comparison should be that of
80592  ** the parent key columns. The affinity of the parent key column should
80593  ** be applied to each child key value before the comparison takes place.
80594  */
80595  for(i=0; i<pFKey->nCol; i++){
80596    Expr *pLeft;                  /* Value from parent table row */
80597    Expr *pRight;                 /* Column ref to child table */
80598    Expr *pEq;                    /* Expression (pLeft = pRight) */
80599    int iCol;                     /* Index of column in child table */
80600    const char *zCol;             /* Name of column in child table */
80601
80602    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
80603    if( pLeft ){
80604      /* Set the collation sequence and affinity of the LHS of each TK_EQ
80605      ** expression to the parent key column defaults.  */
80606      if( pIdx ){
80607        Column *pCol;
80608        iCol = pIdx->aiColumn[i];
80609        pCol = &pTab->aCol[iCol];
80610        if( pTab->iPKey==iCol ) iCol = -1;
80611        pLeft->iTable = regData+iCol+1;
80612        pLeft->affinity = pCol->affinity;
80613        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
80614      }else{
80615        pLeft->iTable = regData;
80616        pLeft->affinity = SQLITE_AFF_INTEGER;
80617      }
80618    }
80619    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
80620    assert( iCol>=0 );
80621    zCol = pFKey->pFrom->aCol[iCol].zName;
80622    pRight = sqlite3Expr(db, TK_ID, zCol);
80623    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
80624    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
80625  }
80626
80627  /* If the child table is the same as the parent table, and this scan
80628  ** is taking place as part of a DELETE operation (operation D.2), omit the
80629  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
80630  ** clause, where $rowid is the rowid of the row being deleted.  */
80631  if( pTab==pFKey->pFrom && nIncr>0 ){
80632    Expr *pEq;                    /* Expression (pLeft = pRight) */
80633    Expr *pLeft;                  /* Value from parent table row */
80634    Expr *pRight;                 /* Column ref to child table */
80635    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
80636    pRight = sqlite3Expr(db, TK_COLUMN, 0);
80637    if( pLeft && pRight ){
80638      pLeft->iTable = regData;
80639      pLeft->affinity = SQLITE_AFF_INTEGER;
80640      pRight->iTable = pSrc->a[0].iCursor;
80641      pRight->iColumn = -1;
80642    }
80643    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
80644    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
80645  }
80646
80647  /* Resolve the references in the WHERE clause. */
80648  memset(&sNameContext, 0, sizeof(NameContext));
80649  sNameContext.pSrcList = pSrc;
80650  sNameContext.pParse = pParse;
80651  sqlite3ResolveExprNames(&sNameContext, pWhere);
80652
80653  /* Create VDBE to loop through the entries in pSrc that match the WHERE
80654  ** clause. If the constraint is not deferred, throw an exception for
80655  ** each row found. Otherwise, for deferred constraints, increment the
80656  ** deferred constraint counter by nIncr for each row selected.  */
80657  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
80658  if( nIncr>0 && pFKey->isDeferred==0 ){
80659    sqlite3ParseToplevel(pParse)->mayAbort = 1;
80660  }
80661  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
80662  if( pWInfo ){
80663    sqlite3WhereEnd(pWInfo);
80664  }
80665
80666  /* Clean up the WHERE clause constructed above. */
80667  sqlite3ExprDelete(db, pWhere);
80668  if( iFkIfZero ){
80669    sqlite3VdbeJumpHere(v, iFkIfZero);
80670  }
80671}
80672
80673/*
80674** This function returns a pointer to the head of a linked list of FK
80675** constraints for which table pTab is the parent table. For example,
80676** given the following schema:
80677**
80678**   CREATE TABLE t1(a PRIMARY KEY);
80679**   CREATE TABLE t2(b REFERENCES t1(a);
80680**
80681** Calling this function with table "t1" as an argument returns a pointer
80682** to the FKey structure representing the foreign key constraint on table
80683** "t2". Calling this function with "t2" as the argument would return a
80684** NULL pointer (as there are no FK constraints for which t2 is the parent
80685** table).
80686*/
80687SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
80688  int nName = sqlite3Strlen30(pTab->zName);
80689  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
80690}
80691
80692/*
80693** The second argument is a Trigger structure allocated by the
80694** fkActionTrigger() routine. This function deletes the Trigger structure
80695** and all of its sub-components.
80696**
80697** The Trigger structure or any of its sub-components may be allocated from
80698** the lookaside buffer belonging to database handle dbMem.
80699*/
80700static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
80701  if( p ){
80702    TriggerStep *pStep = p->step_list;
80703    sqlite3ExprDelete(dbMem, pStep->pWhere);
80704    sqlite3ExprListDelete(dbMem, pStep->pExprList);
80705    sqlite3SelectDelete(dbMem, pStep->pSelect);
80706    sqlite3ExprDelete(dbMem, p->pWhen);
80707    sqlite3DbFree(dbMem, p);
80708  }
80709}
80710
80711/*
80712** This function is called to generate code that runs when table pTab is
80713** being dropped from the database. The SrcList passed as the second argument
80714** to this function contains a single entry guaranteed to resolve to
80715** table pTab.
80716**
80717** Normally, no code is required. However, if either
80718**
80719**   (a) The table is the parent table of a FK constraint, or
80720**   (b) The table is the child table of a deferred FK constraint and it is
80721**       determined at runtime that there are outstanding deferred FK
80722**       constraint violations in the database,
80723**
80724** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
80725** the table from the database. Triggers are disabled while running this
80726** DELETE, but foreign key actions are not.
80727*/
80728SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
80729  sqlite3 *db = pParse->db;
80730  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
80731    int iSkip = 0;
80732    Vdbe *v = sqlite3GetVdbe(pParse);
80733
80734    assert( v );                  /* VDBE has already been allocated */
80735    if( sqlite3FkReferences(pTab)==0 ){
80736      /* Search for a deferred foreign key constraint for which this table
80737      ** is the child table. If one cannot be found, return without
80738      ** generating any VDBE code. If one can be found, then jump over
80739      ** the entire DELETE if there are no outstanding deferred constraints
80740      ** when this statement is run.  */
80741      FKey *p;
80742      for(p=pTab->pFKey; p; p=p->pNextFrom){
80743        if( p->isDeferred ) break;
80744      }
80745      if( !p ) return;
80746      iSkip = sqlite3VdbeMakeLabel(v);
80747      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
80748    }
80749
80750    pParse->disableTriggers = 1;
80751    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
80752    pParse->disableTriggers = 0;
80753
80754    /* If the DELETE has generated immediate foreign key constraint
80755    ** violations, halt the VDBE and return an error at this point, before
80756    ** any modifications to the schema are made. This is because statement
80757    ** transactions are not able to rollback schema changes.  */
80758    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
80759    sqlite3HaltConstraint(
80760        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
80761    );
80762
80763    if( iSkip ){
80764      sqlite3VdbeResolveLabel(v, iSkip);
80765    }
80766  }
80767}
80768
80769/*
80770** This function is called when inserting, deleting or updating a row of
80771** table pTab to generate VDBE code to perform foreign key constraint
80772** processing for the operation.
80773**
80774** For a DELETE operation, parameter regOld is passed the index of the
80775** first register in an array of (pTab->nCol+1) registers containing the
80776** rowid of the row being deleted, followed by each of the column values
80777** of the row being deleted, from left to right. Parameter regNew is passed
80778** zero in this case.
80779**
80780** For an INSERT operation, regOld is passed zero and regNew is passed the
80781** first register of an array of (pTab->nCol+1) registers containing the new
80782** row data.
80783**
80784** For an UPDATE operation, this function is called twice. Once before
80785** the original record is deleted from the table using the calling convention
80786** described for DELETE. Then again after the original record is deleted
80787** but before the new record is inserted using the INSERT convention.
80788*/
80789SQLITE_PRIVATE void sqlite3FkCheck(
80790  Parse *pParse,                  /* Parse context */
80791  Table *pTab,                    /* Row is being deleted from this table */
80792  int regOld,                     /* Previous row data is stored here */
80793  int regNew                      /* New row data is stored here */
80794){
80795  sqlite3 *db = pParse->db;       /* Database handle */
80796  Vdbe *v;                        /* VM to write code to */
80797  FKey *pFKey;                    /* Used to iterate through FKs */
80798  int iDb;                        /* Index of database containing pTab */
80799  const char *zDb;                /* Name of database containing pTab */
80800  int isIgnoreErrors = pParse->disableTriggers;
80801
80802  /* Exactly one of regOld and regNew should be non-zero. */
80803  assert( (regOld==0)!=(regNew==0) );
80804
80805  /* If foreign-keys are disabled, this function is a no-op. */
80806  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
80807
80808  v = sqlite3GetVdbe(pParse);
80809  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80810  zDb = db->aDb[iDb].zName;
80811
80812  /* Loop through all the foreign key constraints for which pTab is the
80813  ** child table (the table that the foreign key definition is part of).  */
80814  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
80815    Table *pTo;                   /* Parent table of foreign key pFKey */
80816    Index *pIdx = 0;              /* Index on key columns in pTo */
80817    int *aiFree = 0;
80818    int *aiCol;
80819    int iCol;
80820    int i;
80821    int isIgnore = 0;
80822
80823    /* Find the parent table of this foreign key. Also find a unique index
80824    ** on the parent key columns in the parent table. If either of these
80825    ** schema items cannot be located, set an error in pParse and return
80826    ** early.  */
80827    if( pParse->disableTriggers ){
80828      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
80829    }else{
80830      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
80831    }
80832    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
80833      if( !isIgnoreErrors || db->mallocFailed ) return;
80834      continue;
80835    }
80836    assert( pFKey->nCol==1 || (aiFree && pIdx) );
80837
80838    if( aiFree ){
80839      aiCol = aiFree;
80840    }else{
80841      iCol = pFKey->aCol[0].iFrom;
80842      aiCol = &iCol;
80843    }
80844    for(i=0; i<pFKey->nCol; i++){
80845      if( aiCol[i]==pTab->iPKey ){
80846        aiCol[i] = -1;
80847      }
80848#ifndef SQLITE_OMIT_AUTHORIZATION
80849      /* Request permission to read the parent key columns. If the
80850      ** authorization callback returns SQLITE_IGNORE, behave as if any
80851      ** values read from the parent table are NULL. */
80852      if( db->xAuth ){
80853        int rcauth;
80854        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
80855        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
80856        isIgnore = (rcauth==SQLITE_IGNORE);
80857      }
80858#endif
80859    }
80860
80861    /* Take a shared-cache advisory read-lock on the parent table. Allocate
80862    ** a cursor to use to search the unique index on the parent key columns
80863    ** in the parent table.  */
80864    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
80865    pParse->nTab++;
80866
80867    if( regOld!=0 ){
80868      /* A row is being removed from the child table. Search for the parent.
80869      ** If the parent does not exist, removing the child row resolves an
80870      ** outstanding foreign key constraint violation. */
80871      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
80872    }
80873    if( regNew!=0 ){
80874      /* A row is being added to the child table. If a parent row cannot
80875      ** be found, adding the child row has violated the FK constraint. */
80876      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
80877    }
80878
80879    sqlite3DbFree(db, aiFree);
80880  }
80881
80882  /* Loop through all the foreign key constraints that refer to this table */
80883  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
80884    Index *pIdx = 0;              /* Foreign key index for pFKey */
80885    SrcList *pSrc;
80886    int *aiCol = 0;
80887
80888    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
80889      assert( regOld==0 && regNew!=0 );
80890      /* Inserting a single row into a parent table cannot cause an immediate
80891      ** foreign key violation. So do nothing in this case.  */
80892      continue;
80893    }
80894
80895    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
80896      if( !isIgnoreErrors || db->mallocFailed ) return;
80897      continue;
80898    }
80899    assert( aiCol || pFKey->nCol==1 );
80900
80901    /* Create a SrcList structure containing a single table (the table
80902    ** the foreign key that refers to this table is attached to). This
80903    ** is required for the sqlite3WhereXXX() interface.  */
80904    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
80905    if( pSrc ){
80906      struct SrcList_item *pItem = pSrc->a;
80907      pItem->pTab = pFKey->pFrom;
80908      pItem->zName = pFKey->pFrom->zName;
80909      pItem->pTab->nRef++;
80910      pItem->iCursor = pParse->nTab++;
80911
80912      if( regNew!=0 ){
80913        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
80914      }
80915      if( regOld!=0 ){
80916        /* If there is a RESTRICT action configured for the current operation
80917        ** on the parent table of this FK, then throw an exception
80918        ** immediately if the FK constraint is violated, even if this is a
80919        ** deferred trigger. That's what RESTRICT means. To defer checking
80920        ** the constraint, the FK should specify NO ACTION (represented
80921        ** using OE_None). NO ACTION is the default.  */
80922        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
80923      }
80924      pItem->zName = 0;
80925      sqlite3SrcListDelete(db, pSrc);
80926    }
80927    sqlite3DbFree(db, aiCol);
80928  }
80929}
80930
80931#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
80932
80933/*
80934** This function is called before generating code to update or delete a
80935** row contained in table pTab.
80936*/
80937SQLITE_PRIVATE u32 sqlite3FkOldmask(
80938  Parse *pParse,                  /* Parse context */
80939  Table *pTab                     /* Table being modified */
80940){
80941  u32 mask = 0;
80942  if( pParse->db->flags&SQLITE_ForeignKeys ){
80943    FKey *p;
80944    int i;
80945    for(p=pTab->pFKey; p; p=p->pNextFrom){
80946      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
80947    }
80948    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
80949      Index *pIdx = 0;
80950      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
80951      if( pIdx ){
80952        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
80953      }
80954    }
80955  }
80956  return mask;
80957}
80958
80959/*
80960** This function is called before generating code to update or delete a
80961** row contained in table pTab. If the operation is a DELETE, then
80962** parameter aChange is passed a NULL value. For an UPDATE, aChange points
80963** to an array of size N, where N is the number of columns in table pTab.
80964** If the i'th column is not modified by the UPDATE, then the corresponding
80965** entry in the aChange[] array is set to -1. If the column is modified,
80966** the value is 0 or greater. Parameter chngRowid is set to true if the
80967** UPDATE statement modifies the rowid fields of the table.
80968**
80969** If any foreign key processing will be required, this function returns
80970** true. If there is no foreign key related processing, this function
80971** returns false.
80972*/
80973SQLITE_PRIVATE int sqlite3FkRequired(
80974  Parse *pParse,                  /* Parse context */
80975  Table *pTab,                    /* Table being modified */
80976  int *aChange,                   /* Non-NULL for UPDATE operations */
80977  int chngRowid                   /* True for UPDATE that affects rowid */
80978){
80979  if( pParse->db->flags&SQLITE_ForeignKeys ){
80980    if( !aChange ){
80981      /* A DELETE operation. Foreign key processing is required if the
80982      ** table in question is either the child or parent table for any
80983      ** foreign key constraint.  */
80984      return (sqlite3FkReferences(pTab) || pTab->pFKey);
80985    }else{
80986      /* This is an UPDATE. Foreign key processing is only required if the
80987      ** operation modifies one or more child or parent key columns. */
80988      int i;
80989      FKey *p;
80990
80991      /* Check if any child key columns are being modified. */
80992      for(p=pTab->pFKey; p; p=p->pNextFrom){
80993        for(i=0; i<p->nCol; i++){
80994          int iChildKey = p->aCol[i].iFrom;
80995          if( aChange[iChildKey]>=0 ) return 1;
80996          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
80997        }
80998      }
80999
81000      /* Check if any parent key columns are being modified. */
81001      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81002        for(i=0; i<p->nCol; i++){
81003          char *zKey = p->aCol[i].zCol;
81004          int iKey;
81005          for(iKey=0; iKey<pTab->nCol; iKey++){
81006            Column *pCol = &pTab->aCol[iKey];
81007            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
81008              if( aChange[iKey]>=0 ) return 1;
81009              if( iKey==pTab->iPKey && chngRowid ) return 1;
81010            }
81011          }
81012        }
81013      }
81014    }
81015  }
81016  return 0;
81017}
81018
81019/*
81020** This function is called when an UPDATE or DELETE operation is being
81021** compiled on table pTab, which is the parent table of foreign-key pFKey.
81022** If the current operation is an UPDATE, then the pChanges parameter is
81023** passed a pointer to the list of columns being modified. If it is a
81024** DELETE, pChanges is passed a NULL pointer.
81025**
81026** It returns a pointer to a Trigger structure containing a trigger
81027** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
81028** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
81029** returned (these actions require no special handling by the triggers
81030** sub-system, code for them is created by fkScanChildren()).
81031**
81032** For example, if pFKey is the foreign key and pTab is table "p" in
81033** the following schema:
81034**
81035**   CREATE TABLE p(pk PRIMARY KEY);
81036**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
81037**
81038** then the returned trigger structure is equivalent to:
81039**
81040**   CREATE TRIGGER ... DELETE ON p BEGIN
81041**     DELETE FROM c WHERE ck = old.pk;
81042**   END;
81043**
81044** The returned pointer is cached as part of the foreign key object. It
81045** is eventually freed along with the rest of the foreign key object by
81046** sqlite3FkDelete().
81047*/
81048static Trigger *fkActionTrigger(
81049  Parse *pParse,                  /* Parse context */
81050  Table *pTab,                    /* Table being updated or deleted from */
81051  FKey *pFKey,                    /* Foreign key to get action for */
81052  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
81053){
81054  sqlite3 *db = pParse->db;       /* Database handle */
81055  int action;                     /* One of OE_None, OE_Cascade etc. */
81056  Trigger *pTrigger;              /* Trigger definition to return */
81057  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
81058
81059  action = pFKey->aAction[iAction];
81060  pTrigger = pFKey->apTrigger[iAction];
81061
81062  if( action!=OE_None && !pTrigger ){
81063    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
81064    char const *zFrom;            /* Name of child table */
81065    int nFrom;                    /* Length in bytes of zFrom */
81066    Index *pIdx = 0;              /* Parent key index for this FK */
81067    int *aiCol = 0;               /* child table cols -> parent key cols */
81068    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
81069    Expr *pWhere = 0;             /* WHERE clause of trigger step */
81070    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
81071    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
81072    int i;                        /* Iterator variable */
81073    Expr *pWhen = 0;              /* WHEN clause for the trigger */
81074
81075    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
81076    assert( aiCol || pFKey->nCol==1 );
81077
81078    for(i=0; i<pFKey->nCol; i++){
81079      Token tOld = { "old", 3 };  /* Literal "old" token */
81080      Token tNew = { "new", 3 };  /* Literal "new" token */
81081      Token tFromCol;             /* Name of column in child table */
81082      Token tToCol;               /* Name of column in parent table */
81083      int iFromCol;               /* Idx of column in child table */
81084      Expr *pEq;                  /* tFromCol = OLD.tToCol */
81085
81086      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
81087      assert( iFromCol>=0 );
81088      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
81089      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
81090
81091      tToCol.n = sqlite3Strlen30(tToCol.z);
81092      tFromCol.n = sqlite3Strlen30(tFromCol.z);
81093
81094      /* Create the expression "OLD.zToCol = zFromCol". It is important
81095      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
81096      ** that the affinity and collation sequence associated with the
81097      ** parent table are used for the comparison. */
81098      pEq = sqlite3PExpr(pParse, TK_EQ,
81099          sqlite3PExpr(pParse, TK_DOT,
81100            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
81101            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
81102          , 0),
81103          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
81104      , 0);
81105      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81106
81107      /* For ON UPDATE, construct the next term of the WHEN clause.
81108      ** The final WHEN clause will be like this:
81109      **
81110      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
81111      */
81112      if( pChanges ){
81113        pEq = sqlite3PExpr(pParse, TK_IS,
81114            sqlite3PExpr(pParse, TK_DOT,
81115              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
81116              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
81117              0),
81118            sqlite3PExpr(pParse, TK_DOT,
81119              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
81120              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
81121              0),
81122            0);
81123        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
81124      }
81125
81126      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
81127        Expr *pNew;
81128        if( action==OE_Cascade ){
81129          pNew = sqlite3PExpr(pParse, TK_DOT,
81130            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
81131            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
81132          , 0);
81133        }else if( action==OE_SetDflt ){
81134          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
81135          if( pDflt ){
81136            pNew = sqlite3ExprDup(db, pDflt, 0);
81137          }else{
81138            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
81139          }
81140        }else{
81141          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
81142        }
81143        pList = sqlite3ExprListAppend(pParse, pList, pNew);
81144        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
81145      }
81146    }
81147    sqlite3DbFree(db, aiCol);
81148
81149    zFrom = pFKey->pFrom->zName;
81150    nFrom = sqlite3Strlen30(zFrom);
81151
81152    if( action==OE_Restrict ){
81153      Token tFrom;
81154      Expr *pRaise;
81155
81156      tFrom.z = zFrom;
81157      tFrom.n = nFrom;
81158      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
81159      if( pRaise ){
81160        pRaise->affinity = OE_Abort;
81161      }
81162      pSelect = sqlite3SelectNew(pParse,
81163          sqlite3ExprListAppend(pParse, 0, pRaise),
81164          sqlite3SrcListAppend(db, 0, &tFrom, 0),
81165          pWhere,
81166          0, 0, 0, 0, 0, 0
81167      );
81168      pWhere = 0;
81169    }
81170
81171    /* Disable lookaside memory allocation */
81172    enableLookaside = db->lookaside.bEnabled;
81173    db->lookaside.bEnabled = 0;
81174
81175    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
81176        sizeof(Trigger) +         /* struct Trigger */
81177        sizeof(TriggerStep) +     /* Single step in trigger program */
81178        nFrom + 1                 /* Space for pStep->target.z */
81179    );
81180    if( pTrigger ){
81181      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
81182      pStep->target.z = (char *)&pStep[1];
81183      pStep->target.n = nFrom;
81184      memcpy((char *)pStep->target.z, zFrom, nFrom);
81185
81186      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
81187      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
81188      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
81189      if( pWhen ){
81190        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
81191        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
81192      }
81193    }
81194
81195    /* Re-enable the lookaside buffer, if it was disabled earlier. */
81196    db->lookaside.bEnabled = enableLookaside;
81197
81198    sqlite3ExprDelete(db, pWhere);
81199    sqlite3ExprDelete(db, pWhen);
81200    sqlite3ExprListDelete(db, pList);
81201    sqlite3SelectDelete(db, pSelect);
81202    if( db->mallocFailed==1 ){
81203      fkTriggerDelete(db, pTrigger);
81204      return 0;
81205    }
81206
81207    switch( action ){
81208      case OE_Restrict:
81209        pStep->op = TK_SELECT;
81210        break;
81211      case OE_Cascade:
81212        if( !pChanges ){
81213          pStep->op = TK_DELETE;
81214          break;
81215        }
81216      default:
81217        pStep->op = TK_UPDATE;
81218    }
81219    pStep->pTrig = pTrigger;
81220    pTrigger->pSchema = pTab->pSchema;
81221    pTrigger->pTabSchema = pTab->pSchema;
81222    pFKey->apTrigger[iAction] = pTrigger;
81223    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
81224  }
81225
81226  return pTrigger;
81227}
81228
81229/*
81230** This function is called when deleting or updating a row to implement
81231** any required CASCADE, SET NULL or SET DEFAULT actions.
81232*/
81233SQLITE_PRIVATE void sqlite3FkActions(
81234  Parse *pParse,                  /* Parse context */
81235  Table *pTab,                    /* Table being updated or deleted from */
81236  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
81237  int regOld                      /* Address of array containing old row */
81238){
81239  /* If foreign-key support is enabled, iterate through all FKs that
81240  ** refer to table pTab. If there is an action associated with the FK
81241  ** for this operation (either update or delete), invoke the associated
81242  ** trigger sub-program.  */
81243  if( pParse->db->flags&SQLITE_ForeignKeys ){
81244    FKey *pFKey;                  /* Iterator variable */
81245    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
81246      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
81247      if( pAction ){
81248        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
81249      }
81250    }
81251  }
81252}
81253
81254#endif /* ifndef SQLITE_OMIT_TRIGGER */
81255
81256/*
81257** Free all memory associated with foreign key definitions attached to
81258** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
81259** hash table.
81260*/
81261SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
81262  FKey *pFKey;                    /* Iterator variable */
81263  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
81264
81265  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
81266
81267    /* Remove the FK from the fkeyHash hash table. */
81268    if( !db || db->pnBytesFreed==0 ){
81269      if( pFKey->pPrevTo ){
81270        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
81271      }else{
81272        void *p = (void *)pFKey->pNextTo;
81273        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
81274        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
81275      }
81276      if( pFKey->pNextTo ){
81277        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
81278      }
81279    }
81280
81281    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
81282    ** classified as either immediate or deferred.
81283    */
81284    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
81285
81286    /* Delete any triggers created to implement actions for this FK. */
81287#ifndef SQLITE_OMIT_TRIGGER
81288    fkTriggerDelete(db, pFKey->apTrigger[0]);
81289    fkTriggerDelete(db, pFKey->apTrigger[1]);
81290#endif
81291
81292    pNext = pFKey->pNextFrom;
81293    sqlite3DbFree(db, pFKey);
81294  }
81295}
81296#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
81297
81298/************** End of fkey.c ************************************************/
81299/************** Begin file insert.c ******************************************/
81300/*
81301** 2001 September 15
81302**
81303** The author disclaims copyright to this source code.  In place of
81304** a legal notice, here is a blessing:
81305**
81306**    May you do good and not evil.
81307**    May you find forgiveness for yourself and forgive others.
81308**    May you share freely, never taking more than you give.
81309**
81310*************************************************************************
81311** This file contains C code routines that are called by the parser
81312** to handle INSERT statements in SQLite.
81313*/
81314
81315/*
81316** Generate code that will open a table for reading.
81317*/
81318SQLITE_PRIVATE void sqlite3OpenTable(
81319  Parse *p,       /* Generate code into this VDBE */
81320  int iCur,       /* The cursor number of the table */
81321  int iDb,        /* The database index in sqlite3.aDb[] */
81322  Table *pTab,    /* The table to be opened */
81323  int opcode      /* OP_OpenRead or OP_OpenWrite */
81324){
81325  Vdbe *v;
81326  if( IsVirtual(pTab) ) return;
81327  v = sqlite3GetVdbe(p);
81328  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
81329  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
81330  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
81331  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
81332  VdbeComment((v, "%s", pTab->zName));
81333}
81334
81335/*
81336** Return a pointer to the column affinity string associated with index
81337** pIdx. A column affinity string has one character for each column in
81338** the table, according to the affinity of the column:
81339**
81340**  Character      Column affinity
81341**  ------------------------------
81342**  'a'            TEXT
81343**  'b'            NONE
81344**  'c'            NUMERIC
81345**  'd'            INTEGER
81346**  'e'            REAL
81347**
81348** An extra 'b' is appended to the end of the string to cover the
81349** rowid that appears as the last column in every index.
81350**
81351** Memory for the buffer containing the column index affinity string
81352** is managed along with the rest of the Index structure. It will be
81353** released when sqlite3DeleteIndex() is called.
81354*/
81355SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
81356  if( !pIdx->zColAff ){
81357    /* The first time a column affinity string for a particular index is
81358    ** required, it is allocated and populated here. It is then stored as
81359    ** a member of the Index structure for subsequent use.
81360    **
81361    ** The column affinity string will eventually be deleted by
81362    ** sqliteDeleteIndex() when the Index structure itself is cleaned
81363    ** up.
81364    */
81365    int n;
81366    Table *pTab = pIdx->pTable;
81367    sqlite3 *db = sqlite3VdbeDb(v);
81368    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
81369    if( !pIdx->zColAff ){
81370      db->mallocFailed = 1;
81371      return 0;
81372    }
81373    for(n=0; n<pIdx->nColumn; n++){
81374      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
81375    }
81376    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
81377    pIdx->zColAff[n] = 0;
81378  }
81379
81380  return pIdx->zColAff;
81381}
81382
81383/*
81384** Set P4 of the most recently inserted opcode to a column affinity
81385** string for table pTab. A column affinity string has one character
81386** for each column indexed by the index, according to the affinity of the
81387** column:
81388**
81389**  Character      Column affinity
81390**  ------------------------------
81391**  'a'            TEXT
81392**  'b'            NONE
81393**  'c'            NUMERIC
81394**  'd'            INTEGER
81395**  'e'            REAL
81396*/
81397SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
81398  /* The first time a column affinity string for a particular table
81399  ** is required, it is allocated and populated here. It is then
81400  ** stored as a member of the Table structure for subsequent use.
81401  **
81402  ** The column affinity string will eventually be deleted by
81403  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
81404  */
81405  if( !pTab->zColAff ){
81406    char *zColAff;
81407    int i;
81408    sqlite3 *db = sqlite3VdbeDb(v);
81409
81410    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
81411    if( !zColAff ){
81412      db->mallocFailed = 1;
81413      return;
81414    }
81415
81416    for(i=0; i<pTab->nCol; i++){
81417      zColAff[i] = pTab->aCol[i].affinity;
81418    }
81419    zColAff[pTab->nCol] = '\0';
81420
81421    pTab->zColAff = zColAff;
81422  }
81423
81424  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
81425}
81426
81427/*
81428** Return non-zero if the table pTab in database iDb or any of its indices
81429** have been opened at any point in the VDBE program beginning at location
81430** iStartAddr throught the end of the program.  This is used to see if
81431** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
81432** run without using temporary table for the results of the SELECT.
81433*/
81434static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
81435  Vdbe *v = sqlite3GetVdbe(p);
81436  int i;
81437  int iEnd = sqlite3VdbeCurrentAddr(v);
81438#ifndef SQLITE_OMIT_VIRTUALTABLE
81439  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
81440#endif
81441
81442  for(i=iStartAddr; i<iEnd; i++){
81443    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
81444    assert( pOp!=0 );
81445    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
81446      Index *pIndex;
81447      int tnum = pOp->p2;
81448      if( tnum==pTab->tnum ){
81449        return 1;
81450      }
81451      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
81452        if( tnum==pIndex->tnum ){
81453          return 1;
81454        }
81455      }
81456    }
81457#ifndef SQLITE_OMIT_VIRTUALTABLE
81458    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
81459      assert( pOp->p4.pVtab!=0 );
81460      assert( pOp->p4type==P4_VTAB );
81461      return 1;
81462    }
81463#endif
81464  }
81465  return 0;
81466}
81467
81468#ifndef SQLITE_OMIT_AUTOINCREMENT
81469/*
81470** Locate or create an AutoincInfo structure associated with table pTab
81471** which is in database iDb.  Return the register number for the register
81472** that holds the maximum rowid.
81473**
81474** There is at most one AutoincInfo structure per table even if the
81475** same table is autoincremented multiple times due to inserts within
81476** triggers.  A new AutoincInfo structure is created if this is the
81477** first use of table pTab.  On 2nd and subsequent uses, the original
81478** AutoincInfo structure is used.
81479**
81480** Three memory locations are allocated:
81481**
81482**   (1)  Register to hold the name of the pTab table.
81483**   (2)  Register to hold the maximum ROWID of pTab.
81484**   (3)  Register to hold the rowid in sqlite_sequence of pTab
81485**
81486** The 2nd register is the one that is returned.  That is all the
81487** insert routine needs to know about.
81488*/
81489static int autoIncBegin(
81490  Parse *pParse,      /* Parsing context */
81491  int iDb,            /* Index of the database holding pTab */
81492  Table *pTab         /* The table we are writing to */
81493){
81494  int memId = 0;      /* Register holding maximum rowid */
81495  if( pTab->tabFlags & TF_Autoincrement ){
81496    Parse *pToplevel = sqlite3ParseToplevel(pParse);
81497    AutoincInfo *pInfo;
81498
81499    pInfo = pToplevel->pAinc;
81500    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
81501    if( pInfo==0 ){
81502      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
81503      if( pInfo==0 ) return 0;
81504      pInfo->pNext = pToplevel->pAinc;
81505      pToplevel->pAinc = pInfo;
81506      pInfo->pTab = pTab;
81507      pInfo->iDb = iDb;
81508      pToplevel->nMem++;                  /* Register to hold name of table */
81509      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
81510      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
81511    }
81512    memId = pInfo->regCtr;
81513  }
81514  return memId;
81515}
81516
81517/*
81518** This routine generates code that will initialize all of the
81519** register used by the autoincrement tracker.
81520*/
81521SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
81522  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
81523  sqlite3 *db = pParse->db;  /* The database connection */
81524  Db *pDb;                   /* Database only autoinc table */
81525  int memId;                 /* Register holding max rowid */
81526  int addr;                  /* A VDBE address */
81527  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
81528
81529  /* This routine is never called during trigger-generation.  It is
81530  ** only called from the top-level */
81531  assert( pParse->pTriggerTab==0 );
81532  assert( pParse==sqlite3ParseToplevel(pParse) );
81533
81534  assert( v );   /* We failed long ago if this is not so */
81535  for(p = pParse->pAinc; p; p = p->pNext){
81536    pDb = &db->aDb[p->iDb];
81537    memId = p->regCtr;
81538    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
81539    addr = sqlite3VdbeCurrentAddr(v);
81540    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
81541    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
81542    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
81543    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
81544    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
81545    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
81546    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
81547    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
81548    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
81549    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
81550    sqlite3VdbeAddOp0(v, OP_Close);
81551  }
81552}
81553
81554/*
81555** Update the maximum rowid for an autoincrement calculation.
81556**
81557** This routine should be called when the top of the stack holds a
81558** new rowid that is about to be inserted.  If that new rowid is
81559** larger than the maximum rowid in the memId memory cell, then the
81560** memory cell is updated.  The stack is unchanged.
81561*/
81562static void autoIncStep(Parse *pParse, int memId, int regRowid){
81563  if( memId>0 ){
81564    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
81565  }
81566}
81567
81568/*
81569** This routine generates the code needed to write autoincrement
81570** maximum rowid values back into the sqlite_sequence register.
81571** Every statement that might do an INSERT into an autoincrement
81572** table (either directly or through triggers) needs to call this
81573** routine just before the "exit" code.
81574*/
81575SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
81576  AutoincInfo *p;
81577  Vdbe *v = pParse->pVdbe;
81578  sqlite3 *db = pParse->db;
81579
81580  assert( v );
81581  for(p = pParse->pAinc; p; p = p->pNext){
81582    Db *pDb = &db->aDb[p->iDb];
81583    int j1, j2, j3, j4, j5;
81584    int iRec;
81585    int memId = p->regCtr;
81586
81587    iRec = sqlite3GetTempReg(pParse);
81588    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
81589    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
81590    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
81591    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
81592    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
81593    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
81594    sqlite3VdbeJumpHere(v, j2);
81595    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
81596    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
81597    sqlite3VdbeJumpHere(v, j4);
81598    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
81599    sqlite3VdbeJumpHere(v, j1);
81600    sqlite3VdbeJumpHere(v, j5);
81601    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
81602    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
81603    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81604    sqlite3VdbeAddOp0(v, OP_Close);
81605    sqlite3ReleaseTempReg(pParse, iRec);
81606  }
81607}
81608#else
81609/*
81610** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
81611** above are all no-ops
81612*/
81613# define autoIncBegin(A,B,C) (0)
81614# define autoIncStep(A,B,C)
81615#endif /* SQLITE_OMIT_AUTOINCREMENT */
81616
81617
81618/* Forward declaration */
81619static int xferOptimization(
81620  Parse *pParse,        /* Parser context */
81621  Table *pDest,         /* The table we are inserting into */
81622  Select *pSelect,      /* A SELECT statement to use as the data source */
81623  int onError,          /* How to handle constraint errors */
81624  int iDbDest           /* The database of pDest */
81625);
81626
81627/*
81628** This routine is call to handle SQL of the following forms:
81629**
81630**    insert into TABLE (IDLIST) values(EXPRLIST)
81631**    insert into TABLE (IDLIST) select
81632**
81633** The IDLIST following the table name is always optional.  If omitted,
81634** then a list of all columns for the table is substituted.  The IDLIST
81635** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
81636**
81637** The pList parameter holds EXPRLIST in the first form of the INSERT
81638** statement above, and pSelect is NULL.  For the second form, pList is
81639** NULL and pSelect is a pointer to the select statement used to generate
81640** data for the insert.
81641**
81642** The code generated follows one of four templates.  For a simple
81643** select with data coming from a VALUES clause, the code executes
81644** once straight down through.  Pseudo-code follows (we call this
81645** the "1st template"):
81646**
81647**         open write cursor to <table> and its indices
81648**         puts VALUES clause expressions onto the stack
81649**         write the resulting record into <table>
81650**         cleanup
81651**
81652** The three remaining templates assume the statement is of the form
81653**
81654**   INSERT INTO <table> SELECT ...
81655**
81656** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
81657** in other words if the SELECT pulls all columns from a single table
81658** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
81659** if <table2> and <table1> are distinct tables but have identical
81660** schemas, including all the same indices, then a special optimization
81661** is invoked that copies raw records from <table2> over to <table1>.
81662** See the xferOptimization() function for the implementation of this
81663** template.  This is the 2nd template.
81664**
81665**         open a write cursor to <table>
81666**         open read cursor on <table2>
81667**         transfer all records in <table2> over to <table>
81668**         close cursors
81669**         foreach index on <table>
81670**           open a write cursor on the <table> index
81671**           open a read cursor on the corresponding <table2> index
81672**           transfer all records from the read to the write cursors
81673**           close cursors
81674**         end foreach
81675**
81676** The 3rd template is for when the second template does not apply
81677** and the SELECT clause does not read from <table> at any time.
81678** The generated code follows this template:
81679**
81680**         EOF <- 0
81681**         X <- A
81682**         goto B
81683**      A: setup for the SELECT
81684**         loop over the rows in the SELECT
81685**           load values into registers R..R+n
81686**           yield X
81687**         end loop
81688**         cleanup after the SELECT
81689**         EOF <- 1
81690**         yield X
81691**         goto A
81692**      B: open write cursor to <table> and its indices
81693**      C: yield X
81694**         if EOF goto D
81695**         insert the select result into <table> from R..R+n
81696**         goto C
81697**      D: cleanup
81698**
81699** The 4th template is used if the insert statement takes its
81700** values from a SELECT but the data is being inserted into a table
81701** that is also read as part of the SELECT.  In the third form,
81702** we have to use a intermediate table to store the results of
81703** the select.  The template is like this:
81704**
81705**         EOF <- 0
81706**         X <- A
81707**         goto B
81708**      A: setup for the SELECT
81709**         loop over the tables in the SELECT
81710**           load value into register R..R+n
81711**           yield X
81712**         end loop
81713**         cleanup after the SELECT
81714**         EOF <- 1
81715**         yield X
81716**         halt-error
81717**      B: open temp table
81718**      L: yield X
81719**         if EOF goto M
81720**         insert row from R..R+n into temp table
81721**         goto L
81722**      M: open write cursor to <table> and its indices
81723**         rewind temp table
81724**      C: loop over rows of intermediate table
81725**           transfer values form intermediate table into <table>
81726**         end loop
81727**      D: cleanup
81728*/
81729SQLITE_PRIVATE void sqlite3Insert(
81730  Parse *pParse,        /* Parser context */
81731  SrcList *pTabList,    /* Name of table into which we are inserting */
81732  ExprList *pList,      /* List of values to be inserted */
81733  Select *pSelect,      /* A SELECT statement to use as the data source */
81734  IdList *pColumn,      /* Column names corresponding to IDLIST. */
81735  int onError           /* How to handle constraint errors */
81736){
81737  sqlite3 *db;          /* The main database structure */
81738  Table *pTab;          /* The table to insert into.  aka TABLE */
81739  char *zTab;           /* Name of the table into which we are inserting */
81740  const char *zDb;      /* Name of the database holding this table */
81741  int i, j, idx;        /* Loop counters */
81742  Vdbe *v;              /* Generate code into this virtual machine */
81743  Index *pIdx;          /* For looping over indices of the table */
81744  int nColumn;          /* Number of columns in the data */
81745  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
81746  int baseCur = 0;      /* VDBE Cursor number for pTab */
81747  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
81748  int endOfLoop;        /* Label for the end of the insertion loop */
81749  int useTempTable = 0; /* Store SELECT results in intermediate table */
81750  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
81751  int addrInsTop = 0;   /* Jump to label "D" */
81752  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
81753  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
81754  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
81755  int iDb;              /* Index of database holding TABLE */
81756  Db *pDb;              /* The database containing table being inserted into */
81757  int appendFlag = 0;   /* True if the insert is likely to be an append */
81758
81759  /* Register allocations */
81760  int regFromSelect = 0;/* Base register for data coming from SELECT */
81761  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
81762  int regRowCount = 0;  /* Memory cell used for the row counter */
81763  int regIns;           /* Block of regs holding rowid+data being inserted */
81764  int regRowid;         /* registers holding insert rowid */
81765  int regData;          /* register holding first column to insert */
81766  int regRecord;        /* Holds the assemblied row record */
81767  int regEof = 0;       /* Register recording end of SELECT data */
81768  int *aRegIdx = 0;     /* One register allocated to each index */
81769
81770#ifndef SQLITE_OMIT_TRIGGER
81771  int isView;                 /* True if attempting to insert into a view */
81772  Trigger *pTrigger;          /* List of triggers on pTab, if required */
81773  int tmask;                  /* Mask of trigger times */
81774#endif
81775
81776  db = pParse->db;
81777  memset(&dest, 0, sizeof(dest));
81778  if( pParse->nErr || db->mallocFailed ){
81779    goto insert_cleanup;
81780  }
81781
81782  /* Locate the table into which we will be inserting new information.
81783  */
81784  assert( pTabList->nSrc==1 );
81785  zTab = pTabList->a[0].zName;
81786  if( NEVER(zTab==0) ) goto insert_cleanup;
81787  pTab = sqlite3SrcListLookup(pParse, pTabList);
81788  if( pTab==0 ){
81789    goto insert_cleanup;
81790  }
81791  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81792  assert( iDb<db->nDb );
81793  pDb = &db->aDb[iDb];
81794  zDb = pDb->zName;
81795  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
81796    goto insert_cleanup;
81797  }
81798
81799  /* Figure out if we have any triggers and if the table being
81800  ** inserted into is a view
81801  */
81802#ifndef SQLITE_OMIT_TRIGGER
81803  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
81804  isView = pTab->pSelect!=0;
81805#else
81806# define pTrigger 0
81807# define tmask 0
81808# define isView 0
81809#endif
81810#ifdef SQLITE_OMIT_VIEW
81811# undef isView
81812# define isView 0
81813#endif
81814  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
81815
81816  /* If pTab is really a view, make sure it has been initialized.
81817  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
81818  ** module table).
81819  */
81820  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81821    goto insert_cleanup;
81822  }
81823
81824  /* Ensure that:
81825  *  (a) the table is not read-only,
81826  *  (b) that if it is a view then ON INSERT triggers exist
81827  */
81828  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
81829    goto insert_cleanup;
81830  }
81831
81832  /* Allocate a VDBE
81833  */
81834  v = sqlite3GetVdbe(pParse);
81835  if( v==0 ) goto insert_cleanup;
81836  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81837  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
81838
81839#ifndef SQLITE_OMIT_XFER_OPT
81840  /* If the statement is of the form
81841  **
81842  **       INSERT INTO <table1> SELECT * FROM <table2>;
81843  **
81844  ** Then special optimizations can be applied that make the transfer
81845  ** very fast and which reduce fragmentation of indices.
81846  **
81847  ** This is the 2nd template.
81848  */
81849  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
81850    assert( !pTrigger );
81851    assert( pList==0 );
81852    goto insert_end;
81853  }
81854#endif /* SQLITE_OMIT_XFER_OPT */
81855
81856  /* If this is an AUTOINCREMENT table, look up the sequence number in the
81857  ** sqlite_sequence table and store it in memory cell regAutoinc.
81858  */
81859  regAutoinc = autoIncBegin(pParse, iDb, pTab);
81860
81861  /* Figure out how many columns of data are supplied.  If the data
81862  ** is coming from a SELECT statement, then generate a co-routine that
81863  ** produces a single row of the SELECT on each invocation.  The
81864  ** co-routine is the common header to the 3rd and 4th templates.
81865  */
81866  if( pSelect ){
81867    /* Data is coming from a SELECT.  Generate code to implement that SELECT
81868    ** as a co-routine.  The code is common to both the 3rd and 4th
81869    ** templates:
81870    **
81871    **         EOF <- 0
81872    **         X <- A
81873    **         goto B
81874    **      A: setup for the SELECT
81875    **         loop over the tables in the SELECT
81876    **           load value into register R..R+n
81877    **           yield X
81878    **         end loop
81879    **         cleanup after the SELECT
81880    **         EOF <- 1
81881    **         yield X
81882    **         halt-error
81883    **
81884    ** On each invocation of the co-routine, it puts a single row of the
81885    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
81886    ** (These output registers are allocated by sqlite3Select().)  When
81887    ** the SELECT completes, it sets the EOF flag stored in regEof.
81888    */
81889    int rc, j1;
81890
81891    regEof = ++pParse->nMem;
81892    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
81893    VdbeComment((v, "SELECT eof flag"));
81894    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
81895    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
81896    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
81897    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
81898    VdbeComment((v, "Jump over SELECT coroutine"));
81899
81900    /* Resolve the expressions in the SELECT statement and execute it. */
81901    rc = sqlite3Select(pParse, pSelect, &dest);
81902    assert( pParse->nErr==0 || rc );
81903    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
81904      goto insert_cleanup;
81905    }
81906    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
81907    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
81908    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
81909    VdbeComment((v, "End of SELECT coroutine"));
81910    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
81911
81912    regFromSelect = dest.iMem;
81913    assert( pSelect->pEList );
81914    nColumn = pSelect->pEList->nExpr;
81915    assert( dest.nMem==nColumn );
81916
81917    /* Set useTempTable to TRUE if the result of the SELECT statement
81918    ** should be written into a temporary table (template 4).  Set to
81919    ** FALSE if each* row of the SELECT can be written directly into
81920    ** the destination table (template 3).
81921    **
81922    ** A temp table must be used if the table being updated is also one
81923    ** of the tables being read by the SELECT statement.  Also use a
81924    ** temp table in the case of row triggers.
81925    */
81926    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
81927      useTempTable = 1;
81928    }
81929
81930    if( useTempTable ){
81931      /* Invoke the coroutine to extract information from the SELECT
81932      ** and add it to a transient table srcTab.  The code generated
81933      ** here is from the 4th template:
81934      **
81935      **      B: open temp table
81936      **      L: yield X
81937      **         if EOF goto M
81938      **         insert row from R..R+n into temp table
81939      **         goto L
81940      **      M: ...
81941      */
81942      int regRec;          /* Register to hold packed record */
81943      int regTempRowid;    /* Register to hold temp table ROWID */
81944      int addrTop;         /* Label "L" */
81945      int addrIf;          /* Address of jump to M */
81946
81947      srcTab = pParse->nTab++;
81948      regRec = sqlite3GetTempReg(pParse);
81949      regTempRowid = sqlite3GetTempReg(pParse);
81950      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
81951      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
81952      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
81953      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
81954      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
81955      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
81956      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
81957      sqlite3VdbeJumpHere(v, addrIf);
81958      sqlite3ReleaseTempReg(pParse, regRec);
81959      sqlite3ReleaseTempReg(pParse, regTempRowid);
81960    }
81961  }else{
81962    /* This is the case if the data for the INSERT is coming from a VALUES
81963    ** clause
81964    */
81965    NameContext sNC;
81966    memset(&sNC, 0, sizeof(sNC));
81967    sNC.pParse = pParse;
81968    srcTab = -1;
81969    assert( useTempTable==0 );
81970    nColumn = pList ? pList->nExpr : 0;
81971    for(i=0; i<nColumn; i++){
81972      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
81973        goto insert_cleanup;
81974      }
81975    }
81976  }
81977
81978  /* Make sure the number of columns in the source data matches the number
81979  ** of columns to be inserted into the table.
81980  */
81981  if( IsVirtual(pTab) ){
81982    for(i=0; i<pTab->nCol; i++){
81983      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
81984    }
81985  }
81986  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
81987    sqlite3ErrorMsg(pParse,
81988       "table %S has %d columns but %d values were supplied",
81989       pTabList, 0, pTab->nCol-nHidden, nColumn);
81990    goto insert_cleanup;
81991  }
81992  if( pColumn!=0 && nColumn!=pColumn->nId ){
81993    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
81994    goto insert_cleanup;
81995  }
81996
81997  /* If the INSERT statement included an IDLIST term, then make sure
81998  ** all elements of the IDLIST really are columns of the table and
81999  ** remember the column indices.
82000  **
82001  ** If the table has an INTEGER PRIMARY KEY column and that column
82002  ** is named in the IDLIST, then record in the keyColumn variable
82003  ** the index into IDLIST of the primary key column.  keyColumn is
82004  ** the index of the primary key as it appears in IDLIST, not as
82005  ** is appears in the original table.  (The index of the primary
82006  ** key in the original table is pTab->iPKey.)
82007  */
82008  if( pColumn ){
82009    for(i=0; i<pColumn->nId; i++){
82010      pColumn->a[i].idx = -1;
82011    }
82012    for(i=0; i<pColumn->nId; i++){
82013      for(j=0; j<pTab->nCol; j++){
82014        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
82015          pColumn->a[i].idx = j;
82016          if( j==pTab->iPKey ){
82017            keyColumn = i;
82018          }
82019          break;
82020        }
82021      }
82022      if( j>=pTab->nCol ){
82023        if( sqlite3IsRowid(pColumn->a[i].zName) ){
82024          keyColumn = i;
82025        }else{
82026          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
82027              pTabList, 0, pColumn->a[i].zName);
82028          pParse->checkSchema = 1;
82029          goto insert_cleanup;
82030        }
82031      }
82032    }
82033  }
82034
82035  /* If there is no IDLIST term but the table has an integer primary
82036  ** key, the set the keyColumn variable to the primary key column index
82037  ** in the original table definition.
82038  */
82039  if( pColumn==0 && nColumn>0 ){
82040    keyColumn = pTab->iPKey;
82041  }
82042
82043  /* Initialize the count of rows to be inserted
82044  */
82045  if( db->flags & SQLITE_CountRows ){
82046    regRowCount = ++pParse->nMem;
82047    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
82048  }
82049
82050  /* If this is not a view, open the table and and all indices */
82051  if( !isView ){
82052    int nIdx;
82053
82054    baseCur = pParse->nTab;
82055    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
82056    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
82057    if( aRegIdx==0 ){
82058      goto insert_cleanup;
82059    }
82060    for(i=0; i<nIdx; i++){
82061      aRegIdx[i] = ++pParse->nMem;
82062    }
82063  }
82064
82065  /* This is the top of the main insertion loop */
82066  if( useTempTable ){
82067    /* This block codes the top of loop only.  The complete loop is the
82068    ** following pseudocode (template 4):
82069    **
82070    **         rewind temp table
82071    **      C: loop over rows of intermediate table
82072    **           transfer values form intermediate table into <table>
82073    **         end loop
82074    **      D: ...
82075    */
82076    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
82077    addrCont = sqlite3VdbeCurrentAddr(v);
82078  }else if( pSelect ){
82079    /* This block codes the top of loop only.  The complete loop is the
82080    ** following pseudocode (template 3):
82081    **
82082    **      C: yield X
82083    **         if EOF goto D
82084    **         insert the select result into <table> from R..R+n
82085    **         goto C
82086    **      D: ...
82087    */
82088    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
82089    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
82090  }
82091
82092  /* Allocate registers for holding the rowid of the new row,
82093  ** the content of the new row, and the assemblied row record.
82094  */
82095  regRecord = ++pParse->nMem;
82096  regRowid = regIns = pParse->nMem+1;
82097  pParse->nMem += pTab->nCol + 1;
82098  if( IsVirtual(pTab) ){
82099    regRowid++;
82100    pParse->nMem++;
82101  }
82102  regData = regRowid+1;
82103
82104  /* Run the BEFORE and INSTEAD OF triggers, if there are any
82105  */
82106  endOfLoop = sqlite3VdbeMakeLabel(v);
82107  if( tmask & TRIGGER_BEFORE ){
82108    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
82109
82110    /* build the NEW.* reference row.  Note that if there is an INTEGER
82111    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
82112    ** translated into a unique ID for the row.  But on a BEFORE trigger,
82113    ** we do not know what the unique ID will be (because the insert has
82114    ** not happened yet) so we substitute a rowid of -1
82115    */
82116    if( keyColumn<0 ){
82117      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
82118    }else{
82119      int j1;
82120      if( useTempTable ){
82121        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
82122      }else{
82123        assert( pSelect==0 );  /* Otherwise useTempTable is true */
82124        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
82125      }
82126      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
82127      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
82128      sqlite3VdbeJumpHere(v, j1);
82129      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
82130    }
82131
82132    /* Cannot have triggers on a virtual table. If it were possible,
82133    ** this block would have to account for hidden column.
82134    */
82135    assert( !IsVirtual(pTab) );
82136
82137    /* Create the new column data
82138    */
82139    for(i=0; i<pTab->nCol; i++){
82140      if( pColumn==0 ){
82141        j = i;
82142      }else{
82143        for(j=0; j<pColumn->nId; j++){
82144          if( pColumn->a[j].idx==i ) break;
82145        }
82146      }
82147      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
82148        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
82149      }else if( useTempTable ){
82150        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
82151      }else{
82152        assert( pSelect==0 ); /* Otherwise useTempTable is true */
82153        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
82154      }
82155    }
82156
82157    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
82158    ** do not attempt any conversions before assembling the record.
82159    ** If this is a real table, attempt conversions as required by the
82160    ** table column affinities.
82161    */
82162    if( !isView ){
82163      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
82164      sqlite3TableAffinityStr(v, pTab);
82165    }
82166
82167    /* Fire BEFORE or INSTEAD OF triggers */
82168    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
82169        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
82170
82171    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
82172  }
82173
82174  /* Push the record number for the new entry onto the stack.  The
82175  ** record number is a randomly generate integer created by NewRowid
82176  ** except when the table has an INTEGER PRIMARY KEY column, in which
82177  ** case the record number is the same as that column.
82178  */
82179  if( !isView ){
82180    if( IsVirtual(pTab) ){
82181      /* The row that the VUpdate opcode will delete: none */
82182      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
82183    }
82184    if( keyColumn>=0 ){
82185      if( useTempTable ){
82186        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
82187      }else if( pSelect ){
82188        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
82189      }else{
82190        VdbeOp *pOp;
82191        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
82192        pOp = sqlite3VdbeGetOp(v, -1);
82193        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
82194          appendFlag = 1;
82195          pOp->opcode = OP_NewRowid;
82196          pOp->p1 = baseCur;
82197          pOp->p2 = regRowid;
82198          pOp->p3 = regAutoinc;
82199        }
82200      }
82201      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
82202      ** to generate a unique primary key value.
82203      */
82204      if( !appendFlag ){
82205        int j1;
82206        if( !IsVirtual(pTab) ){
82207          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
82208          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
82209          sqlite3VdbeJumpHere(v, j1);
82210        }else{
82211          j1 = sqlite3VdbeCurrentAddr(v);
82212          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
82213        }
82214        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
82215      }
82216    }else if( IsVirtual(pTab) ){
82217      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
82218    }else{
82219      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
82220      appendFlag = 1;
82221    }
82222    autoIncStep(pParse, regAutoinc, regRowid);
82223
82224    /* Push onto the stack, data for all columns of the new entry, beginning
82225    ** with the first column.
82226    */
82227    nHidden = 0;
82228    for(i=0; i<pTab->nCol; i++){
82229      int iRegStore = regRowid+1+i;
82230      if( i==pTab->iPKey ){
82231        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
82232        ** Whenever this column is read, the record number will be substituted
82233        ** in its place.  So will fill this column with a NULL to avoid
82234        ** taking up data space with information that will never be used. */
82235        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
82236        continue;
82237      }
82238      if( pColumn==0 ){
82239        if( IsHiddenColumn(&pTab->aCol[i]) ){
82240          assert( IsVirtual(pTab) );
82241          j = -1;
82242          nHidden++;
82243        }else{
82244          j = i - nHidden;
82245        }
82246      }else{
82247        for(j=0; j<pColumn->nId; j++){
82248          if( pColumn->a[j].idx==i ) break;
82249        }
82250      }
82251      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
82252        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
82253      }else if( useTempTable ){
82254        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
82255      }else if( pSelect ){
82256        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
82257      }else{
82258        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
82259      }
82260    }
82261
82262    /* Generate code to check constraints and generate index keys and
82263    ** do the insertion.
82264    */
82265#ifndef SQLITE_OMIT_VIRTUALTABLE
82266    if( IsVirtual(pTab) ){
82267      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
82268      sqlite3VtabMakeWritable(pParse, pTab);
82269      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
82270      sqlite3MayAbort(pParse);
82271    }else
82272#endif
82273    {
82274      int isReplace;    /* Set to true if constraints may cause a replace */
82275      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
82276          keyColumn>=0, 0, onError, endOfLoop, &isReplace
82277      );
82278      sqlite3FkCheck(pParse, pTab, 0, regIns);
82279      sqlite3CompleteInsertion(
82280          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
82281      );
82282    }
82283  }
82284
82285  /* Update the count of rows that are inserted
82286  */
82287  if( (db->flags & SQLITE_CountRows)!=0 ){
82288    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
82289  }
82290
82291  if( pTrigger ){
82292    /* Code AFTER triggers */
82293    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
82294        pTab, regData-2-pTab->nCol, onError, endOfLoop);
82295  }
82296
82297  /* The bottom of the main insertion loop, if the data source
82298  ** is a SELECT statement.
82299  */
82300  sqlite3VdbeResolveLabel(v, endOfLoop);
82301  if( useTempTable ){
82302    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
82303    sqlite3VdbeJumpHere(v, addrInsTop);
82304    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
82305  }else if( pSelect ){
82306    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
82307    sqlite3VdbeJumpHere(v, addrInsTop);
82308  }
82309
82310  if( !IsVirtual(pTab) && !isView ){
82311    /* Close all tables opened */
82312    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
82313    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
82314      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
82315    }
82316  }
82317
82318insert_end:
82319  /* Update the sqlite_sequence table by storing the content of the
82320  ** maximum rowid counter values recorded while inserting into
82321  ** autoincrement tables.
82322  */
82323  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
82324    sqlite3AutoincrementEnd(pParse);
82325  }
82326
82327  /*
82328  ** Return the number of rows inserted. If this routine is
82329  ** generating code because of a call to sqlite3NestedParse(), do not
82330  ** invoke the callback function.
82331  */
82332  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
82333    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
82334    sqlite3VdbeSetNumCols(v, 1);
82335    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
82336  }
82337
82338insert_cleanup:
82339  sqlite3SrcListDelete(db, pTabList);
82340  sqlite3ExprListDelete(db, pList);
82341  sqlite3SelectDelete(db, pSelect);
82342  sqlite3IdListDelete(db, pColumn);
82343  sqlite3DbFree(db, aRegIdx);
82344}
82345
82346/* Make sure "isView" and other macros defined above are undefined. Otherwise
82347** thely may interfere with compilation of other functions in this file
82348** (or in another file, if this file becomes part of the amalgamation).  */
82349#ifdef isView
82350 #undef isView
82351#endif
82352#ifdef pTrigger
82353 #undef pTrigger
82354#endif
82355#ifdef tmask
82356 #undef tmask
82357#endif
82358
82359
82360/*
82361** Generate code to do constraint checks prior to an INSERT or an UPDATE.
82362**
82363** The input is a range of consecutive registers as follows:
82364**
82365**    1.  The rowid of the row after the update.
82366**
82367**    2.  The data in the first column of the entry after the update.
82368**
82369**    i.  Data from middle columns...
82370**
82371**    N.  The data in the last column of the entry after the update.
82372**
82373** The regRowid parameter is the index of the register containing (1).
82374**
82375** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
82376** the address of a register containing the rowid before the update takes
82377** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
82378** is false, indicating an INSERT statement, then a non-zero rowidChng
82379** indicates that the rowid was explicitly specified as part of the
82380** INSERT statement. If rowidChng is false, it means that  the rowid is
82381** computed automatically in an insert or that the rowid value is not
82382** modified by an update.
82383**
82384** The code generated by this routine store new index entries into
82385** registers identified by aRegIdx[].  No index entry is created for
82386** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
82387** the same as the order of indices on the linked list of indices
82388** attached to the table.
82389**
82390** This routine also generates code to check constraints.  NOT NULL,
82391** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
82392** then the appropriate action is performed.  There are five possible
82393** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
82394**
82395**  Constraint type  Action       What Happens
82396**  ---------------  ----------   ----------------------------------------
82397**  any              ROLLBACK     The current transaction is rolled back and
82398**                                sqlite3_exec() returns immediately with a
82399**                                return code of SQLITE_CONSTRAINT.
82400**
82401**  any              ABORT        Back out changes from the current command
82402**                                only (do not do a complete rollback) then
82403**                                cause sqlite3_exec() to return immediately
82404**                                with SQLITE_CONSTRAINT.
82405**
82406**  any              FAIL         Sqlite_exec() returns immediately with a
82407**                                return code of SQLITE_CONSTRAINT.  The
82408**                                transaction is not rolled back and any
82409**                                prior changes are retained.
82410**
82411**  any              IGNORE       The record number and data is popped from
82412**                                the stack and there is an immediate jump
82413**                                to label ignoreDest.
82414**
82415**  NOT NULL         REPLACE      The NULL value is replace by the default
82416**                                value for that column.  If the default value
82417**                                is NULL, the action is the same as ABORT.
82418**
82419**  UNIQUE           REPLACE      The other row that conflicts with the row
82420**                                being inserted is removed.
82421**
82422**  CHECK            REPLACE      Illegal.  The results in an exception.
82423**
82424** Which action to take is determined by the overrideError parameter.
82425** Or if overrideError==OE_Default, then the pParse->onError parameter
82426** is used.  Or if pParse->onError==OE_Default then the onError value
82427** for the constraint is used.
82428**
82429** The calling routine must open a read/write cursor for pTab with
82430** cursor number "baseCur".  All indices of pTab must also have open
82431** read/write cursors with cursor number baseCur+i for the i-th cursor.
82432** Except, if there is no possibility of a REPLACE action then
82433** cursors do not need to be open for indices where aRegIdx[i]==0.
82434*/
82435SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
82436  Parse *pParse,      /* The parser context */
82437  Table *pTab,        /* the table into which we are inserting */
82438  int baseCur,        /* Index of a read/write cursor pointing at pTab */
82439  int regRowid,       /* Index of the range of input registers */
82440  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
82441  int rowidChng,      /* True if the rowid might collide with existing entry */
82442  int isUpdate,       /* True for UPDATE, False for INSERT */
82443  int overrideError,  /* Override onError to this if not OE_Default */
82444  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
82445  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
82446){
82447  int i;              /* loop counter */
82448  Vdbe *v;            /* VDBE under constrution */
82449  int nCol;           /* Number of columns */
82450  int onError;        /* Conflict resolution strategy */
82451  int j1;             /* Addresss of jump instruction */
82452  int j2 = 0, j3;     /* Addresses of jump instructions */
82453  int regData;        /* Register containing first data column */
82454  int iCur;           /* Table cursor number */
82455  Index *pIdx;         /* Pointer to one of the indices */
82456  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
82457  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
82458
82459  v = sqlite3GetVdbe(pParse);
82460  assert( v!=0 );
82461  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
82462  nCol = pTab->nCol;
82463  regData = regRowid + 1;
82464
82465  /* Test all NOT NULL constraints.
82466  */
82467  for(i=0; i<nCol; i++){
82468    if( i==pTab->iPKey ){
82469      continue;
82470    }
82471    onError = pTab->aCol[i].notNull;
82472    if( onError==OE_None ) continue;
82473    if( overrideError!=OE_Default ){
82474      onError = overrideError;
82475    }else if( onError==OE_Default ){
82476      onError = OE_Abort;
82477    }
82478    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
82479      onError = OE_Abort;
82480    }
82481    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
82482        || onError==OE_Ignore || onError==OE_Replace );
82483    switch( onError ){
82484      case OE_Abort:
82485        sqlite3MayAbort(pParse);
82486      case OE_Rollback:
82487      case OE_Fail: {
82488        char *zMsg;
82489        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
82490                                  SQLITE_CONSTRAINT, onError, regData+i);
82491        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
82492                              pTab->zName, pTab->aCol[i].zName);
82493        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
82494        break;
82495      }
82496      case OE_Ignore: {
82497        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
82498        break;
82499      }
82500      default: {
82501        assert( onError==OE_Replace );
82502        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
82503        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
82504        sqlite3VdbeJumpHere(v, j1);
82505        break;
82506      }
82507    }
82508  }
82509
82510  /* Test all CHECK constraints
82511  */
82512#ifndef SQLITE_OMIT_CHECK
82513  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
82514    int allOk = sqlite3VdbeMakeLabel(v);
82515    pParse->ckBase = regData;
82516    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
82517    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
82518    if( onError==OE_Ignore ){
82519      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
82520    }else{
82521      if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
82522      sqlite3HaltConstraint(pParse, onError, 0, 0);
82523    }
82524    sqlite3VdbeResolveLabel(v, allOk);
82525  }
82526#endif /* !defined(SQLITE_OMIT_CHECK) */
82527
82528  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
82529  ** of the new record does not previously exist.  Except, if this
82530  ** is an UPDATE and the primary key is not changing, that is OK.
82531  */
82532  if( rowidChng ){
82533    onError = pTab->keyConf;
82534    if( overrideError!=OE_Default ){
82535      onError = overrideError;
82536    }else if( onError==OE_Default ){
82537      onError = OE_Abort;
82538    }
82539
82540    if( isUpdate ){
82541      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
82542    }
82543    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
82544    switch( onError ){
82545      default: {
82546        onError = OE_Abort;
82547        /* Fall thru into the next case */
82548      }
82549      case OE_Rollback:
82550      case OE_Abort:
82551      case OE_Fail: {
82552        sqlite3HaltConstraint(
82553          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
82554        break;
82555      }
82556      case OE_Replace: {
82557        /* If there are DELETE triggers on this table and the
82558        ** recursive-triggers flag is set, call GenerateRowDelete() to
82559        ** remove the conflicting row from the the table. This will fire
82560        ** the triggers and remove both the table and index b-tree entries.
82561        **
82562        ** Otherwise, if there are no triggers or the recursive-triggers
82563        ** flag is not set, but the table has one or more indexes, call
82564        ** GenerateRowIndexDelete(). This removes the index b-tree entries
82565        ** only. The table b-tree entry will be replaced by the new entry
82566        ** when it is inserted.
82567        **
82568        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
82569        ** also invoke MultiWrite() to indicate that this VDBE may require
82570        ** statement rollback (if the statement is aborted after the delete
82571        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
82572        ** but being more selective here allows statements like:
82573        **
82574        **   REPLACE INTO t(rowid) VALUES($newrowid)
82575        **
82576        ** to run without a statement journal if there are no indexes on the
82577        ** table.
82578        */
82579        Trigger *pTrigger = 0;
82580        if( pParse->db->flags&SQLITE_RecTriggers ){
82581          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
82582        }
82583        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
82584          sqlite3MultiWrite(pParse);
82585          sqlite3GenerateRowDelete(
82586              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
82587          );
82588        }else if( pTab->pIndex ){
82589          sqlite3MultiWrite(pParse);
82590          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
82591        }
82592        seenReplace = 1;
82593        break;
82594      }
82595      case OE_Ignore: {
82596        assert( seenReplace==0 );
82597        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
82598        break;
82599      }
82600    }
82601    sqlite3VdbeJumpHere(v, j3);
82602    if( isUpdate ){
82603      sqlite3VdbeJumpHere(v, j2);
82604    }
82605  }
82606
82607  /* Test all UNIQUE constraints by creating entries for each UNIQUE
82608  ** index and making sure that duplicate entries do not already exist.
82609  ** Add the new records to the indices as we go.
82610  */
82611  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
82612    int regIdx;
82613    int regR;
82614
82615    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
82616
82617    /* Create a key for accessing the index entry */
82618    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
82619    for(i=0; i<pIdx->nColumn; i++){
82620      int idx = pIdx->aiColumn[i];
82621      if( idx==pTab->iPKey ){
82622        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
82623      }else{
82624        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
82625      }
82626    }
82627    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
82628    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
82629    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
82630    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
82631
82632    /* Find out what action to take in case there is an indexing conflict */
82633    onError = pIdx->onError;
82634    if( onError==OE_None ){
82635      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
82636      continue;  /* pIdx is not a UNIQUE index */
82637    }
82638    if( overrideError!=OE_Default ){
82639      onError = overrideError;
82640    }else if( onError==OE_Default ){
82641      onError = OE_Abort;
82642    }
82643    if( seenReplace ){
82644      if( onError==OE_Ignore ) onError = OE_Replace;
82645      else if( onError==OE_Fail ) onError = OE_Abort;
82646    }
82647
82648    /* Check to see if the new index entry will be unique */
82649    regR = sqlite3GetTempReg(pParse);
82650    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
82651    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
82652                           regR, SQLITE_INT_TO_PTR(regIdx),
82653                           P4_INT32);
82654    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
82655
82656    /* Generate code that executes if the new index entry is not unique */
82657    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
82658        || onError==OE_Ignore || onError==OE_Replace );
82659    switch( onError ){
82660      case OE_Rollback:
82661      case OE_Abort:
82662      case OE_Fail: {
82663        int j;
82664        StrAccum errMsg;
82665        const char *zSep;
82666        char *zErr;
82667
82668        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
82669        errMsg.db = pParse->db;
82670        zSep = pIdx->nColumn>1 ? "columns " : "column ";
82671        for(j=0; j<pIdx->nColumn; j++){
82672          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
82673          sqlite3StrAccumAppend(&errMsg, zSep, -1);
82674          zSep = ", ";
82675          sqlite3StrAccumAppend(&errMsg, zCol, -1);
82676        }
82677        sqlite3StrAccumAppend(&errMsg,
82678            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
82679        zErr = sqlite3StrAccumFinish(&errMsg);
82680        sqlite3HaltConstraint(pParse, onError, zErr, 0);
82681        sqlite3DbFree(errMsg.db, zErr);
82682        break;
82683      }
82684      case OE_Ignore: {
82685        assert( seenReplace==0 );
82686        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
82687        break;
82688      }
82689      default: {
82690        Trigger *pTrigger = 0;
82691        assert( onError==OE_Replace );
82692        sqlite3MultiWrite(pParse);
82693        if( pParse->db->flags&SQLITE_RecTriggers ){
82694          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
82695        }
82696        sqlite3GenerateRowDelete(
82697            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
82698        );
82699        seenReplace = 1;
82700        break;
82701      }
82702    }
82703    sqlite3VdbeJumpHere(v, j3);
82704    sqlite3ReleaseTempReg(pParse, regR);
82705  }
82706
82707  if( pbMayReplace ){
82708    *pbMayReplace = seenReplace;
82709  }
82710}
82711
82712/*
82713** This routine generates code to finish the INSERT or UPDATE operation
82714** that was started by a prior call to sqlite3GenerateConstraintChecks.
82715** A consecutive range of registers starting at regRowid contains the
82716** rowid and the content to be inserted.
82717**
82718** The arguments to this routine should be the same as the first six
82719** arguments to sqlite3GenerateConstraintChecks.
82720*/
82721SQLITE_PRIVATE void sqlite3CompleteInsertion(
82722  Parse *pParse,      /* The parser context */
82723  Table *pTab,        /* the table into which we are inserting */
82724  int baseCur,        /* Index of a read/write cursor pointing at pTab */
82725  int regRowid,       /* Range of content */
82726  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
82727  int isUpdate,       /* True for UPDATE, False for INSERT */
82728  int appendBias,     /* True if this is likely to be an append */
82729  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
82730){
82731  int i;
82732  Vdbe *v;
82733  int nIdx;
82734  Index *pIdx;
82735  u8 pik_flags;
82736  int regData;
82737  int regRec;
82738
82739  v = sqlite3GetVdbe(pParse);
82740  assert( v!=0 );
82741  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
82742  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
82743  for(i=nIdx-1; i>=0; i--){
82744    if( aRegIdx[i]==0 ) continue;
82745    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
82746    if( useSeekResult ){
82747      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
82748    }
82749  }
82750  regData = regRowid + 1;
82751  regRec = sqlite3GetTempReg(pParse);
82752  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
82753  sqlite3TableAffinityStr(v, pTab);
82754  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
82755  if( pParse->nested ){
82756    pik_flags = 0;
82757  }else{
82758    pik_flags = OPFLAG_NCHANGE;
82759    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
82760  }
82761  if( appendBias ){
82762    pik_flags |= OPFLAG_APPEND;
82763  }
82764  if( useSeekResult ){
82765    pik_flags |= OPFLAG_USESEEKRESULT;
82766  }
82767  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
82768  if( !pParse->nested ){
82769    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
82770  }
82771  sqlite3VdbeChangeP5(v, pik_flags);
82772}
82773
82774/*
82775** Generate code that will open cursors for a table and for all
82776** indices of that table.  The "baseCur" parameter is the cursor number used
82777** for the table.  Indices are opened on subsequent cursors.
82778**
82779** Return the number of indices on the table.
82780*/
82781SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
82782  Parse *pParse,   /* Parsing context */
82783  Table *pTab,     /* Table to be opened */
82784  int baseCur,     /* Cursor number assigned to the table */
82785  int op           /* OP_OpenRead or OP_OpenWrite */
82786){
82787  int i;
82788  int iDb;
82789  Index *pIdx;
82790  Vdbe *v;
82791
82792  if( IsVirtual(pTab) ) return 0;
82793  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82794  v = sqlite3GetVdbe(pParse);
82795  assert( v!=0 );
82796  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
82797  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
82798    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
82799    assert( pIdx->pSchema==pTab->pSchema );
82800    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
82801                      (char*)pKey, P4_KEYINFO_HANDOFF);
82802    VdbeComment((v, "%s", pIdx->zName));
82803  }
82804  if( pParse->nTab<baseCur+i ){
82805    pParse->nTab = baseCur+i;
82806  }
82807  return i-1;
82808}
82809
82810
82811#ifdef SQLITE_TEST
82812/*
82813** The following global variable is incremented whenever the
82814** transfer optimization is used.  This is used for testing
82815** purposes only - to make sure the transfer optimization really
82816** is happening when it is suppose to.
82817*/
82818SQLITE_API int sqlite3_xferopt_count;
82819#endif /* SQLITE_TEST */
82820
82821
82822#ifndef SQLITE_OMIT_XFER_OPT
82823/*
82824** Check to collation names to see if they are compatible.
82825*/
82826static int xferCompatibleCollation(const char *z1, const char *z2){
82827  if( z1==0 ){
82828    return z2==0;
82829  }
82830  if( z2==0 ){
82831    return 0;
82832  }
82833  return sqlite3StrICmp(z1, z2)==0;
82834}
82835
82836
82837/*
82838** Check to see if index pSrc is compatible as a source of data
82839** for index pDest in an insert transfer optimization.  The rules
82840** for a compatible index:
82841**
82842**    *   The index is over the same set of columns
82843**    *   The same DESC and ASC markings occurs on all columns
82844**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
82845**    *   The same collating sequence on each column
82846*/
82847static int xferCompatibleIndex(Index *pDest, Index *pSrc){
82848  int i;
82849  assert( pDest && pSrc );
82850  assert( pDest->pTable!=pSrc->pTable );
82851  if( pDest->nColumn!=pSrc->nColumn ){
82852    return 0;   /* Different number of columns */
82853  }
82854  if( pDest->onError!=pSrc->onError ){
82855    return 0;   /* Different conflict resolution strategies */
82856  }
82857  for(i=0; i<pSrc->nColumn; i++){
82858    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
82859      return 0;   /* Different columns indexed */
82860    }
82861    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
82862      return 0;   /* Different sort orders */
82863    }
82864    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
82865      return 0;   /* Different collating sequences */
82866    }
82867  }
82868
82869  /* If no test above fails then the indices must be compatible */
82870  return 1;
82871}
82872
82873/*
82874** Attempt the transfer optimization on INSERTs of the form
82875**
82876**     INSERT INTO tab1 SELECT * FROM tab2;
82877**
82878** This optimization is only attempted if
82879**
82880**    (1)  tab1 and tab2 have identical schemas including all the
82881**         same indices and constraints
82882**
82883**    (2)  tab1 and tab2 are different tables
82884**
82885**    (3)  There must be no triggers on tab1
82886**
82887**    (4)  The result set of the SELECT statement is "*"
82888**
82889**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
82890**         or LIMIT clause.
82891**
82892**    (6)  The SELECT statement is a simple (not a compound) select that
82893**         contains only tab2 in its FROM clause
82894**
82895** This method for implementing the INSERT transfers raw records from
82896** tab2 over to tab1.  The columns are not decoded.  Raw records from
82897** the indices of tab2 are transfered to tab1 as well.  In so doing,
82898** the resulting tab1 has much less fragmentation.
82899**
82900** This routine returns TRUE if the optimization is attempted.  If any
82901** of the conditions above fail so that the optimization should not
82902** be attempted, then this routine returns FALSE.
82903*/
82904static int xferOptimization(
82905  Parse *pParse,        /* Parser context */
82906  Table *pDest,         /* The table we are inserting into */
82907  Select *pSelect,      /* A SELECT statement to use as the data source */
82908  int onError,          /* How to handle constraint errors */
82909  int iDbDest           /* The database of pDest */
82910){
82911  ExprList *pEList;                /* The result set of the SELECT */
82912  Table *pSrc;                     /* The table in the FROM clause of SELECT */
82913  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
82914  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
82915  int i;                           /* Loop counter */
82916  int iDbSrc;                      /* The database of pSrc */
82917  int iSrc, iDest;                 /* Cursors from source and destination */
82918  int addr1, addr2;                /* Loop addresses */
82919  int emptyDestTest;               /* Address of test for empty pDest */
82920  int emptySrcTest;                /* Address of test for empty pSrc */
82921  Vdbe *v;                         /* The VDBE we are building */
82922  KeyInfo *pKey;                   /* Key information for an index */
82923  int regAutoinc;                  /* Memory register used by AUTOINC */
82924  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
82925  int regData, regRowid;           /* Registers holding data and rowid */
82926
82927  if( pSelect==0 ){
82928    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
82929  }
82930  if( sqlite3TriggerList(pParse, pDest) ){
82931    return 0;   /* tab1 must not have triggers */
82932  }
82933#ifndef SQLITE_OMIT_VIRTUALTABLE
82934  if( pDest->tabFlags & TF_Virtual ){
82935    return 0;   /* tab1 must not be a virtual table */
82936  }
82937#endif
82938  if( onError==OE_Default ){
82939    onError = OE_Abort;
82940  }
82941  if( onError!=OE_Abort && onError!=OE_Rollback ){
82942    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
82943  }
82944  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
82945  if( pSelect->pSrc->nSrc!=1 ){
82946    return 0;   /* FROM clause must have exactly one term */
82947  }
82948  if( pSelect->pSrc->a[0].pSelect ){
82949    return 0;   /* FROM clause cannot contain a subquery */
82950  }
82951  if( pSelect->pWhere ){
82952    return 0;   /* SELECT may not have a WHERE clause */
82953  }
82954  if( pSelect->pOrderBy ){
82955    return 0;   /* SELECT may not have an ORDER BY clause */
82956  }
82957  /* Do not need to test for a HAVING clause.  If HAVING is present but
82958  ** there is no ORDER BY, we will get an error. */
82959  if( pSelect->pGroupBy ){
82960    return 0;   /* SELECT may not have a GROUP BY clause */
82961  }
82962  if( pSelect->pLimit ){
82963    return 0;   /* SELECT may not have a LIMIT clause */
82964  }
82965  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
82966  if( pSelect->pPrior ){
82967    return 0;   /* SELECT may not be a compound query */
82968  }
82969  if( pSelect->selFlags & SF_Distinct ){
82970    return 0;   /* SELECT may not be DISTINCT */
82971  }
82972  pEList = pSelect->pEList;
82973  assert( pEList!=0 );
82974  if( pEList->nExpr!=1 ){
82975    return 0;   /* The result set must have exactly one column */
82976  }
82977  assert( pEList->a[0].pExpr );
82978  if( pEList->a[0].pExpr->op!=TK_ALL ){
82979    return 0;   /* The result set must be the special operator "*" */
82980  }
82981
82982  /* At this point we have established that the statement is of the
82983  ** correct syntactic form to participate in this optimization.  Now
82984  ** we have to check the semantics.
82985  */
82986  pItem = pSelect->pSrc->a;
82987  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
82988  if( pSrc==0 ){
82989    return 0;   /* FROM clause does not contain a real table */
82990  }
82991  if( pSrc==pDest ){
82992    return 0;   /* tab1 and tab2 may not be the same table */
82993  }
82994#ifndef SQLITE_OMIT_VIRTUALTABLE
82995  if( pSrc->tabFlags & TF_Virtual ){
82996    return 0;   /* tab2 must not be a virtual table */
82997  }
82998#endif
82999  if( pSrc->pSelect ){
83000    return 0;   /* tab2 may not be a view */
83001  }
83002  if( pDest->nCol!=pSrc->nCol ){
83003    return 0;   /* Number of columns must be the same in tab1 and tab2 */
83004  }
83005  if( pDest->iPKey!=pSrc->iPKey ){
83006    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
83007  }
83008  for(i=0; i<pDest->nCol; i++){
83009    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
83010      return 0;    /* Affinity must be the same on all columns */
83011    }
83012    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
83013      return 0;    /* Collating sequence must be the same on all columns */
83014    }
83015    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
83016      return 0;    /* tab2 must be NOT NULL if tab1 is */
83017    }
83018  }
83019  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
83020    if( pDestIdx->onError!=OE_None ){
83021      destHasUniqueIdx = 1;
83022    }
83023    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
83024      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
83025    }
83026    if( pSrcIdx==0 ){
83027      return 0;    /* pDestIdx has no corresponding index in pSrc */
83028    }
83029  }
83030#ifndef SQLITE_OMIT_CHECK
83031  if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
83032    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
83033  }
83034#endif
83035
83036  /* If we get this far, it means either:
83037  **
83038  **    *   We can always do the transfer if the table contains an
83039  **        an integer primary key
83040  **
83041  **    *   We can conditionally do the transfer if the destination
83042  **        table is empty.
83043  */
83044#ifdef SQLITE_TEST
83045  sqlite3_xferopt_count++;
83046#endif
83047  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
83048  v = sqlite3GetVdbe(pParse);
83049  sqlite3CodeVerifySchema(pParse, iDbSrc);
83050  iSrc = pParse->nTab++;
83051  iDest = pParse->nTab++;
83052  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
83053  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
83054  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
83055    /* If tables do not have an INTEGER PRIMARY KEY and there
83056    ** are indices to be copied and the destination is not empty,
83057    ** we have to disallow the transfer optimization because the
83058    ** the rowids might change which will mess up indexing.
83059    **
83060    ** Or if the destination has a UNIQUE index and is not empty,
83061    ** we also disallow the transfer optimization because we cannot
83062    ** insure that all entries in the union of DEST and SRC will be
83063    ** unique.
83064    */
83065    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
83066    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
83067    sqlite3VdbeJumpHere(v, addr1);
83068  }else{
83069    emptyDestTest = 0;
83070  }
83071  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
83072  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
83073  regData = sqlite3GetTempReg(pParse);
83074  regRowid = sqlite3GetTempReg(pParse);
83075  if( pDest->iPKey>=0 ){
83076    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
83077    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
83078    sqlite3HaltConstraint(
83079        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
83080    sqlite3VdbeJumpHere(v, addr2);
83081    autoIncStep(pParse, regAutoinc, regRowid);
83082  }else if( pDest->pIndex==0 ){
83083    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
83084  }else{
83085    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
83086    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
83087  }
83088  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
83089  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
83090  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
83091  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
83092  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
83093  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
83094    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
83095      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
83096    }
83097    assert( pSrcIdx );
83098    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
83099    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
83100    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
83101    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
83102                      (char*)pKey, P4_KEYINFO_HANDOFF);
83103    VdbeComment((v, "%s", pSrcIdx->zName));
83104    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
83105    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
83106                      (char*)pKey, P4_KEYINFO_HANDOFF);
83107    VdbeComment((v, "%s", pDestIdx->zName));
83108    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
83109    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
83110    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
83111    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
83112    sqlite3VdbeJumpHere(v, addr1);
83113  }
83114  sqlite3VdbeJumpHere(v, emptySrcTest);
83115  sqlite3ReleaseTempReg(pParse, regRowid);
83116  sqlite3ReleaseTempReg(pParse, regData);
83117  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
83118  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
83119  if( emptyDestTest ){
83120    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
83121    sqlite3VdbeJumpHere(v, emptyDestTest);
83122    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
83123    return 0;
83124  }else{
83125    return 1;
83126  }
83127}
83128#endif /* SQLITE_OMIT_XFER_OPT */
83129
83130/************** End of insert.c **********************************************/
83131/************** Begin file legacy.c ******************************************/
83132/*
83133** 2001 September 15
83134**
83135** The author disclaims copyright to this source code.  In place of
83136** a legal notice, here is a blessing:
83137**
83138**    May you do good and not evil.
83139**    May you find forgiveness for yourself and forgive others.
83140**    May you share freely, never taking more than you give.
83141**
83142*************************************************************************
83143** Main file for the SQLite library.  The routines in this file
83144** implement the programmer interface to the library.  Routines in
83145** other files are for internal use by SQLite and should not be
83146** accessed by users of the library.
83147*/
83148
83149
83150/*
83151** Execute SQL code.  Return one of the SQLITE_ success/failure
83152** codes.  Also write an error message into memory obtained from
83153** malloc() and make *pzErrMsg point to that message.
83154**
83155** If the SQL is a query, then for each row in the query result
83156** the xCallback() function is called.  pArg becomes the first
83157** argument to xCallback().  If xCallback=NULL then no callback
83158** is invoked, even for queries.
83159*/
83160SQLITE_API int sqlite3_exec(
83161  sqlite3 *db,                /* The database on which the SQL executes */
83162  const char *zSql,           /* The SQL to be executed */
83163  sqlite3_callback xCallback, /* Invoke this callback routine */
83164  void *pArg,                 /* First argument to xCallback() */
83165  char **pzErrMsg             /* Write error messages here */
83166){
83167  int rc = SQLITE_OK;         /* Return code */
83168  const char *zLeftover;      /* Tail of unprocessed SQL */
83169  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
83170  char **azCols = 0;          /* Names of result columns */
83171  int nRetry = 0;             /* Number of retry attempts */
83172  int callbackIsInit;         /* True if callback data is initialized */
83173
83174  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
83175  if( zSql==0 ) zSql = "";
83176
83177  sqlite3_mutex_enter(db->mutex);
83178  sqlite3Error(db, SQLITE_OK, 0);
83179  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
83180    int nCol;
83181    char **azVals = 0;
83182
83183    pStmt = 0;
83184    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
83185    assert( rc==SQLITE_OK || pStmt==0 );
83186    if( rc!=SQLITE_OK ){
83187      continue;
83188    }
83189    if( !pStmt ){
83190      /* this happens for a comment or white-space */
83191      zSql = zLeftover;
83192      continue;
83193    }
83194
83195    callbackIsInit = 0;
83196    nCol = sqlite3_column_count(pStmt);
83197
83198    while( 1 ){
83199      int i;
83200      rc = sqlite3_step(pStmt);
83201
83202      /* Invoke the callback function if required */
83203      if( xCallback && (SQLITE_ROW==rc ||
83204          (SQLITE_DONE==rc && !callbackIsInit
83205                           && db->flags&SQLITE_NullCallback)) ){
83206        if( !callbackIsInit ){
83207          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
83208          if( azCols==0 ){
83209            goto exec_out;
83210          }
83211          for(i=0; i<nCol; i++){
83212            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
83213            /* sqlite3VdbeSetColName() installs column names as UTF8
83214            ** strings so there is no way for sqlite3_column_name() to fail. */
83215            assert( azCols[i]!=0 );
83216          }
83217          callbackIsInit = 1;
83218        }
83219        if( rc==SQLITE_ROW ){
83220          azVals = &azCols[nCol];
83221          for(i=0; i<nCol; i++){
83222            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
83223            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
83224              db->mallocFailed = 1;
83225              goto exec_out;
83226            }
83227          }
83228        }
83229        if( xCallback(pArg, nCol, azVals, azCols) ){
83230          rc = SQLITE_ABORT;
83231          sqlite3VdbeFinalize((Vdbe *)pStmt);
83232          pStmt = 0;
83233          sqlite3Error(db, SQLITE_ABORT, 0);
83234          goto exec_out;
83235        }
83236      }
83237
83238      if( rc!=SQLITE_ROW ){
83239        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
83240        pStmt = 0;
83241        if( rc!=SQLITE_SCHEMA ){
83242          nRetry = 0;
83243          zSql = zLeftover;
83244          while( sqlite3Isspace(zSql[0]) ) zSql++;
83245        }
83246        break;
83247      }
83248    }
83249
83250    sqlite3DbFree(db, azCols);
83251    azCols = 0;
83252  }
83253
83254exec_out:
83255  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
83256  sqlite3DbFree(db, azCols);
83257
83258  rc = sqlite3ApiExit(db, rc);
83259  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
83260    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
83261    *pzErrMsg = sqlite3Malloc(nErrMsg);
83262    if( *pzErrMsg ){
83263      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
83264    }else{
83265      rc = SQLITE_NOMEM;
83266      sqlite3Error(db, SQLITE_NOMEM, 0);
83267    }
83268  }else if( pzErrMsg ){
83269    *pzErrMsg = 0;
83270  }
83271
83272  assert( (rc&db->errMask)==rc );
83273  sqlite3_mutex_leave(db->mutex);
83274  return rc;
83275}
83276
83277/************** End of legacy.c **********************************************/
83278/************** Begin file loadext.c *****************************************/
83279/*
83280** 2006 June 7
83281**
83282** The author disclaims copyright to this source code.  In place of
83283** a legal notice, here is a blessing:
83284**
83285**    May you do good and not evil.
83286**    May you find forgiveness for yourself and forgive others.
83287**    May you share freely, never taking more than you give.
83288**
83289*************************************************************************
83290** This file contains code used to dynamically load extensions into
83291** the SQLite library.
83292*/
83293
83294#ifndef SQLITE_CORE
83295  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
83296#endif
83297/************** Include sqlite3ext.h in the middle of loadext.c **************/
83298/************** Begin file sqlite3ext.h **************************************/
83299/*
83300** 2006 June 7
83301**
83302** The author disclaims copyright to this source code.  In place of
83303** a legal notice, here is a blessing:
83304**
83305**    May you do good and not evil.
83306**    May you find forgiveness for yourself and forgive others.
83307**    May you share freely, never taking more than you give.
83308**
83309*************************************************************************
83310** This header file defines the SQLite interface for use by
83311** shared libraries that want to be imported as extensions into
83312** an SQLite instance.  Shared libraries that intend to be loaded
83313** as extensions by SQLite should #include this file instead of
83314** sqlite3.h.
83315*/
83316#ifndef _SQLITE3EXT_H_
83317#define _SQLITE3EXT_H_
83318
83319typedef struct sqlite3_api_routines sqlite3_api_routines;
83320
83321/*
83322** The following structure holds pointers to all of the SQLite API
83323** routines.
83324**
83325** WARNING:  In order to maintain backwards compatibility, add new
83326** interfaces to the end of this structure only.  If you insert new
83327** interfaces in the middle of this structure, then older different
83328** versions of SQLite will not be able to load each others' shared
83329** libraries!
83330*/
83331struct sqlite3_api_routines {
83332  void * (*aggregate_context)(sqlite3_context*,int nBytes);
83333  int  (*aggregate_count)(sqlite3_context*);
83334  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
83335  int  (*bind_double)(sqlite3_stmt*,int,double);
83336  int  (*bind_int)(sqlite3_stmt*,int,int);
83337  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
83338  int  (*bind_null)(sqlite3_stmt*,int);
83339  int  (*bind_parameter_count)(sqlite3_stmt*);
83340  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
83341  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
83342  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
83343  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
83344  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
83345  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
83346  int  (*busy_timeout)(sqlite3*,int ms);
83347  int  (*changes)(sqlite3*);
83348  int  (*close)(sqlite3*);
83349  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
83350  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
83351  const void * (*column_blob)(sqlite3_stmt*,int iCol);
83352  int  (*column_bytes)(sqlite3_stmt*,int iCol);
83353  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
83354  int  (*column_count)(sqlite3_stmt*pStmt);
83355  const char * (*column_database_name)(sqlite3_stmt*,int);
83356  const void * (*column_database_name16)(sqlite3_stmt*,int);
83357  const char * (*column_decltype)(sqlite3_stmt*,int i);
83358  const void * (*column_decltype16)(sqlite3_stmt*,int);
83359  double  (*column_double)(sqlite3_stmt*,int iCol);
83360  int  (*column_int)(sqlite3_stmt*,int iCol);
83361  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
83362  const char * (*column_name)(sqlite3_stmt*,int);
83363  const void * (*column_name16)(sqlite3_stmt*,int);
83364  const char * (*column_origin_name)(sqlite3_stmt*,int);
83365  const void * (*column_origin_name16)(sqlite3_stmt*,int);
83366  const char * (*column_table_name)(sqlite3_stmt*,int);
83367  const void * (*column_table_name16)(sqlite3_stmt*,int);
83368  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
83369  const void * (*column_text16)(sqlite3_stmt*,int iCol);
83370  int  (*column_type)(sqlite3_stmt*,int iCol);
83371  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
83372  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
83373  int  (*complete)(const char*sql);
83374  int  (*complete16)(const void*sql);
83375  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
83376  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
83377  int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
83378  int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
83379  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
83380  int  (*data_count)(sqlite3_stmt*pStmt);
83381  sqlite3 * (*db_handle)(sqlite3_stmt*);
83382  int (*declare_vtab)(sqlite3*,const char*);
83383  int  (*enable_shared_cache)(int);
83384  int  (*errcode)(sqlite3*db);
83385  const char * (*errmsg)(sqlite3*);
83386  const void * (*errmsg16)(sqlite3*);
83387  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
83388  int  (*expired)(sqlite3_stmt*);
83389  int  (*finalize)(sqlite3_stmt*pStmt);
83390  void  (*free)(void*);
83391  void  (*free_table)(char**result);
83392  int  (*get_autocommit)(sqlite3*);
83393  void * (*get_auxdata)(sqlite3_context*,int);
83394  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
83395  int  (*global_recover)(void);
83396  void  (*interruptx)(sqlite3*);
83397  sqlite_int64  (*last_insert_rowid)(sqlite3*);
83398  const char * (*libversion)(void);
83399  int  (*libversion_number)(void);
83400  void *(*malloc)(int);
83401  char * (*mprintf)(const char*,...);
83402  int  (*open)(const char*,sqlite3**);
83403  int  (*open16)(const void*,sqlite3**);
83404  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
83405  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
83406  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
83407  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
83408  void *(*realloc)(void*,int);
83409  int  (*reset)(sqlite3_stmt*pStmt);
83410  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
83411  void  (*result_double)(sqlite3_context*,double);
83412  void  (*result_error)(sqlite3_context*,const char*,int);
83413  void  (*result_error16)(sqlite3_context*,const void*,int);
83414  void  (*result_int)(sqlite3_context*,int);
83415  void  (*result_int64)(sqlite3_context*,sqlite_int64);
83416  void  (*result_null)(sqlite3_context*);
83417  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
83418  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
83419  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
83420  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
83421  void  (*result_value)(sqlite3_context*,sqlite3_value*);
83422  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
83423  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
83424  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
83425  char * (*snprintf)(int,char*,const char*,...);
83426  int  (*step)(sqlite3_stmt*);
83427  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
83428  void  (*thread_cleanup)(void);
83429  int  (*total_changes)(sqlite3*);
83430  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
83431  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
83432  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
83433  void * (*user_data)(sqlite3_context*);
83434  const void * (*value_blob)(sqlite3_value*);
83435  int  (*value_bytes)(sqlite3_value*);
83436  int  (*value_bytes16)(sqlite3_value*);
83437  double  (*value_double)(sqlite3_value*);
83438  int  (*value_int)(sqlite3_value*);
83439  sqlite_int64  (*value_int64)(sqlite3_value*);
83440  int  (*value_numeric_type)(sqlite3_value*);
83441  const unsigned char * (*value_text)(sqlite3_value*);
83442  const void * (*value_text16)(sqlite3_value*);
83443  const void * (*value_text16be)(sqlite3_value*);
83444  const void * (*value_text16le)(sqlite3_value*);
83445  int  (*value_type)(sqlite3_value*);
83446  char *(*vmprintf)(const char*,va_list);
83447  /* Added ??? */
83448  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
83449  /* Added by 3.3.13 */
83450  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
83451  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
83452  int (*clear_bindings)(sqlite3_stmt*);
83453  /* Added by 3.4.1 */
83454  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
83455  /* Added by 3.5.0 */
83456  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
83457  int (*blob_bytes)(sqlite3_blob*);
83458  int (*blob_close)(sqlite3_blob*);
83459  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
83460  int (*blob_read)(sqlite3_blob*,void*,int,int);
83461  int (*blob_write)(sqlite3_blob*,const void*,int,int);
83462  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
83463  int (*file_control)(sqlite3*,const char*,int,void*);
83464  sqlite3_int64 (*memory_highwater)(int);
83465  sqlite3_int64 (*memory_used)(void);
83466  sqlite3_mutex *(*mutex_alloc)(int);
83467  void (*mutex_enter)(sqlite3_mutex*);
83468  void (*mutex_free)(sqlite3_mutex*);
83469  void (*mutex_leave)(sqlite3_mutex*);
83470  int (*mutex_try)(sqlite3_mutex*);
83471  int (*open_v2)(const char*,sqlite3**,int,const char*);
83472  int (*release_memory)(int);
83473  void (*result_error_nomem)(sqlite3_context*);
83474  void (*result_error_toobig)(sqlite3_context*);
83475  int (*sleep)(int);
83476  void (*soft_heap_limit)(int);
83477  sqlite3_vfs *(*vfs_find)(const char*);
83478  int (*vfs_register)(sqlite3_vfs*,int);
83479  int (*vfs_unregister)(sqlite3_vfs*);
83480  int (*xthreadsafe)(void);
83481  void (*result_zeroblob)(sqlite3_context*,int);
83482  void (*result_error_code)(sqlite3_context*,int);
83483  int (*test_control)(int, ...);
83484  void (*randomness)(int,void*);
83485  sqlite3 *(*context_db_handle)(sqlite3_context*);
83486  int (*extended_result_codes)(sqlite3*,int);
83487  int (*limit)(sqlite3*,int,int);
83488  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
83489  const char *(*sql)(sqlite3_stmt*);
83490  int (*status)(int,int*,int*,int);
83491};
83492
83493/*
83494** The following macros redefine the API routines so that they are
83495** redirected throught the global sqlite3_api structure.
83496**
83497** This header file is also used by the loadext.c source file
83498** (part of the main SQLite library - not an extension) so that
83499** it can get access to the sqlite3_api_routines structure
83500** definition.  But the main library does not want to redefine
83501** the API.  So the redefinition macros are only valid if the
83502** SQLITE_CORE macros is undefined.
83503*/
83504#ifndef SQLITE_CORE
83505#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
83506#ifndef SQLITE_OMIT_DEPRECATED
83507#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
83508#endif
83509#define sqlite3_bind_blob              sqlite3_api->bind_blob
83510#define sqlite3_bind_double            sqlite3_api->bind_double
83511#define sqlite3_bind_int               sqlite3_api->bind_int
83512#define sqlite3_bind_int64             sqlite3_api->bind_int64
83513#define sqlite3_bind_null              sqlite3_api->bind_null
83514#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
83515#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
83516#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
83517#define sqlite3_bind_text              sqlite3_api->bind_text
83518#define sqlite3_bind_text16            sqlite3_api->bind_text16
83519#define sqlite3_bind_value             sqlite3_api->bind_value
83520#define sqlite3_busy_handler           sqlite3_api->busy_handler
83521#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
83522#define sqlite3_changes                sqlite3_api->changes
83523#define sqlite3_close                  sqlite3_api->close
83524#define sqlite3_collation_needed       sqlite3_api->collation_needed
83525#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
83526#define sqlite3_column_blob            sqlite3_api->column_blob
83527#define sqlite3_column_bytes           sqlite3_api->column_bytes
83528#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
83529#define sqlite3_column_count           sqlite3_api->column_count
83530#define sqlite3_column_database_name   sqlite3_api->column_database_name
83531#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
83532#define sqlite3_column_decltype        sqlite3_api->column_decltype
83533#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
83534#define sqlite3_column_double          sqlite3_api->column_double
83535#define sqlite3_column_int             sqlite3_api->column_int
83536#define sqlite3_column_int64           sqlite3_api->column_int64
83537#define sqlite3_column_name            sqlite3_api->column_name
83538#define sqlite3_column_name16          sqlite3_api->column_name16
83539#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
83540#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
83541#define sqlite3_column_table_name      sqlite3_api->column_table_name
83542#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
83543#define sqlite3_column_text            sqlite3_api->column_text
83544#define sqlite3_column_text16          sqlite3_api->column_text16
83545#define sqlite3_column_type            sqlite3_api->column_type
83546#define sqlite3_column_value           sqlite3_api->column_value
83547#define sqlite3_commit_hook            sqlite3_api->commit_hook
83548#define sqlite3_complete               sqlite3_api->complete
83549#define sqlite3_complete16             sqlite3_api->complete16
83550#define sqlite3_create_collation       sqlite3_api->create_collation
83551#define sqlite3_create_collation16     sqlite3_api->create_collation16
83552#define sqlite3_create_function        sqlite3_api->create_function
83553#define sqlite3_create_function16      sqlite3_api->create_function16
83554#define sqlite3_create_module          sqlite3_api->create_module
83555#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
83556#define sqlite3_data_count             sqlite3_api->data_count
83557#define sqlite3_db_handle              sqlite3_api->db_handle
83558#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
83559#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
83560#define sqlite3_errcode                sqlite3_api->errcode
83561#define sqlite3_errmsg                 sqlite3_api->errmsg
83562#define sqlite3_errmsg16               sqlite3_api->errmsg16
83563#define sqlite3_exec                   sqlite3_api->exec
83564#ifndef SQLITE_OMIT_DEPRECATED
83565#define sqlite3_expired                sqlite3_api->expired
83566#endif
83567#define sqlite3_finalize               sqlite3_api->finalize
83568#define sqlite3_free                   sqlite3_api->free
83569#define sqlite3_free_table             sqlite3_api->free_table
83570#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
83571#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
83572#define sqlite3_get_table              sqlite3_api->get_table
83573#ifndef SQLITE_OMIT_DEPRECATED
83574#define sqlite3_global_recover         sqlite3_api->global_recover
83575#endif
83576#define sqlite3_interrupt              sqlite3_api->interruptx
83577#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
83578#define sqlite3_libversion             sqlite3_api->libversion
83579#define sqlite3_libversion_number      sqlite3_api->libversion_number
83580#define sqlite3_malloc                 sqlite3_api->malloc
83581#define sqlite3_mprintf                sqlite3_api->mprintf
83582#define sqlite3_open                   sqlite3_api->open
83583#define sqlite3_open16                 sqlite3_api->open16
83584#define sqlite3_prepare                sqlite3_api->prepare
83585#define sqlite3_prepare16              sqlite3_api->prepare16
83586#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
83587#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
83588#define sqlite3_profile                sqlite3_api->profile
83589#define sqlite3_progress_handler       sqlite3_api->progress_handler
83590#define sqlite3_realloc                sqlite3_api->realloc
83591#define sqlite3_reset                  sqlite3_api->reset
83592#define sqlite3_result_blob            sqlite3_api->result_blob
83593#define sqlite3_result_double          sqlite3_api->result_double
83594#define sqlite3_result_error           sqlite3_api->result_error
83595#define sqlite3_result_error16         sqlite3_api->result_error16
83596#define sqlite3_result_int             sqlite3_api->result_int
83597#define sqlite3_result_int64           sqlite3_api->result_int64
83598#define sqlite3_result_null            sqlite3_api->result_null
83599#define sqlite3_result_text            sqlite3_api->result_text
83600#define sqlite3_result_text16          sqlite3_api->result_text16
83601#define sqlite3_result_text16be        sqlite3_api->result_text16be
83602#define sqlite3_result_text16le        sqlite3_api->result_text16le
83603#define sqlite3_result_value           sqlite3_api->result_value
83604#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
83605#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
83606#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
83607#define sqlite3_snprintf               sqlite3_api->snprintf
83608#define sqlite3_step                   sqlite3_api->step
83609#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
83610#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
83611#define sqlite3_total_changes          sqlite3_api->total_changes
83612#define sqlite3_trace                  sqlite3_api->trace
83613#ifndef SQLITE_OMIT_DEPRECATED
83614#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
83615#endif
83616#define sqlite3_update_hook            sqlite3_api->update_hook
83617#define sqlite3_user_data              sqlite3_api->user_data
83618#define sqlite3_value_blob             sqlite3_api->value_blob
83619#define sqlite3_value_bytes            sqlite3_api->value_bytes
83620#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
83621#define sqlite3_value_double           sqlite3_api->value_double
83622#define sqlite3_value_int              sqlite3_api->value_int
83623#define sqlite3_value_int64            sqlite3_api->value_int64
83624#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
83625#define sqlite3_value_text             sqlite3_api->value_text
83626#define sqlite3_value_text16           sqlite3_api->value_text16
83627#define sqlite3_value_text16be         sqlite3_api->value_text16be
83628#define sqlite3_value_text16le         sqlite3_api->value_text16le
83629#define sqlite3_value_type             sqlite3_api->value_type
83630#define sqlite3_vmprintf               sqlite3_api->vmprintf
83631#define sqlite3_overload_function      sqlite3_api->overload_function
83632#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
83633#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
83634#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
83635#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
83636#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
83637#define sqlite3_blob_close             sqlite3_api->blob_close
83638#define sqlite3_blob_open              sqlite3_api->blob_open
83639#define sqlite3_blob_read              sqlite3_api->blob_read
83640#define sqlite3_blob_write             sqlite3_api->blob_write
83641#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
83642#define sqlite3_file_control           sqlite3_api->file_control
83643#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
83644#define sqlite3_memory_used            sqlite3_api->memory_used
83645#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
83646#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
83647#define sqlite3_mutex_free             sqlite3_api->mutex_free
83648#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
83649#define sqlite3_mutex_try              sqlite3_api->mutex_try
83650#define sqlite3_open_v2                sqlite3_api->open_v2
83651#define sqlite3_release_memory         sqlite3_api->release_memory
83652#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
83653#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
83654#define sqlite3_sleep                  sqlite3_api->sleep
83655#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
83656#define sqlite3_vfs_find               sqlite3_api->vfs_find
83657#define sqlite3_vfs_register           sqlite3_api->vfs_register
83658#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
83659#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
83660#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
83661#define sqlite3_result_error_code      sqlite3_api->result_error_code
83662#define sqlite3_test_control           sqlite3_api->test_control
83663#define sqlite3_randomness             sqlite3_api->randomness
83664#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
83665#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
83666#define sqlite3_limit                  sqlite3_api->limit
83667#define sqlite3_next_stmt              sqlite3_api->next_stmt
83668#define sqlite3_sql                    sqlite3_api->sql
83669#define sqlite3_status                 sqlite3_api->status
83670#endif /* SQLITE_CORE */
83671
83672#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
83673#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
83674
83675#endif /* _SQLITE3EXT_H_ */
83676
83677/************** End of sqlite3ext.h ******************************************/
83678/************** Continuing where we left off in loadext.c ********************/
83679
83680#ifndef SQLITE_OMIT_LOAD_EXTENSION
83681
83682/*
83683** Some API routines are omitted when various features are
83684** excluded from a build of SQLite.  Substitute a NULL pointer
83685** for any missing APIs.
83686*/
83687#ifndef SQLITE_ENABLE_COLUMN_METADATA
83688# define sqlite3_column_database_name   0
83689# define sqlite3_column_database_name16 0
83690# define sqlite3_column_table_name      0
83691# define sqlite3_column_table_name16    0
83692# define sqlite3_column_origin_name     0
83693# define sqlite3_column_origin_name16   0
83694# define sqlite3_table_column_metadata  0
83695#endif
83696
83697#ifdef SQLITE_OMIT_AUTHORIZATION
83698# define sqlite3_set_authorizer         0
83699#endif
83700
83701#ifdef SQLITE_OMIT_UTF16
83702# define sqlite3_bind_text16            0
83703# define sqlite3_collation_needed16     0
83704# define sqlite3_column_decltype16      0
83705# define sqlite3_column_name16          0
83706# define sqlite3_column_text16          0
83707# define sqlite3_complete16             0
83708# define sqlite3_create_collation16     0
83709# define sqlite3_create_function16      0
83710# define sqlite3_errmsg16               0
83711# define sqlite3_open16                 0
83712# define sqlite3_prepare16              0
83713# define sqlite3_prepare16_v2           0
83714# define sqlite3_result_error16         0
83715# define sqlite3_result_text16          0
83716# define sqlite3_result_text16be        0
83717# define sqlite3_result_text16le        0
83718# define sqlite3_value_text16           0
83719# define sqlite3_value_text16be         0
83720# define sqlite3_value_text16le         0
83721# define sqlite3_column_database_name16 0
83722# define sqlite3_column_table_name16    0
83723# define sqlite3_column_origin_name16   0
83724#endif
83725
83726#ifdef SQLITE_OMIT_COMPLETE
83727# define sqlite3_complete 0
83728# define sqlite3_complete16 0
83729#endif
83730
83731#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
83732# define sqlite3_progress_handler 0
83733#endif
83734
83735#ifdef SQLITE_OMIT_VIRTUALTABLE
83736# define sqlite3_create_module 0
83737# define sqlite3_create_module_v2 0
83738# define sqlite3_declare_vtab 0
83739#endif
83740
83741#ifdef SQLITE_OMIT_SHARED_CACHE
83742# define sqlite3_enable_shared_cache 0
83743#endif
83744
83745#ifdef SQLITE_OMIT_TRACE
83746# define sqlite3_profile       0
83747# define sqlite3_trace         0
83748#endif
83749
83750#ifdef SQLITE_OMIT_GET_TABLE
83751# define sqlite3_free_table    0
83752# define sqlite3_get_table     0
83753#endif
83754
83755#ifdef SQLITE_OMIT_INCRBLOB
83756#define sqlite3_bind_zeroblob  0
83757#define sqlite3_blob_bytes     0
83758#define sqlite3_blob_close     0
83759#define sqlite3_blob_open      0
83760#define sqlite3_blob_read      0
83761#define sqlite3_blob_write     0
83762#endif
83763
83764/*
83765** The following structure contains pointers to all SQLite API routines.
83766** A pointer to this structure is passed into extensions when they are
83767** loaded so that the extension can make calls back into the SQLite
83768** library.
83769**
83770** When adding new APIs, add them to the bottom of this structure
83771** in order to preserve backwards compatibility.
83772**
83773** Extensions that use newer APIs should first call the
83774** sqlite3_libversion_number() to make sure that the API they
83775** intend to use is supported by the library.  Extensions should
83776** also check to make sure that the pointer to the function is
83777** not NULL before calling it.
83778*/
83779static const sqlite3_api_routines sqlite3Apis = {
83780  sqlite3_aggregate_context,
83781#ifndef SQLITE_OMIT_DEPRECATED
83782  sqlite3_aggregate_count,
83783#else
83784  0,
83785#endif
83786  sqlite3_bind_blob,
83787  sqlite3_bind_double,
83788  sqlite3_bind_int,
83789  sqlite3_bind_int64,
83790  sqlite3_bind_null,
83791  sqlite3_bind_parameter_count,
83792  sqlite3_bind_parameter_index,
83793  sqlite3_bind_parameter_name,
83794  sqlite3_bind_text,
83795  sqlite3_bind_text16,
83796  sqlite3_bind_value,
83797  sqlite3_busy_handler,
83798  sqlite3_busy_timeout,
83799  sqlite3_changes,
83800  sqlite3_close,
83801  sqlite3_collation_needed,
83802  sqlite3_collation_needed16,
83803  sqlite3_column_blob,
83804  sqlite3_column_bytes,
83805  sqlite3_column_bytes16,
83806  sqlite3_column_count,
83807  sqlite3_column_database_name,
83808  sqlite3_column_database_name16,
83809  sqlite3_column_decltype,
83810  sqlite3_column_decltype16,
83811  sqlite3_column_double,
83812  sqlite3_column_int,
83813  sqlite3_column_int64,
83814  sqlite3_column_name,
83815  sqlite3_column_name16,
83816  sqlite3_column_origin_name,
83817  sqlite3_column_origin_name16,
83818  sqlite3_column_table_name,
83819  sqlite3_column_table_name16,
83820  sqlite3_column_text,
83821  sqlite3_column_text16,
83822  sqlite3_column_type,
83823  sqlite3_column_value,
83824  sqlite3_commit_hook,
83825  sqlite3_complete,
83826  sqlite3_complete16,
83827  sqlite3_create_collation,
83828  sqlite3_create_collation16,
83829  sqlite3_create_function,
83830  sqlite3_create_function16,
83831  sqlite3_create_module,
83832  sqlite3_data_count,
83833  sqlite3_db_handle,
83834  sqlite3_declare_vtab,
83835  sqlite3_enable_shared_cache,
83836  sqlite3_errcode,
83837  sqlite3_errmsg,
83838  sqlite3_errmsg16,
83839  sqlite3_exec,
83840#ifndef SQLITE_OMIT_DEPRECATED
83841  sqlite3_expired,
83842#else
83843  0,
83844#endif
83845  sqlite3_finalize,
83846  sqlite3_free,
83847  sqlite3_free_table,
83848  sqlite3_get_autocommit,
83849  sqlite3_get_auxdata,
83850  sqlite3_get_table,
83851  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
83852  sqlite3_interrupt,
83853  sqlite3_last_insert_rowid,
83854  sqlite3_libversion,
83855  sqlite3_libversion_number,
83856  sqlite3_malloc,
83857  sqlite3_mprintf,
83858  sqlite3_open,
83859  sqlite3_open16,
83860  sqlite3_prepare,
83861  sqlite3_prepare16,
83862  sqlite3_profile,
83863  sqlite3_progress_handler,
83864  sqlite3_realloc,
83865  sqlite3_reset,
83866  sqlite3_result_blob,
83867  sqlite3_result_double,
83868  sqlite3_result_error,
83869  sqlite3_result_error16,
83870  sqlite3_result_int,
83871  sqlite3_result_int64,
83872  sqlite3_result_null,
83873  sqlite3_result_text,
83874  sqlite3_result_text16,
83875  sqlite3_result_text16be,
83876  sqlite3_result_text16le,
83877  sqlite3_result_value,
83878  sqlite3_rollback_hook,
83879  sqlite3_set_authorizer,
83880  sqlite3_set_auxdata,
83881  sqlite3_snprintf,
83882  sqlite3_step,
83883  sqlite3_table_column_metadata,
83884#ifndef SQLITE_OMIT_DEPRECATED
83885  sqlite3_thread_cleanup,
83886#else
83887  0,
83888#endif
83889  sqlite3_total_changes,
83890  sqlite3_trace,
83891#ifndef SQLITE_OMIT_DEPRECATED
83892  sqlite3_transfer_bindings,
83893#else
83894  0,
83895#endif
83896  sqlite3_update_hook,
83897  sqlite3_user_data,
83898  sqlite3_value_blob,
83899  sqlite3_value_bytes,
83900  sqlite3_value_bytes16,
83901  sqlite3_value_double,
83902  sqlite3_value_int,
83903  sqlite3_value_int64,
83904  sqlite3_value_numeric_type,
83905  sqlite3_value_text,
83906  sqlite3_value_text16,
83907  sqlite3_value_text16be,
83908  sqlite3_value_text16le,
83909  sqlite3_value_type,
83910  sqlite3_vmprintf,
83911  /*
83912  ** The original API set ends here.  All extensions can call any
83913  ** of the APIs above provided that the pointer is not NULL.  But
83914  ** before calling APIs that follow, extension should check the
83915  ** sqlite3_libversion_number() to make sure they are dealing with
83916  ** a library that is new enough to support that API.
83917  *************************************************************************
83918  */
83919  sqlite3_overload_function,
83920
83921  /*
83922  ** Added after 3.3.13
83923  */
83924  sqlite3_prepare_v2,
83925  sqlite3_prepare16_v2,
83926  sqlite3_clear_bindings,
83927
83928  /*
83929  ** Added for 3.4.1
83930  */
83931  sqlite3_create_module_v2,
83932
83933  /*
83934  ** Added for 3.5.0
83935  */
83936  sqlite3_bind_zeroblob,
83937  sqlite3_blob_bytes,
83938  sqlite3_blob_close,
83939  sqlite3_blob_open,
83940  sqlite3_blob_read,
83941  sqlite3_blob_write,
83942  sqlite3_create_collation_v2,
83943  sqlite3_file_control,
83944  sqlite3_memory_highwater,
83945  sqlite3_memory_used,
83946#ifdef SQLITE_MUTEX_OMIT
83947  0,
83948  0,
83949  0,
83950  0,
83951  0,
83952#else
83953  sqlite3_mutex_alloc,
83954  sqlite3_mutex_enter,
83955  sqlite3_mutex_free,
83956  sqlite3_mutex_leave,
83957  sqlite3_mutex_try,
83958#endif
83959  sqlite3_open_v2,
83960  sqlite3_release_memory,
83961  sqlite3_result_error_nomem,
83962  sqlite3_result_error_toobig,
83963  sqlite3_sleep,
83964  sqlite3_soft_heap_limit,
83965  sqlite3_vfs_find,
83966  sqlite3_vfs_register,
83967  sqlite3_vfs_unregister,
83968
83969  /*
83970  ** Added for 3.5.8
83971  */
83972  sqlite3_threadsafe,
83973  sqlite3_result_zeroblob,
83974  sqlite3_result_error_code,
83975  sqlite3_test_control,
83976  sqlite3_randomness,
83977  sqlite3_context_db_handle,
83978
83979  /*
83980  ** Added for 3.6.0
83981  */
83982  sqlite3_extended_result_codes,
83983  sqlite3_limit,
83984  sqlite3_next_stmt,
83985  sqlite3_sql,
83986  sqlite3_status,
83987};
83988
83989/*
83990** Attempt to load an SQLite extension library contained in the file
83991** zFile.  The entry point is zProc.  zProc may be 0 in which case a
83992** default entry point name (sqlite3_extension_init) is used.  Use
83993** of the default name is recommended.
83994**
83995** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
83996**
83997** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
83998** error message text.  The calling function should free this memory
83999** by calling sqlite3DbFree(db, ).
84000*/
84001static int sqlite3LoadExtension(
84002  sqlite3 *db,          /* Load the extension into this database connection */
84003  const char *zFile,    /* Name of the shared library containing extension */
84004  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
84005  char **pzErrMsg       /* Put error message here if not 0 */
84006){
84007  sqlite3_vfs *pVfs = db->pVfs;
84008  void *handle;
84009  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
84010  char *zErrmsg = 0;
84011  void **aHandle;
84012  const int nMsg = 300;
84013
84014  if( pzErrMsg ) *pzErrMsg = 0;
84015
84016  /* Ticket #1863.  To avoid a creating security problems for older
84017  ** applications that relink against newer versions of SQLite, the
84018  ** ability to run load_extension is turned off by default.  One
84019  ** must call sqlite3_enable_load_extension() to turn on extension
84020  ** loading.  Otherwise you get the following error.
84021  */
84022  if( (db->flags & SQLITE_LoadExtension)==0 ){
84023    if( pzErrMsg ){
84024      *pzErrMsg = sqlite3_mprintf("not authorized");
84025    }
84026    return SQLITE_ERROR;
84027  }
84028
84029  if( zProc==0 ){
84030    zProc = "sqlite3_extension_init";
84031  }
84032
84033  handle = sqlite3OsDlOpen(pVfs, zFile);
84034  if( handle==0 ){
84035    if( pzErrMsg ){
84036      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
84037      if( zErrmsg ){
84038        sqlite3_snprintf(nMsg, zErrmsg,
84039            "unable to open shared library [%s]", zFile);
84040        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
84041      }
84042    }
84043    return SQLITE_ERROR;
84044  }
84045  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
84046                   sqlite3OsDlSym(pVfs, handle, zProc);
84047  if( xInit==0 ){
84048    if( pzErrMsg ){
84049      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
84050      if( zErrmsg ){
84051        sqlite3_snprintf(nMsg, zErrmsg,
84052            "no entry point [%s] in shared library [%s]", zProc,zFile);
84053        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
84054      }
84055      sqlite3OsDlClose(pVfs, handle);
84056    }
84057    return SQLITE_ERROR;
84058  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
84059    if( pzErrMsg ){
84060      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
84061    }
84062    sqlite3_free(zErrmsg);
84063    sqlite3OsDlClose(pVfs, handle);
84064    return SQLITE_ERROR;
84065  }
84066
84067  /* Append the new shared library handle to the db->aExtension array. */
84068  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
84069  if( aHandle==0 ){
84070    return SQLITE_NOMEM;
84071  }
84072  if( db->nExtension>0 ){
84073    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
84074  }
84075  sqlite3DbFree(db, db->aExtension);
84076  db->aExtension = aHandle;
84077
84078  db->aExtension[db->nExtension++] = handle;
84079  return SQLITE_OK;
84080}
84081SQLITE_API int sqlite3_load_extension(
84082  sqlite3 *db,          /* Load the extension into this database connection */
84083  const char *zFile,    /* Name of the shared library containing extension */
84084  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
84085  char **pzErrMsg       /* Put error message here if not 0 */
84086){
84087  int rc;
84088  sqlite3_mutex_enter(db->mutex);
84089  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
84090  rc = sqlite3ApiExit(db, rc);
84091  sqlite3_mutex_leave(db->mutex);
84092  return rc;
84093}
84094
84095/*
84096** Call this routine when the database connection is closing in order
84097** to clean up loaded extensions
84098*/
84099SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
84100  int i;
84101  assert( sqlite3_mutex_held(db->mutex) );
84102  for(i=0; i<db->nExtension; i++){
84103    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
84104  }
84105  sqlite3DbFree(db, db->aExtension);
84106}
84107
84108/*
84109** Enable or disable extension loading.  Extension loading is disabled by
84110** default so as not to open security holes in older applications.
84111*/
84112SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
84113  sqlite3_mutex_enter(db->mutex);
84114  if( onoff ){
84115    db->flags |= SQLITE_LoadExtension;
84116  }else{
84117    db->flags &= ~SQLITE_LoadExtension;
84118  }
84119  sqlite3_mutex_leave(db->mutex);
84120  return SQLITE_OK;
84121}
84122
84123#endif /* SQLITE_OMIT_LOAD_EXTENSION */
84124
84125/*
84126** The auto-extension code added regardless of whether or not extension
84127** loading is supported.  We need a dummy sqlite3Apis pointer for that
84128** code if regular extension loading is not available.  This is that
84129** dummy pointer.
84130*/
84131#ifdef SQLITE_OMIT_LOAD_EXTENSION
84132static const sqlite3_api_routines sqlite3Apis = { 0 };
84133#endif
84134
84135
84136/*
84137** The following object holds the list of automatically loaded
84138** extensions.
84139**
84140** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
84141** mutex must be held while accessing this list.
84142*/
84143typedef struct sqlite3AutoExtList sqlite3AutoExtList;
84144static SQLITE_WSD struct sqlite3AutoExtList {
84145  int nExt;              /* Number of entries in aExt[] */
84146  void (**aExt)(void);   /* Pointers to the extension init functions */
84147} sqlite3Autoext = { 0, 0 };
84148
84149/* The "wsdAutoext" macro will resolve to the autoextension
84150** state vector.  If writable static data is unsupported on the target,
84151** we have to locate the state vector at run-time.  In the more common
84152** case where writable static data is supported, wsdStat can refer directly
84153** to the "sqlite3Autoext" state vector declared above.
84154*/
84155#ifdef SQLITE_OMIT_WSD
84156# define wsdAutoextInit \
84157  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
84158# define wsdAutoext x[0]
84159#else
84160# define wsdAutoextInit
84161# define wsdAutoext sqlite3Autoext
84162#endif
84163
84164
84165/*
84166** Register a statically linked extension that is automatically
84167** loaded by every new database connection.
84168*/
84169SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
84170  int rc = SQLITE_OK;
84171#ifndef SQLITE_OMIT_AUTOINIT
84172  rc = sqlite3_initialize();
84173  if( rc ){
84174    return rc;
84175  }else
84176#endif
84177  {
84178    int i;
84179#if SQLITE_THREADSAFE
84180    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84181#endif
84182    wsdAutoextInit;
84183    sqlite3_mutex_enter(mutex);
84184    for(i=0; i<wsdAutoext.nExt; i++){
84185      if( wsdAutoext.aExt[i]==xInit ) break;
84186    }
84187    if( i==wsdAutoext.nExt ){
84188      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
84189      void (**aNew)(void);
84190      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
84191      if( aNew==0 ){
84192        rc = SQLITE_NOMEM;
84193      }else{
84194        wsdAutoext.aExt = aNew;
84195        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
84196        wsdAutoext.nExt++;
84197      }
84198    }
84199    sqlite3_mutex_leave(mutex);
84200    assert( (rc&0xff)==rc );
84201    return rc;
84202  }
84203}
84204
84205/*
84206** Reset the automatic extension loading mechanism.
84207*/
84208SQLITE_API void sqlite3_reset_auto_extension(void){
84209#ifndef SQLITE_OMIT_AUTOINIT
84210  if( sqlite3_initialize()==SQLITE_OK )
84211#endif
84212  {
84213#if SQLITE_THREADSAFE
84214    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84215#endif
84216    wsdAutoextInit;
84217    sqlite3_mutex_enter(mutex);
84218    sqlite3_free(wsdAutoext.aExt);
84219    wsdAutoext.aExt = 0;
84220    wsdAutoext.nExt = 0;
84221    sqlite3_mutex_leave(mutex);
84222  }
84223}
84224
84225/*
84226** Load all automatic extensions.
84227**
84228** If anything goes wrong, set an error in the database connection.
84229*/
84230SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
84231  int i;
84232  int go = 1;
84233  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
84234
84235  wsdAutoextInit;
84236  if( wsdAutoext.nExt==0 ){
84237    /* Common case: early out without every having to acquire a mutex */
84238    return;
84239  }
84240  for(i=0; go; i++){
84241    char *zErrmsg;
84242#if SQLITE_THREADSAFE
84243    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
84244#endif
84245    sqlite3_mutex_enter(mutex);
84246    if( i>=wsdAutoext.nExt ){
84247      xInit = 0;
84248      go = 0;
84249    }else{
84250      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
84251              wsdAutoext.aExt[i];
84252    }
84253    sqlite3_mutex_leave(mutex);
84254    zErrmsg = 0;
84255    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
84256      sqlite3Error(db, SQLITE_ERROR,
84257            "automatic extension loading failed: %s", zErrmsg);
84258      go = 0;
84259    }
84260    sqlite3_free(zErrmsg);
84261  }
84262}
84263
84264/************** End of loadext.c *********************************************/
84265/************** Begin file pragma.c ******************************************/
84266/*
84267** 2003 April 6
84268**
84269** The author disclaims copyright to this source code.  In place of
84270** a legal notice, here is a blessing:
84271**
84272**    May you do good and not evil.
84273**    May you find forgiveness for yourself and forgive others.
84274**    May you share freely, never taking more than you give.
84275**
84276*************************************************************************
84277** This file contains code used to implement the PRAGMA command.
84278*/
84279
84280/* Ignore this whole file if pragmas are disabled
84281*/
84282#if !defined(SQLITE_OMIT_PRAGMA)
84283
84284/*
84285** Interpret the given string as a safety level.  Return 0 for OFF,
84286** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
84287** unrecognized string argument.
84288**
84289** Note that the values returned are one less that the values that
84290** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
84291** to support legacy SQL code.  The safety level used to be boolean
84292** and older scripts may have used numbers 0 for OFF and 1 for ON.
84293*/
84294static u8 getSafetyLevel(const char *z){
84295                             /* 123456789 123456789 */
84296  static const char zText[] = "onoffalseyestruefull";
84297  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
84298  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
84299  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
84300  int i, n;
84301  if( sqlite3Isdigit(*z) ){
84302    return (u8)atoi(z);
84303  }
84304  n = sqlite3Strlen30(z);
84305  for(i=0; i<ArraySize(iLength); i++){
84306    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
84307      return iValue[i];
84308    }
84309  }
84310  return 1;
84311}
84312
84313/*
84314** Interpret the given string as a boolean value.
84315*/
84316static u8 getBoolean(const char *z){
84317  return getSafetyLevel(z)&1;
84318}
84319
84320/*
84321** Interpret the given string as a locking mode value.
84322*/
84323static int getLockingMode(const char *z){
84324  if( z ){
84325    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
84326    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
84327  }
84328  return PAGER_LOCKINGMODE_QUERY;
84329}
84330
84331#ifndef SQLITE_OMIT_AUTOVACUUM
84332/*
84333** Interpret the given string as an auto-vacuum mode value.
84334**
84335** The following strings, "none", "full" and "incremental" are
84336** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
84337*/
84338static int getAutoVacuum(const char *z){
84339  int i;
84340  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
84341  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
84342  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
84343  i = atoi(z);
84344  return (u8)((i>=0&&i<=2)?i:0);
84345}
84346#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
84347
84348#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84349/*
84350** Interpret the given string as a temp db location. Return 1 for file
84351** backed temporary databases, 2 for the Red-Black tree in memory database
84352** and 0 to use the compile-time default.
84353*/
84354static int getTempStore(const char *z){
84355  if( z[0]>='0' && z[0]<='2' ){
84356    return z[0] - '0';
84357  }else if( sqlite3StrICmp(z, "file")==0 ){
84358    return 1;
84359  }else if( sqlite3StrICmp(z, "memory")==0 ){
84360    return 2;
84361  }else{
84362    return 0;
84363  }
84364}
84365#endif /* SQLITE_PAGER_PRAGMAS */
84366
84367#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84368/*
84369** Invalidate temp storage, either when the temp storage is changed
84370** from default, or when 'file' and the temp_store_directory has changed
84371*/
84372static int invalidateTempStorage(Parse *pParse){
84373  sqlite3 *db = pParse->db;
84374  if( db->aDb[1].pBt!=0 ){
84375    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
84376      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
84377        "from within a transaction");
84378      return SQLITE_ERROR;
84379    }
84380    sqlite3BtreeClose(db->aDb[1].pBt);
84381    db->aDb[1].pBt = 0;
84382    sqlite3ResetInternalSchema(db, 0);
84383  }
84384  return SQLITE_OK;
84385}
84386#endif /* SQLITE_PAGER_PRAGMAS */
84387
84388#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84389/*
84390** If the TEMP database is open, close it and mark the database schema
84391** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
84392** or DEFAULT_TEMP_STORE pragmas.
84393*/
84394static int changeTempStorage(Parse *pParse, const char *zStorageType){
84395  int ts = getTempStore(zStorageType);
84396  sqlite3 *db = pParse->db;
84397  if( db->temp_store==ts ) return SQLITE_OK;
84398  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
84399    return SQLITE_ERROR;
84400  }
84401  db->temp_store = (u8)ts;
84402  return SQLITE_OK;
84403}
84404#endif /* SQLITE_PAGER_PRAGMAS */
84405
84406/*
84407** Generate code to return a single integer value.
84408*/
84409static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
84410  Vdbe *v = sqlite3GetVdbe(pParse);
84411  int mem = ++pParse->nMem;
84412  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
84413  if( pI64 ){
84414    memcpy(pI64, &value, sizeof(value));
84415  }
84416  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
84417  sqlite3VdbeSetNumCols(v, 1);
84418  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
84419  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
84420}
84421
84422#ifndef SQLITE_OMIT_FLAG_PRAGMAS
84423/*
84424** Check to see if zRight and zLeft refer to a pragma that queries
84425** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
84426** Also, implement the pragma.
84427*/
84428static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
84429  static const struct sPragmaType {
84430    const char *zName;  /* Name of the pragma */
84431    int mask;           /* Mask for the db->flags value */
84432  } aPragma[] = {
84433    { "full_column_names",        SQLITE_FullColNames  },
84434    { "short_column_names",       SQLITE_ShortColNames },
84435    { "count_changes",            SQLITE_CountRows     },
84436    { "empty_result_callbacks",   SQLITE_NullCallback  },
84437    { "legacy_file_format",       SQLITE_LegacyFileFmt },
84438    { "fullfsync",                SQLITE_FullFSync     },
84439    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
84440#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
84441    { "automatic_index",          SQLITE_AutoIndex     },
84442#endif
84443#ifdef SQLITE_DEBUG
84444    { "sql_trace",                SQLITE_SqlTrace      },
84445    { "vdbe_listing",             SQLITE_VdbeListing   },
84446    { "vdbe_trace",               SQLITE_VdbeTrace     },
84447#endif
84448#ifndef SQLITE_OMIT_CHECK
84449    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
84450#endif
84451    /* The following is VERY experimental */
84452    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
84453    { "omit_readlock",            SQLITE_NoReadlock    },
84454
84455    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
84456    ** flag if there are any active statements. */
84457    { "read_uncommitted",         SQLITE_ReadUncommitted },
84458    { "recursive_triggers",       SQLITE_RecTriggers },
84459
84460    /* This flag may only be set if both foreign-key and trigger support
84461    ** are present in the build.  */
84462#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
84463    { "foreign_keys",             SQLITE_ForeignKeys },
84464#endif
84465  };
84466  int i;
84467  const struct sPragmaType *p;
84468  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
84469    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
84470      sqlite3 *db = pParse->db;
84471      Vdbe *v;
84472      v = sqlite3GetVdbe(pParse);
84473      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
84474      if( ALWAYS(v) ){
84475        if( zRight==0 ){
84476          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
84477        }else{
84478          int mask = p->mask;          /* Mask of bits to set or clear. */
84479          if( db->autoCommit==0 ){
84480            /* Foreign key support may not be enabled or disabled while not
84481            ** in auto-commit mode.  */
84482            mask &= ~(SQLITE_ForeignKeys);
84483          }
84484
84485          if( getBoolean(zRight) ){
84486            db->flags |= mask;
84487          }else{
84488            db->flags &= ~mask;
84489          }
84490
84491          /* Many of the flag-pragmas modify the code generated by the SQL
84492          ** compiler (eg. count_changes). So add an opcode to expire all
84493          ** compiled SQL statements after modifying a pragma value.
84494          */
84495          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
84496        }
84497      }
84498
84499      return 1;
84500    }
84501  }
84502  return 0;
84503}
84504#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
84505
84506/*
84507** Return a human-readable name for a constraint resolution action.
84508*/
84509#ifndef SQLITE_OMIT_FOREIGN_KEY
84510static const char *actionName(u8 action){
84511  const char *zName;
84512  switch( action ){
84513    case OE_SetNull:  zName = "SET NULL";        break;
84514    case OE_SetDflt:  zName = "SET DEFAULT";     break;
84515    case OE_Cascade:  zName = "CASCADE";         break;
84516    case OE_Restrict: zName = "RESTRICT";        break;
84517    default:          zName = "NO ACTION";
84518                      assert( action==OE_None ); break;
84519  }
84520  return zName;
84521}
84522#endif
84523
84524
84525/*
84526** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
84527** defined in pager.h. This function returns the associated lowercase
84528** journal-mode name.
84529*/
84530SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
84531  static char * const azModeName[] = {
84532    "delete", "persist", "off", "truncate", "memory"
84533#ifndef SQLITE_OMIT_WAL
84534     , "wal"
84535#endif
84536  };
84537  assert( PAGER_JOURNALMODE_DELETE==0 );
84538  assert( PAGER_JOURNALMODE_PERSIST==1 );
84539  assert( PAGER_JOURNALMODE_OFF==2 );
84540  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
84541  assert( PAGER_JOURNALMODE_MEMORY==4 );
84542  assert( PAGER_JOURNALMODE_WAL==5 );
84543  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
84544
84545  if( eMode==ArraySize(azModeName) ) return 0;
84546  return azModeName[eMode];
84547}
84548
84549/*
84550** Process a pragma statement.
84551**
84552** Pragmas are of this form:
84553**
84554**      PRAGMA [database.]id [= value]
84555**
84556** The identifier might also be a string.  The value is a string, and
84557** identifier, or a number.  If minusFlag is true, then the value is
84558** a number that was preceded by a minus sign.
84559**
84560** If the left side is "database.id" then pId1 is the database name
84561** and pId2 is the id.  If the left side is just "id" then pId1 is the
84562** id and pId2 is any empty string.
84563*/
84564SQLITE_PRIVATE void sqlite3Pragma(
84565  Parse *pParse,
84566  Token *pId1,        /* First part of [database.]id field */
84567  Token *pId2,        /* Second part of [database.]id field, or NULL */
84568  Token *pValue,      /* Token for <value>, or NULL */
84569  int minusFlag       /* True if a '-' sign preceded <value> */
84570){
84571  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
84572  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
84573  const char *zDb = 0;   /* The database name */
84574  Token *pId;            /* Pointer to <id> token */
84575  int iDb;               /* Database index for <database> */
84576  sqlite3 *db = pParse->db;
84577  Db *pDb;
84578  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
84579  if( v==0 ) return;
84580  sqlite3VdbeRunOnlyOnce(v);
84581  pParse->nMem = 2;
84582
84583  /* Interpret the [database.] part of the pragma statement. iDb is the
84584  ** index of the database this pragma is being applied to in db.aDb[]. */
84585  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
84586  if( iDb<0 ) return;
84587  pDb = &db->aDb[iDb];
84588
84589  /* If the temp database has been explicitly named as part of the
84590  ** pragma, make sure it is open.
84591  */
84592  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
84593    return;
84594  }
84595
84596  zLeft = sqlite3NameFromToken(db, pId);
84597  if( !zLeft ) return;
84598  if( minusFlag ){
84599    zRight = sqlite3MPrintf(db, "-%T", pValue);
84600  }else{
84601    zRight = sqlite3NameFromToken(db, pValue);
84602  }
84603
84604  assert( pId2 );
84605  zDb = pId2->n>0 ? pDb->zName : 0;
84606  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
84607    goto pragma_out;
84608  }
84609
84610#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84611  /*
84612  **  PRAGMA [database.]default_cache_size
84613  **  PRAGMA [database.]default_cache_size=N
84614  **
84615  ** The first form reports the current persistent setting for the
84616  ** page cache size.  The value returned is the maximum number of
84617  ** pages in the page cache.  The second form sets both the current
84618  ** page cache size value and the persistent page cache size value
84619  ** stored in the database file.
84620  **
84621  ** Older versions of SQLite would set the default cache size to a
84622  ** negative number to indicate synchronous=OFF.  These days, synchronous
84623  ** is always on by default regardless of the sign of the default cache
84624  ** size.  But continue to take the absolute value of the default cache
84625  ** size of historical compatibility.
84626  */
84627  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
84628    static const VdbeOpList getCacheSize[] = {
84629      { OP_Transaction, 0, 0,        0},                         /* 0 */
84630      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
84631      { OP_IfPos,       1, 7,        0},
84632      { OP_Integer,     0, 2,        0},
84633      { OP_Subtract,    1, 2,        1},
84634      { OP_IfPos,       1, 7,        0},
84635      { OP_Integer,     0, 1,        0},                         /* 6 */
84636      { OP_ResultRow,   1, 1,        0},
84637    };
84638    int addr;
84639    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84640    sqlite3VdbeUsesBtree(v, iDb);
84641    if( !zRight ){
84642      sqlite3VdbeSetNumCols(v, 1);
84643      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
84644      pParse->nMem += 2;
84645      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
84646      sqlite3VdbeChangeP1(v, addr, iDb);
84647      sqlite3VdbeChangeP1(v, addr+1, iDb);
84648      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
84649    }else{
84650      int size = atoi(zRight);
84651      if( size<0 ) size = -size;
84652      sqlite3BeginWriteOperation(pParse, 0, iDb);
84653      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
84654      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
84655      pDb->pSchema->cache_size = size;
84656      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
84657    }
84658  }else
84659
84660  /*
84661  **  PRAGMA [database.]page_size
84662  **  PRAGMA [database.]page_size=N
84663  **
84664  ** The first form reports the current setting for the
84665  ** database page size in bytes.  The second form sets the
84666  ** database page size value.  The value can only be set if
84667  ** the database has not yet been created.
84668  */
84669  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
84670    Btree *pBt = pDb->pBt;
84671    assert( pBt!=0 );
84672    if( !zRight ){
84673      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
84674      returnSingleInt(pParse, "page_size", size);
84675    }else{
84676      /* Malloc may fail when setting the page-size, as there is an internal
84677      ** buffer that the pager module resizes using sqlite3_realloc().
84678      */
84679      db->nextPagesize = atoi(zRight);
84680      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84681        db->mallocFailed = 1;
84682      }
84683    }
84684  }else
84685
84686  /*
84687  **  PRAGMA [database.]max_page_count
84688  **  PRAGMA [database.]max_page_count=N
84689  **
84690  ** The first form reports the current setting for the
84691  ** maximum number of pages in the database file.  The
84692  ** second form attempts to change this setting.  Both
84693  ** forms return the current setting.
84694  */
84695  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
84696    Btree *pBt = pDb->pBt;
84697    int newMax = 0;
84698    assert( pBt!=0 );
84699    if( zRight ){
84700      newMax = atoi(zRight);
84701    }
84702    if( ALWAYS(pBt) ){
84703      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
84704    }
84705    returnSingleInt(pParse, "max_page_count", newMax);
84706  }else
84707
84708  /*
84709  **  PRAGMA [database.]secure_delete
84710  **  PRAGMA [database.]secure_delete=ON/OFF
84711  **
84712  ** The first form reports the current setting for the
84713  ** secure_delete flag.  The second form changes the secure_delete
84714  ** flag setting and reports thenew value.
84715  */
84716  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
84717    Btree *pBt = pDb->pBt;
84718    int b = -1;
84719    assert( pBt!=0 );
84720    if( zRight ){
84721      b = getBoolean(zRight);
84722    }
84723    if( pId2->n==0 && b>=0 ){
84724      int ii;
84725      for(ii=0; ii<db->nDb; ii++){
84726        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
84727      }
84728    }
84729    b = sqlite3BtreeSecureDelete(pBt, b);
84730    returnSingleInt(pParse, "secure_delete", b);
84731  }else
84732
84733  /*
84734  **  PRAGMA [database.]page_count
84735  **
84736  ** Return the number of pages in the specified database.
84737  */
84738  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
84739    int iReg;
84740    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84741    sqlite3CodeVerifySchema(pParse, iDb);
84742    iReg = ++pParse->nMem;
84743    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
84744    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
84745    sqlite3VdbeSetNumCols(v, 1);
84746    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
84747  }else
84748
84749  /*
84750  **  PRAGMA [database.]locking_mode
84751  **  PRAGMA [database.]locking_mode = (normal|exclusive)
84752  */
84753  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
84754    const char *zRet = "normal";
84755    int eMode = getLockingMode(zRight);
84756
84757    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
84758      /* Simple "PRAGMA locking_mode;" statement. This is a query for
84759      ** the current default locking mode (which may be different to
84760      ** the locking-mode of the main database).
84761      */
84762      eMode = db->dfltLockMode;
84763    }else{
84764      Pager *pPager;
84765      if( pId2->n==0 ){
84766        /* This indicates that no database name was specified as part
84767        ** of the PRAGMA command. In this case the locking-mode must be
84768        ** set on all attached databases, as well as the main db file.
84769        **
84770        ** Also, the sqlite3.dfltLockMode variable is set so that
84771        ** any subsequently attached databases also use the specified
84772        ** locking mode.
84773        */
84774        int ii;
84775        assert(pDb==&db->aDb[0]);
84776        for(ii=2; ii<db->nDb; ii++){
84777          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
84778          sqlite3PagerLockingMode(pPager, eMode);
84779        }
84780        db->dfltLockMode = (u8)eMode;
84781      }
84782      pPager = sqlite3BtreePager(pDb->pBt);
84783      eMode = sqlite3PagerLockingMode(pPager, eMode);
84784    }
84785
84786    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
84787    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
84788      zRet = "exclusive";
84789    }
84790    sqlite3VdbeSetNumCols(v, 1);
84791    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
84792    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
84793    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84794  }else
84795
84796  /*
84797  **  PRAGMA [database.]journal_mode
84798  **  PRAGMA [database.]journal_mode =
84799  **                      (delete|persist|off|truncate|memory|wal|off)
84800  */
84801  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
84802    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
84803    int ii;           /* Loop counter */
84804
84805    /* Force the schema to be loaded on all databases.  This cases all
84806    ** database files to be opened and the journal_modes set. */
84807    if( sqlite3ReadSchema(pParse) ){
84808      goto pragma_out;
84809    }
84810
84811    sqlite3VdbeSetNumCols(v, 1);
84812    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
84813
84814    if( zRight==0 ){
84815      /* If there is no "=MODE" part of the pragma, do a query for the
84816      ** current mode */
84817      eMode = PAGER_JOURNALMODE_QUERY;
84818    }else{
84819      const char *zMode;
84820      int n = sqlite3Strlen30(zRight);
84821      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
84822        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
84823      }
84824      if( !zMode ){
84825        /* If the "=MODE" part does not match any known journal mode,
84826        ** then do a query */
84827        eMode = PAGER_JOURNALMODE_QUERY;
84828      }
84829    }
84830    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
84831      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
84832      iDb = 0;
84833      pId2->n = 1;
84834    }
84835    for(ii=db->nDb-1; ii>=0; ii--){
84836      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
84837        sqlite3VdbeUsesBtree(v, ii);
84838        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
84839      }
84840    }
84841    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
84842  }else
84843
84844  /*
84845  **  PRAGMA [database.]journal_size_limit
84846  **  PRAGMA [database.]journal_size_limit=N
84847  **
84848  ** Get or set the size limit on rollback journal files.
84849  */
84850  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
84851    Pager *pPager = sqlite3BtreePager(pDb->pBt);
84852    i64 iLimit = -2;
84853    if( zRight ){
84854      sqlite3Atoi64(zRight, &iLimit);
84855      if( iLimit<-1 ) iLimit = -1;
84856    }
84857    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
84858    returnSingleInt(pParse, "journal_size_limit", iLimit);
84859  }else
84860
84861#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
84862
84863  /*
84864  **  PRAGMA [database.]auto_vacuum
84865  **  PRAGMA [database.]auto_vacuum=N
84866  **
84867  ** Get or set the value of the database 'auto-vacuum' parameter.
84868  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
84869  */
84870#ifndef SQLITE_OMIT_AUTOVACUUM
84871  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
84872    Btree *pBt = pDb->pBt;
84873    assert( pBt!=0 );
84874    if( sqlite3ReadSchema(pParse) ){
84875      goto pragma_out;
84876    }
84877    if( !zRight ){
84878      int auto_vacuum;
84879      if( ALWAYS(pBt) ){
84880         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
84881      }else{
84882         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
84883      }
84884      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
84885    }else{
84886      int eAuto = getAutoVacuum(zRight);
84887      assert( eAuto>=0 && eAuto<=2 );
84888      db->nextAutovac = (u8)eAuto;
84889      if( ALWAYS(eAuto>=0) ){
84890        /* Call SetAutoVacuum() to set initialize the internal auto and
84891        ** incr-vacuum flags. This is required in case this connection
84892        ** creates the database file. It is important that it is created
84893        ** as an auto-vacuum capable db.
84894        */
84895        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
84896        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
84897          /* When setting the auto_vacuum mode to either "full" or
84898          ** "incremental", write the value of meta[6] in the database
84899          ** file. Before writing to meta[6], check that meta[3] indicates
84900          ** that this really is an auto-vacuum capable database.
84901          */
84902          static const VdbeOpList setMeta6[] = {
84903            { OP_Transaction,    0,         1,                 0},    /* 0 */
84904            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
84905            { OP_If,             1,         0,                 0},    /* 2 */
84906            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
84907            { OP_Integer,        0,         1,                 0},    /* 4 */
84908            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
84909          };
84910          int iAddr;
84911          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
84912          sqlite3VdbeChangeP1(v, iAddr, iDb);
84913          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
84914          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
84915          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
84916          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
84917          sqlite3VdbeUsesBtree(v, iDb);
84918        }
84919      }
84920    }
84921  }else
84922#endif
84923
84924  /*
84925  **  PRAGMA [database.]incremental_vacuum(N)
84926  **
84927  ** Do N steps of incremental vacuuming on a database.
84928  */
84929#ifndef SQLITE_OMIT_AUTOVACUUM
84930  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
84931    int iLimit, addr;
84932    if( sqlite3ReadSchema(pParse) ){
84933      goto pragma_out;
84934    }
84935    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
84936      iLimit = 0x7fffffff;
84937    }
84938    sqlite3BeginWriteOperation(pParse, 0, iDb);
84939    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
84940    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
84941    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
84942    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
84943    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
84944    sqlite3VdbeJumpHere(v, addr);
84945  }else
84946#endif
84947
84948#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84949  /*
84950  **  PRAGMA [database.]cache_size
84951  **  PRAGMA [database.]cache_size=N
84952  **
84953  ** The first form reports the current local setting for the
84954  ** page cache size.  The local setting can be different from
84955  ** the persistent cache size value that is stored in the database
84956  ** file itself.  The value returned is the maximum number of
84957  ** pages in the page cache.  The second form sets the local
84958  ** page cache size value.  It does not change the persistent
84959  ** cache size stored on the disk so the cache size will revert
84960  ** to its default value when the database is closed and reopened.
84961  ** N should be a positive integer.
84962  */
84963  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
84964    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
84965    if( !zRight ){
84966      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
84967    }else{
84968      int size = atoi(zRight);
84969      if( size<0 ) size = -size;
84970      pDb->pSchema->cache_size = size;
84971      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
84972    }
84973  }else
84974
84975  /*
84976  **   PRAGMA temp_store
84977  **   PRAGMA temp_store = "default"|"memory"|"file"
84978  **
84979  ** Return or set the local value of the temp_store flag.  Changing
84980  ** the local value does not make changes to the disk file and the default
84981  ** value will be restored the next time the database is opened.
84982  **
84983  ** Note that it is possible for the library compile-time options to
84984  ** override this setting
84985  */
84986  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
84987    if( !zRight ){
84988      returnSingleInt(pParse, "temp_store", db->temp_store);
84989    }else{
84990      changeTempStorage(pParse, zRight);
84991    }
84992  }else
84993
84994  /*
84995  **   PRAGMA temp_store_directory
84996  **   PRAGMA temp_store_directory = ""|"directory_name"
84997  **
84998  ** Return or set the local value of the temp_store_directory flag.  Changing
84999  ** the value sets a specific directory to be used for temporary files.
85000  ** Setting to a null string reverts to the default temporary directory search.
85001  ** If temporary directory is changed, then invalidateTempStorage.
85002  **
85003  */
85004  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
85005    if( !zRight ){
85006      if( sqlite3_temp_directory ){
85007        sqlite3VdbeSetNumCols(v, 1);
85008        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
85009            "temp_store_directory", SQLITE_STATIC);
85010        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
85011        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85012      }
85013    }else{
85014#ifndef SQLITE_OMIT_WSD
85015      if( zRight[0] ){
85016        int rc;
85017        int res;
85018        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
85019        if( rc!=SQLITE_OK || res==0 ){
85020          sqlite3ErrorMsg(pParse, "not a writable directory");
85021          goto pragma_out;
85022        }
85023      }
85024      if( SQLITE_TEMP_STORE==0
85025       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
85026       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
85027      ){
85028        invalidateTempStorage(pParse);
85029      }
85030      sqlite3_free(sqlite3_temp_directory);
85031      if( zRight[0] ){
85032        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
85033      }else{
85034        sqlite3_temp_directory = 0;
85035      }
85036#endif /* SQLITE_OMIT_WSD */
85037    }
85038  }else
85039
85040#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
85041#  if defined(__APPLE__)
85042#    define SQLITE_ENABLE_LOCKING_STYLE 1
85043#  else
85044#    define SQLITE_ENABLE_LOCKING_STYLE 0
85045#  endif
85046#endif
85047#if SQLITE_ENABLE_LOCKING_STYLE
85048  /*
85049   **   PRAGMA [database.]lock_proxy_file
85050   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
85051   **
85052   ** Return or set the value of the lock_proxy_file flag.  Changing
85053   ** the value sets a specific file to be used for database access locks.
85054   **
85055   */
85056  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
85057    if( !zRight ){
85058      Pager *pPager = sqlite3BtreePager(pDb->pBt);
85059      char *proxy_file_path = NULL;
85060      sqlite3_file *pFile = sqlite3PagerFile(pPager);
85061      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
85062                           &proxy_file_path);
85063
85064      if( proxy_file_path ){
85065        sqlite3VdbeSetNumCols(v, 1);
85066        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
85067                              "lock_proxy_file", SQLITE_STATIC);
85068        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
85069        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85070      }
85071    }else{
85072      Pager *pPager = sqlite3BtreePager(pDb->pBt);
85073      sqlite3_file *pFile = sqlite3PagerFile(pPager);
85074      int res;
85075      if( zRight[0] ){
85076        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
85077                                     zRight);
85078      } else {
85079        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
85080                                     NULL);
85081      }
85082      if( res!=SQLITE_OK ){
85083        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
85084        goto pragma_out;
85085      }
85086    }
85087  }else
85088#endif /* SQLITE_ENABLE_LOCKING_STYLE */
85089
85090  /*
85091  **   PRAGMA [database.]synchronous
85092  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
85093  **
85094  ** Return or set the local value of the synchronous flag.  Changing
85095  ** the local value does not make changes to the disk file and the
85096  ** default value will be restored the next time the database is
85097  ** opened.
85098  */
85099  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
85100    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85101    if( !zRight ){
85102      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
85103    }else{
85104      if( !db->autoCommit ){
85105        sqlite3ErrorMsg(pParse,
85106            "Safety level may not be changed inside a transaction");
85107      }else{
85108        pDb->safety_level = getSafetyLevel(zRight)+1;
85109      }
85110    }
85111  }else
85112#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
85113
85114#ifndef SQLITE_OMIT_FLAG_PRAGMAS
85115  if( flagPragma(pParse, zLeft, zRight) ){
85116    /* The flagPragma() subroutine also generates any necessary code
85117    ** there is nothing more to do here */
85118  }else
85119#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
85120
85121#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
85122  /*
85123  **   PRAGMA table_info(<table>)
85124  **
85125  ** Return a single row for each column of the named table. The columns of
85126  ** the returned data set are:
85127  **
85128  ** cid:        Column id (numbered from left to right, starting at 0)
85129  ** name:       Column name
85130  ** type:       Column declaration type.
85131  ** notnull:    True if 'NOT NULL' is part of column declaration
85132  ** dflt_value: The default value for the column, if any.
85133  */
85134  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
85135    Table *pTab;
85136    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85137    pTab = sqlite3FindTable(db, zRight, zDb);
85138    if( pTab ){
85139      int i;
85140      int nHidden = 0;
85141      Column *pCol;
85142      sqlite3VdbeSetNumCols(v, 6);
85143      pParse->nMem = 6;
85144      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
85145      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85146      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
85147      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
85148      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
85149      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
85150      sqlite3ViewGetColumnNames(pParse, pTab);
85151      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
85152        if( IsHiddenColumn(pCol) ){
85153          nHidden++;
85154          continue;
85155        }
85156        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
85157        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
85158        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
85159           pCol->zType ? pCol->zType : "", 0);
85160        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
85161        if( pCol->zDflt ){
85162          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
85163        }else{
85164          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
85165        }
85166        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
85167        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
85168      }
85169    }
85170  }else
85171
85172  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
85173    Index *pIdx;
85174    Table *pTab;
85175    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85176    pIdx = sqlite3FindIndex(db, zRight, zDb);
85177    if( pIdx ){
85178      int i;
85179      pTab = pIdx->pTable;
85180      sqlite3VdbeSetNumCols(v, 3);
85181      pParse->nMem = 3;
85182      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
85183      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
85184      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
85185      for(i=0; i<pIdx->nColumn; i++){
85186        int cnum = pIdx->aiColumn[i];
85187        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85188        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
85189        assert( pTab->nCol>cnum );
85190        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
85191        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
85192      }
85193    }
85194  }else
85195
85196  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
85197    Index *pIdx;
85198    Table *pTab;
85199    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85200    pTab = sqlite3FindTable(db, zRight, zDb);
85201    if( pTab ){
85202      v = sqlite3GetVdbe(pParse);
85203      pIdx = pTab->pIndex;
85204      if( pIdx ){
85205        int i = 0;
85206        sqlite3VdbeSetNumCols(v, 3);
85207        pParse->nMem = 3;
85208        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
85209        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85210        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
85211        while(pIdx){
85212          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85213          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
85214          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
85215          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
85216          ++i;
85217          pIdx = pIdx->pNext;
85218        }
85219      }
85220    }
85221  }else
85222
85223  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
85224    int i;
85225    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85226    sqlite3VdbeSetNumCols(v, 3);
85227    pParse->nMem = 3;
85228    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
85229    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85230    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
85231    for(i=0; i<db->nDb; i++){
85232      if( db->aDb[i].pBt==0 ) continue;
85233      assert( db->aDb[i].zName!=0 );
85234      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85235      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
85236      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
85237           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
85238      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
85239    }
85240  }else
85241
85242  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
85243    int i = 0;
85244    HashElem *p;
85245    sqlite3VdbeSetNumCols(v, 2);
85246    pParse->nMem = 2;
85247    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
85248    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
85249    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
85250      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
85251      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
85252      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
85253      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
85254    }
85255  }else
85256#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
85257
85258#ifndef SQLITE_OMIT_FOREIGN_KEY
85259  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
85260    FKey *pFK;
85261    Table *pTab;
85262    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85263    pTab = sqlite3FindTable(db, zRight, zDb);
85264    if( pTab ){
85265      v = sqlite3GetVdbe(pParse);
85266      pFK = pTab->pFKey;
85267      if( pFK ){
85268        int i = 0;
85269        sqlite3VdbeSetNumCols(v, 8);
85270        pParse->nMem = 8;
85271        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
85272        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
85273        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
85274        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
85275        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
85276        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
85277        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
85278        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
85279        while(pFK){
85280          int j;
85281          for(j=0; j<pFK->nCol; j++){
85282            char *zCol = pFK->aCol[j].zCol;
85283            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
85284            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
85285            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
85286            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
85287            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
85288            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
85289                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
85290            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
85291            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
85292            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
85293            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
85294            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
85295          }
85296          ++i;
85297          pFK = pFK->pNextFrom;
85298        }
85299      }
85300    }
85301  }else
85302#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
85303
85304#ifndef NDEBUG
85305  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
85306    if( zRight ){
85307      if( getBoolean(zRight) ){
85308        sqlite3ParserTrace(stderr, "parser: ");
85309      }else{
85310        sqlite3ParserTrace(0, 0);
85311      }
85312    }
85313  }else
85314#endif
85315
85316  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
85317  ** used will be case sensitive or not depending on the RHS.
85318  */
85319  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
85320    if( zRight ){
85321      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
85322    }
85323  }else
85324
85325#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
85326# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
85327#endif
85328
85329#ifndef SQLITE_OMIT_INTEGRITY_CHECK
85330  /* Pragma "quick_check" is an experimental reduced version of
85331  ** integrity_check designed to detect most database corruption
85332  ** without most of the overhead of a full integrity-check.
85333  */
85334  if( sqlite3StrICmp(zLeft, "integrity_check")==0
85335   || sqlite3StrICmp(zLeft, "quick_check")==0
85336  ){
85337    int i, j, addr, mxErr;
85338
85339    /* Code that appears at the end of the integrity check.  If no error
85340    ** messages have been generated, output OK.  Otherwise output the
85341    ** error message
85342    */
85343    static const VdbeOpList endCode[] = {
85344      { OP_AddImm,      1, 0,        0},    /* 0 */
85345      { OP_IfNeg,       1, 0,        0},    /* 1 */
85346      { OP_String8,     0, 3,        0},    /* 2 */
85347      { OP_ResultRow,   3, 1,        0},
85348    };
85349
85350    int isQuick = (zLeft[0]=='q');
85351
85352    /* Initialize the VDBE program */
85353    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85354    pParse->nMem = 6;
85355    sqlite3VdbeSetNumCols(v, 1);
85356    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
85357
85358    /* Set the maximum error count */
85359    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
85360    if( zRight ){
85361      mxErr = atoi(zRight);
85362      if( mxErr<=0 ){
85363        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
85364      }
85365    }
85366    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
85367
85368    /* Do an integrity check on each database file */
85369    for(i=0; i<db->nDb; i++){
85370      HashElem *x;
85371      Hash *pTbls;
85372      int cnt = 0;
85373
85374      if( OMIT_TEMPDB && i==1 ) continue;
85375
85376      sqlite3CodeVerifySchema(pParse, i);
85377      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
85378      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
85379      sqlite3VdbeJumpHere(v, addr);
85380
85381      /* Do an integrity check of the B-Tree
85382      **
85383      ** Begin by filling registers 2, 3, ... with the root pages numbers
85384      ** for all tables and indices in the database.
85385      */
85386      pTbls = &db->aDb[i].pSchema->tblHash;
85387      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
85388        Table *pTab = sqliteHashData(x);
85389        Index *pIdx;
85390        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
85391        cnt++;
85392        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85393          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
85394          cnt++;
85395        }
85396      }
85397
85398      /* Make sure sufficient number of registers have been allocated */
85399      if( pParse->nMem < cnt+4 ){
85400        pParse->nMem = cnt+4;
85401      }
85402
85403      /* Do the b-tree integrity checks */
85404      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
85405      sqlite3VdbeChangeP5(v, (u8)i);
85406      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
85407      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
85408         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
85409         P4_DYNAMIC);
85410      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
85411      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
85412      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
85413      sqlite3VdbeJumpHere(v, addr);
85414
85415      /* Make sure all the indices are constructed correctly.
85416      */
85417      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
85418        Table *pTab = sqliteHashData(x);
85419        Index *pIdx;
85420        int loopTop;
85421
85422        if( pTab->pIndex==0 ) continue;
85423        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
85424        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
85425        sqlite3VdbeJumpHere(v, addr);
85426        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
85427        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
85428        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
85429        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
85430        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
85431          int jmp2;
85432          int r1;
85433          static const VdbeOpList idxErr[] = {
85434            { OP_AddImm,      1, -1,  0},
85435            { OP_String8,     0,  3,  0},    /* 1 */
85436            { OP_Rowid,       1,  4,  0},
85437            { OP_String8,     0,  5,  0},    /* 3 */
85438            { OP_String8,     0,  6,  0},    /* 4 */
85439            { OP_Concat,      4,  3,  3},
85440            { OP_Concat,      5,  3,  3},
85441            { OP_Concat,      6,  3,  3},
85442            { OP_ResultRow,   3,  1,  0},
85443            { OP_IfPos,       1,  0,  0},    /* 9 */
85444            { OP_Halt,        0,  0,  0},
85445          };
85446          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
85447          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
85448          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
85449          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
85450          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
85451          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
85452          sqlite3VdbeJumpHere(v, addr+9);
85453          sqlite3VdbeJumpHere(v, jmp2);
85454        }
85455        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
85456        sqlite3VdbeJumpHere(v, loopTop);
85457        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
85458          static const VdbeOpList cntIdx[] = {
85459             { OP_Integer,      0,  3,  0},
85460             { OP_Rewind,       0,  0,  0},  /* 1 */
85461             { OP_AddImm,       3,  1,  0},
85462             { OP_Next,         0,  0,  0},  /* 3 */
85463             { OP_Eq,           2,  0,  3},  /* 4 */
85464             { OP_AddImm,       1, -1,  0},
85465             { OP_String8,      0,  2,  0},  /* 6 */
85466             { OP_String8,      0,  3,  0},  /* 7 */
85467             { OP_Concat,       3,  2,  2},
85468             { OP_ResultRow,    2,  1,  0},
85469          };
85470          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
85471          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
85472          sqlite3VdbeJumpHere(v, addr);
85473          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
85474          sqlite3VdbeChangeP1(v, addr+1, j+2);
85475          sqlite3VdbeChangeP2(v, addr+1, addr+4);
85476          sqlite3VdbeChangeP1(v, addr+3, j+2);
85477          sqlite3VdbeChangeP2(v, addr+3, addr+2);
85478          sqlite3VdbeJumpHere(v, addr+4);
85479          sqlite3VdbeChangeP4(v, addr+6,
85480                     "wrong # of entries in index ", P4_STATIC);
85481          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
85482        }
85483      }
85484    }
85485    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
85486    sqlite3VdbeChangeP2(v, addr, -mxErr);
85487    sqlite3VdbeJumpHere(v, addr+1);
85488    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
85489  }else
85490#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
85491
85492#ifndef SQLITE_OMIT_UTF16
85493  /*
85494  **   PRAGMA encoding
85495  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
85496  **
85497  ** In its first form, this pragma returns the encoding of the main
85498  ** database. If the database is not initialized, it is initialized now.
85499  **
85500  ** The second form of this pragma is a no-op if the main database file
85501  ** has not already been initialized. In this case it sets the default
85502  ** encoding that will be used for the main database file if a new file
85503  ** is created. If an existing main database file is opened, then the
85504  ** default text encoding for the existing database is used.
85505  **
85506  ** In all cases new databases created using the ATTACH command are
85507  ** created to use the same default text encoding as the main database. If
85508  ** the main database has not been initialized and/or created when ATTACH
85509  ** is executed, this is done before the ATTACH operation.
85510  **
85511  ** In the second form this pragma sets the text encoding to be used in
85512  ** new database files created using this database handle. It is only
85513  ** useful if invoked immediately after the main database i
85514  */
85515  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
85516    static const struct EncName {
85517      char *zName;
85518      u8 enc;
85519    } encnames[] = {
85520      { "UTF8",     SQLITE_UTF8        },
85521      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
85522      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
85523      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
85524      { "UTF16le",  SQLITE_UTF16LE     },
85525      { "UTF16be",  SQLITE_UTF16BE     },
85526      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
85527      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
85528      { 0, 0 }
85529    };
85530    const struct EncName *pEnc;
85531    if( !zRight ){    /* "PRAGMA encoding" */
85532      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85533      sqlite3VdbeSetNumCols(v, 1);
85534      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
85535      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
85536      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
85537      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
85538      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
85539      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
85540      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85541    }else{                        /* "PRAGMA encoding = XXX" */
85542      /* Only change the value of sqlite.enc if the database handle is not
85543      ** initialized. If the main database exists, the new sqlite.enc value
85544      ** will be overwritten when the schema is next loaded. If it does not
85545      ** already exists, it will be created to use the new encoding value.
85546      */
85547      if(
85548        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
85549        DbHasProperty(db, 0, DB_Empty)
85550      ){
85551        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
85552          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
85553            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
85554            break;
85555          }
85556        }
85557        if( !pEnc->zName ){
85558          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
85559        }
85560      }
85561    }
85562  }else
85563#endif /* SQLITE_OMIT_UTF16 */
85564
85565#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
85566  /*
85567  **   PRAGMA [database.]schema_version
85568  **   PRAGMA [database.]schema_version = <integer>
85569  **
85570  **   PRAGMA [database.]user_version
85571  **   PRAGMA [database.]user_version = <integer>
85572  **
85573  ** The pragma's schema_version and user_version are used to set or get
85574  ** the value of the schema-version and user-version, respectively. Both
85575  ** the schema-version and the user-version are 32-bit signed integers
85576  ** stored in the database header.
85577  **
85578  ** The schema-cookie is usually only manipulated internally by SQLite. It
85579  ** is incremented by SQLite whenever the database schema is modified (by
85580  ** creating or dropping a table or index). The schema version is used by
85581  ** SQLite each time a query is executed to ensure that the internal cache
85582  ** of the schema used when compiling the SQL query matches the schema of
85583  ** the database against which the compiled query is actually executed.
85584  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
85585  ** the schema-version is potentially dangerous and may lead to program
85586  ** crashes or database corruption. Use with caution!
85587  **
85588  ** The user-version is not used internally by SQLite. It may be used by
85589  ** applications for any purpose.
85590  */
85591  if( sqlite3StrICmp(zLeft, "schema_version")==0
85592   || sqlite3StrICmp(zLeft, "user_version")==0
85593   || sqlite3StrICmp(zLeft, "freelist_count")==0
85594  ){
85595    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
85596    sqlite3VdbeUsesBtree(v, iDb);
85597    switch( zLeft[0] ){
85598      case 'f': case 'F':
85599        iCookie = BTREE_FREE_PAGE_COUNT;
85600        break;
85601      case 's': case 'S':
85602        iCookie = BTREE_SCHEMA_VERSION;
85603        break;
85604      default:
85605        iCookie = BTREE_USER_VERSION;
85606        break;
85607    }
85608
85609    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
85610      /* Write the specified cookie value */
85611      static const VdbeOpList setCookie[] = {
85612        { OP_Transaction,    0,  1,  0},    /* 0 */
85613        { OP_Integer,        0,  1,  0},    /* 1 */
85614        { OP_SetCookie,      0,  0,  1},    /* 2 */
85615      };
85616      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
85617      sqlite3VdbeChangeP1(v, addr, iDb);
85618      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
85619      sqlite3VdbeChangeP1(v, addr+2, iDb);
85620      sqlite3VdbeChangeP2(v, addr+2, iCookie);
85621    }else{
85622      /* Read the specified cookie value */
85623      static const VdbeOpList readCookie[] = {
85624        { OP_Transaction,     0,  0,  0},    /* 0 */
85625        { OP_ReadCookie,      0,  1,  0},    /* 1 */
85626        { OP_ResultRow,       1,  1,  0}
85627      };
85628      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
85629      sqlite3VdbeChangeP1(v, addr, iDb);
85630      sqlite3VdbeChangeP1(v, addr+1, iDb);
85631      sqlite3VdbeChangeP3(v, addr+1, iCookie);
85632      sqlite3VdbeSetNumCols(v, 1);
85633      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
85634    }
85635  }else
85636#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
85637
85638#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85639  /*
85640  **   PRAGMA compile_options
85641  **
85642  ** Return the names of all compile-time options used in this build,
85643  ** one option per row.
85644  */
85645  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
85646    int i = 0;
85647    const char *zOpt;
85648    sqlite3VdbeSetNumCols(v, 1);
85649    pParse->nMem = 1;
85650    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
85651    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
85652      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
85653      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85654    }
85655  }else
85656#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85657
85658#ifndef SQLITE_OMIT_WAL
85659  /*
85660  **   PRAGMA [database.]wal_checkpoint
85661  **
85662  ** Checkpoint the database.
85663  */
85664  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
85665    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85666    sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
85667  }else
85668
85669  /*
85670  **   PRAGMA wal_autocheckpoint
85671  **   PRAGMA wal_autocheckpoint = N
85672  **
85673  ** Configure a database connection to automatically checkpoint a database
85674  ** after accumulating N frames in the log. Or query for the current value
85675  ** of N.
85676  */
85677  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
85678    if( zRight ){
85679      int nAuto = atoi(zRight);
85680      sqlite3_wal_autocheckpoint(db, nAuto);
85681    }
85682    returnSingleInt(pParse, "wal_autocheckpoint",
85683       db->xWalCallback==sqlite3WalDefaultHook ?
85684           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
85685  }else
85686#endif
85687
85688#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
85689  /*
85690  ** Report the current state of file logs for all databases
85691  */
85692  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
85693    static const char *const azLockName[] = {
85694      "unlocked", "shared", "reserved", "pending", "exclusive"
85695    };
85696    int i;
85697    sqlite3VdbeSetNumCols(v, 2);
85698    pParse->nMem = 2;
85699    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
85700    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
85701    for(i=0; i<db->nDb; i++){
85702      Btree *pBt;
85703      Pager *pPager;
85704      const char *zState = "unknown";
85705      int j;
85706      if( db->aDb[i].zName==0 ) continue;
85707      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
85708      pBt = db->aDb[i].pBt;
85709      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
85710        zState = "closed";
85711      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
85712                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
85713         zState = azLockName[j];
85714      }
85715      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
85716      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
85717    }
85718
85719  }else
85720#endif
85721
85722#ifdef SQLITE_HAS_CODEC
85723  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
85724    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
85725  }else
85726  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
85727    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
85728  }else
85729  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
85730                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
85731    int i, h1, h2;
85732    char zKey[40];
85733    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
85734      h1 += 9*(1&(h1>>6));
85735      h2 += 9*(1&(h2>>6));
85736      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
85737    }
85738    if( (zLeft[3] & 0xf)==0xb ){
85739      sqlite3_key(db, zKey, i/2);
85740    }else{
85741      sqlite3_rekey(db, zKey, i/2);
85742    }
85743  }else
85744#endif
85745#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
85746  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
85747#ifdef SQLITE_HAS_CODEC
85748    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
85749      sqlite3_activate_see(&zRight[4]);
85750    }
85751#endif
85752#ifdef SQLITE_ENABLE_CEROD
85753    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
85754      sqlite3_activate_cerod(&zRight[6]);
85755    }
85756#endif
85757  }else
85758#endif
85759
85760
85761  {/* Empty ELSE clause */}
85762
85763  /*
85764  ** Reset the safety level, in case the fullfsync flag or synchronous
85765  ** setting changed.
85766  */
85767#ifndef SQLITE_OMIT_PAGER_PRAGMAS
85768  if( db->autoCommit ){
85769    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
85770               (db->flags&SQLITE_FullFSync)!=0);
85771  }
85772#endif
85773pragma_out:
85774  sqlite3DbFree(db, zLeft);
85775  sqlite3DbFree(db, zRight);
85776}
85777
85778#endif /* SQLITE_OMIT_PRAGMA */
85779
85780/************** End of pragma.c **********************************************/
85781/************** Begin file prepare.c *****************************************/
85782/*
85783** 2005 May 25
85784**
85785** The author disclaims copyright to this source code.  In place of
85786** a legal notice, here is a blessing:
85787**
85788**    May you do good and not evil.
85789**    May you find forgiveness for yourself and forgive others.
85790**    May you share freely, never taking more than you give.
85791**
85792*************************************************************************
85793** This file contains the implementation of the sqlite3_prepare()
85794** interface, and routines that contribute to loading the database schema
85795** from disk.
85796*/
85797
85798/*
85799** Fill the InitData structure with an error message that indicates
85800** that the database is corrupt.
85801*/
85802static void corruptSchema(
85803  InitData *pData,     /* Initialization context */
85804  const char *zObj,    /* Object being parsed at the point of error */
85805  const char *zExtra   /* Error information */
85806){
85807  sqlite3 *db = pData->db;
85808  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
85809    if( zObj==0 ) zObj = "?";
85810    sqlite3SetString(pData->pzErrMsg, db,
85811      "malformed database schema (%s)", zObj);
85812    if( zExtra ){
85813      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
85814                                 "%s - %s", *pData->pzErrMsg, zExtra);
85815    }
85816  }
85817  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
85818}
85819
85820/*
85821** This is the callback routine for the code that initializes the
85822** database.  See sqlite3Init() below for additional information.
85823** This routine is also called from the OP_ParseSchema opcode of the VDBE.
85824**
85825** Each callback contains the following information:
85826**
85827**     argv[0] = name of thing being created
85828**     argv[1] = root page number for table or index. 0 for trigger or view.
85829**     argv[2] = SQL text for the CREATE statement.
85830**
85831*/
85832SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
85833  InitData *pData = (InitData*)pInit;
85834  sqlite3 *db = pData->db;
85835  int iDb = pData->iDb;
85836
85837  assert( argc==3 );
85838  UNUSED_PARAMETER2(NotUsed, argc);
85839  assert( sqlite3_mutex_held(db->mutex) );
85840  DbClearProperty(db, iDb, DB_Empty);
85841  if( db->mallocFailed ){
85842    corruptSchema(pData, argv[0], 0);
85843    return 1;
85844  }
85845
85846  assert( iDb>=0 && iDb<db->nDb );
85847  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
85848  if( argv[1]==0 ){
85849    corruptSchema(pData, argv[0], 0);
85850  }else if( argv[2] && argv[2][0] ){
85851    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
85852    ** But because db->init.busy is set to 1, no VDBE code is generated
85853    ** or executed.  All the parser does is build the internal data
85854    ** structures that describe the table, index, or view.
85855    */
85856    int rc;
85857    sqlite3_stmt *pStmt;
85858    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
85859
85860    assert( db->init.busy );
85861    db->init.iDb = iDb;
85862    db->init.newTnum = atoi(argv[1]);
85863    db->init.orphanTrigger = 0;
85864    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
85865    rc = db->errCode;
85866    assert( (rc&0xFF)==(rcp&0xFF) );
85867    db->init.iDb = 0;
85868    if( SQLITE_OK!=rc ){
85869      if( db->init.orphanTrigger ){
85870        assert( iDb==1 );
85871      }else{
85872        pData->rc = rc;
85873        if( rc==SQLITE_NOMEM ){
85874          db->mallocFailed = 1;
85875        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
85876          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
85877        }
85878      }
85879    }
85880    sqlite3_finalize(pStmt);
85881  }else if( argv[0]==0 ){
85882    corruptSchema(pData, 0, 0);
85883  }else{
85884    /* If the SQL column is blank it means this is an index that
85885    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
85886    ** constraint for a CREATE TABLE.  The index should have already
85887    ** been created when we processed the CREATE TABLE.  All we have
85888    ** to do here is record the root page number for that index.
85889    */
85890    Index *pIndex;
85891    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
85892    if( pIndex==0 ){
85893      /* This can occur if there exists an index on a TEMP table which
85894      ** has the same name as another index on a permanent index.  Since
85895      ** the permanent table is hidden by the TEMP table, we can also
85896      ** safely ignore the index on the permanent table.
85897      */
85898      /* Do Nothing */;
85899    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
85900      corruptSchema(pData, argv[0], "invalid rootpage");
85901    }
85902  }
85903  return 0;
85904}
85905
85906/*
85907** Attempt to read the database schema and initialize internal
85908** data structures for a single database file.  The index of the
85909** database file is given by iDb.  iDb==0 is used for the main
85910** database.  iDb==1 should never be used.  iDb>=2 is used for
85911** auxiliary databases.  Return one of the SQLITE_ error codes to
85912** indicate success or failure.
85913*/
85914static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
85915  int rc;
85916  int i;
85917  int size;
85918  Table *pTab;
85919  Db *pDb;
85920  char const *azArg[4];
85921  int meta[5];
85922  InitData initData;
85923  char const *zMasterSchema;
85924  char const *zMasterName = SCHEMA_TABLE(iDb);
85925  int openedTransaction = 0;
85926
85927  /*
85928  ** The master database table has a structure like this
85929  */
85930  static const char master_schema[] =
85931     "CREATE TABLE sqlite_master(\n"
85932     "  type text,\n"
85933     "  name text,\n"
85934     "  tbl_name text,\n"
85935     "  rootpage integer,\n"
85936     "  sql text\n"
85937     ")"
85938  ;
85939#ifndef SQLITE_OMIT_TEMPDB
85940  static const char temp_master_schema[] =
85941     "CREATE TEMP TABLE sqlite_temp_master(\n"
85942     "  type text,\n"
85943     "  name text,\n"
85944     "  tbl_name text,\n"
85945     "  rootpage integer,\n"
85946     "  sql text\n"
85947     ")"
85948  ;
85949#else
85950  #define temp_master_schema 0
85951#endif
85952
85953  assert( iDb>=0 && iDb<db->nDb );
85954  assert( db->aDb[iDb].pSchema );
85955  assert( sqlite3_mutex_held(db->mutex) );
85956  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
85957
85958  /* zMasterSchema and zInitScript are set to point at the master schema
85959  ** and initialisation script appropriate for the database being
85960  ** initialised. zMasterName is the name of the master table.
85961  */
85962  if( !OMIT_TEMPDB && iDb==1 ){
85963    zMasterSchema = temp_master_schema;
85964  }else{
85965    zMasterSchema = master_schema;
85966  }
85967  zMasterName = SCHEMA_TABLE(iDb);
85968
85969  /* Construct the schema tables.  */
85970  azArg[0] = zMasterName;
85971  azArg[1] = "1";
85972  azArg[2] = zMasterSchema;
85973  azArg[3] = 0;
85974  initData.db = db;
85975  initData.iDb = iDb;
85976  initData.rc = SQLITE_OK;
85977  initData.pzErrMsg = pzErrMsg;
85978  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
85979  if( initData.rc ){
85980    rc = initData.rc;
85981    goto error_out;
85982  }
85983  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
85984  if( ALWAYS(pTab) ){
85985    pTab->tabFlags |= TF_Readonly;
85986  }
85987
85988  /* Create a cursor to hold the database open
85989  */
85990  pDb = &db->aDb[iDb];
85991  if( pDb->pBt==0 ){
85992    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
85993      DbSetProperty(db, 1, DB_SchemaLoaded);
85994    }
85995    return SQLITE_OK;
85996  }
85997
85998  /* If there is not already a read-only (or read-write) transaction opened
85999  ** on the b-tree database, open one now. If a transaction is opened, it
86000  ** will be closed before this function returns.  */
86001  sqlite3BtreeEnter(pDb->pBt);
86002  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
86003    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
86004    if( rc!=SQLITE_OK ){
86005      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
86006      goto initone_error_out;
86007    }
86008    openedTransaction = 1;
86009  }
86010
86011  /* Get the database meta information.
86012  **
86013  ** Meta values are as follows:
86014  **    meta[0]   Schema cookie.  Changes with each schema change.
86015  **    meta[1]   File format of schema layer.
86016  **    meta[2]   Size of the page cache.
86017  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
86018  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
86019  **    meta[5]   User version
86020  **    meta[6]   Incremental vacuum mode
86021  **    meta[7]   unused
86022  **    meta[8]   unused
86023  **    meta[9]   unused
86024  **
86025  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
86026  ** the possible values of meta[4].
86027  */
86028  for(i=0; i<ArraySize(meta); i++){
86029    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
86030  }
86031  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
86032
86033  /* If opening a non-empty database, check the text encoding. For the
86034  ** main database, set sqlite3.enc to the encoding of the main database.
86035  ** For an attached db, it is an error if the encoding is not the same
86036  ** as sqlite3.enc.
86037  */
86038  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
86039    if( iDb==0 ){
86040      u8 encoding;
86041      /* If opening the main database, set ENC(db). */
86042      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
86043      if( encoding==0 ) encoding = SQLITE_UTF8;
86044      ENC(db) = encoding;
86045      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
86046    }else{
86047      /* If opening an attached database, the encoding much match ENC(db) */
86048      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
86049        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
86050            " text encoding as main database");
86051        rc = SQLITE_ERROR;
86052        goto initone_error_out;
86053      }
86054    }
86055  }else{
86056    DbSetProperty(db, iDb, DB_Empty);
86057  }
86058  pDb->pSchema->enc = ENC(db);
86059
86060  if( pDb->pSchema->cache_size==0 ){
86061    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
86062    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
86063    if( size<0 ) size = -size;
86064    pDb->pSchema->cache_size = size;
86065    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
86066  }
86067
86068  /*
86069  ** file_format==1    Version 3.0.0.
86070  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
86071  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
86072  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
86073  */
86074  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
86075  if( pDb->pSchema->file_format==0 ){
86076    pDb->pSchema->file_format = 1;
86077  }
86078  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
86079    sqlite3SetString(pzErrMsg, db, "unsupported file format");
86080    rc = SQLITE_ERROR;
86081    goto initone_error_out;
86082  }
86083
86084  /* Ticket #2804:  When we open a database in the newer file format,
86085  ** clear the legacy_file_format pragma flag so that a VACUUM will
86086  ** not downgrade the database and thus invalidate any descending
86087  ** indices that the user might have created.
86088  */
86089  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
86090    db->flags &= ~SQLITE_LegacyFileFmt;
86091  }
86092
86093  /* Read the schema information out of the schema tables
86094  */
86095  assert( db->init.busy );
86096  {
86097    char *zSql;
86098    zSql = sqlite3MPrintf(db,
86099        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
86100        db->aDb[iDb].zName, zMasterName);
86101#ifndef SQLITE_OMIT_AUTHORIZATION
86102    {
86103      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
86104      xAuth = db->xAuth;
86105      db->xAuth = 0;
86106#endif
86107      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
86108#ifndef SQLITE_OMIT_AUTHORIZATION
86109      db->xAuth = xAuth;
86110    }
86111#endif
86112    if( rc==SQLITE_OK ) rc = initData.rc;
86113    sqlite3DbFree(db, zSql);
86114#ifndef SQLITE_OMIT_ANALYZE
86115    if( rc==SQLITE_OK ){
86116      sqlite3AnalysisLoad(db, iDb);
86117    }
86118#endif
86119  }
86120  if( db->mallocFailed ){
86121    rc = SQLITE_NOMEM;
86122    sqlite3ResetInternalSchema(db, 0);
86123  }
86124  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
86125    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
86126    ** the schema loaded, even if errors occurred. In this situation the
86127    ** current sqlite3_prepare() operation will fail, but the following one
86128    ** will attempt to compile the supplied statement against whatever subset
86129    ** of the schema was loaded before the error occurred. The primary
86130    ** purpose of this is to allow access to the sqlite_master table
86131    ** even when its contents have been corrupted.
86132    */
86133    DbSetProperty(db, iDb, DB_SchemaLoaded);
86134    rc = SQLITE_OK;
86135  }
86136
86137  /* Jump here for an error that occurs after successfully allocating
86138  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
86139  ** before that point, jump to error_out.
86140  */
86141initone_error_out:
86142  if( openedTransaction ){
86143    sqlite3BtreeCommit(pDb->pBt);
86144  }
86145  sqlite3BtreeLeave(pDb->pBt);
86146
86147error_out:
86148  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
86149    db->mallocFailed = 1;
86150  }
86151  return rc;
86152}
86153
86154/*
86155** Initialize all database files - the main database file, the file
86156** used to store temporary tables, and any additional database files
86157** created using ATTACH statements.  Return a success code.  If an
86158** error occurs, write an error message into *pzErrMsg.
86159**
86160** After a database is initialized, the DB_SchemaLoaded bit is set
86161** bit is set in the flags field of the Db structure. If the database
86162** file was of zero-length, then the DB_Empty flag is also set.
86163*/
86164SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
86165  int i, rc;
86166  int commit_internal = !(db->flags&SQLITE_InternChanges);
86167
86168  assert( sqlite3_mutex_held(db->mutex) );
86169  rc = SQLITE_OK;
86170  db->init.busy = 1;
86171  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
86172    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
86173    rc = sqlite3InitOne(db, i, pzErrMsg);
86174    if( rc ){
86175      sqlite3ResetInternalSchema(db, i);
86176    }
86177  }
86178
86179  /* Once all the other databases have been initialised, load the schema
86180  ** for the TEMP database. This is loaded last, as the TEMP database
86181  ** schema may contain references to objects in other databases.
86182  */
86183#ifndef SQLITE_OMIT_TEMPDB
86184  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
86185                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
86186    rc = sqlite3InitOne(db, 1, pzErrMsg);
86187    if( rc ){
86188      sqlite3ResetInternalSchema(db, 1);
86189    }
86190  }
86191#endif
86192
86193  db->init.busy = 0;
86194  if( rc==SQLITE_OK && commit_internal ){
86195    sqlite3CommitInternalChanges(db);
86196  }
86197
86198  return rc;
86199}
86200
86201/*
86202** This routine is a no-op if the database schema is already initialised.
86203** Otherwise, the schema is loaded. An error code is returned.
86204*/
86205SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
86206  int rc = SQLITE_OK;
86207  sqlite3 *db = pParse->db;
86208  assert( sqlite3_mutex_held(db->mutex) );
86209  if( !db->init.busy ){
86210    rc = sqlite3Init(db, &pParse->zErrMsg);
86211  }
86212  if( rc!=SQLITE_OK ){
86213    pParse->rc = rc;
86214    pParse->nErr++;
86215  }
86216  return rc;
86217}
86218
86219
86220/*
86221** Check schema cookies in all databases.  If any cookie is out
86222** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
86223** make no changes to pParse->rc.
86224*/
86225static void schemaIsValid(Parse *pParse){
86226  sqlite3 *db = pParse->db;
86227  int iDb;
86228  int rc;
86229  int cookie;
86230
86231  assert( pParse->checkSchema );
86232  assert( sqlite3_mutex_held(db->mutex) );
86233  for(iDb=0; iDb<db->nDb; iDb++){
86234    int openedTransaction = 0;         /* True if a transaction is opened */
86235    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
86236    if( pBt==0 ) continue;
86237
86238    /* If there is not already a read-only (or read-write) transaction opened
86239    ** on the b-tree database, open one now. If a transaction is opened, it
86240    ** will be closed immediately after reading the meta-value. */
86241    if( !sqlite3BtreeIsInReadTrans(pBt) ){
86242      rc = sqlite3BtreeBeginTrans(pBt, 0);
86243      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
86244        db->mallocFailed = 1;
86245      }
86246      if( rc!=SQLITE_OK ) return;
86247      openedTransaction = 1;
86248    }
86249
86250    /* Read the schema cookie from the database. If it does not match the
86251    ** value stored as part of the in-memory schema representation,
86252    ** set Parse.rc to SQLITE_SCHEMA. */
86253    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
86254    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
86255      pParse->rc = SQLITE_SCHEMA;
86256    }
86257
86258    /* Close the transaction, if one was opened. */
86259    if( openedTransaction ){
86260      sqlite3BtreeCommit(pBt);
86261    }
86262  }
86263}
86264
86265/*
86266** Convert a schema pointer into the iDb index that indicates
86267** which database file in db->aDb[] the schema refers to.
86268**
86269** If the same database is attached more than once, the first
86270** attached database is returned.
86271*/
86272SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
86273  int i = -1000000;
86274
86275  /* If pSchema is NULL, then return -1000000. This happens when code in
86276  ** expr.c is trying to resolve a reference to a transient table (i.e. one
86277  ** created by a sub-select). In this case the return value of this
86278  ** function should never be used.
86279  **
86280  ** We return -1000000 instead of the more usual -1 simply because using
86281  ** -1000000 as the incorrect index into db->aDb[] is much
86282  ** more likely to cause a segfault than -1 (of course there are assert()
86283  ** statements too, but it never hurts to play the odds).
86284  */
86285  assert( sqlite3_mutex_held(db->mutex) );
86286  if( pSchema ){
86287    for(i=0; ALWAYS(i<db->nDb); i++){
86288      if( db->aDb[i].pSchema==pSchema ){
86289        break;
86290      }
86291    }
86292    assert( i>=0 && i<db->nDb );
86293  }
86294  return i;
86295}
86296
86297/*
86298** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
86299*/
86300static int sqlite3Prepare(
86301  sqlite3 *db,              /* Database handle. */
86302  const char *zSql,         /* UTF-8 encoded SQL statement. */
86303  int nBytes,               /* Length of zSql in bytes. */
86304  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
86305  Vdbe *pReprepare,         /* VM being reprepared */
86306  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86307  const char **pzTail       /* OUT: End of parsed string */
86308){
86309  Parse *pParse;            /* Parsing context */
86310  char *zErrMsg = 0;        /* Error message */
86311  int rc = SQLITE_OK;       /* Result code */
86312  int i;                    /* Loop counter */
86313
86314  /* Allocate the parsing context */
86315  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86316  if( pParse==0 ){
86317    rc = SQLITE_NOMEM;
86318    goto end_prepare;
86319  }
86320  pParse->pReprepare = pReprepare;
86321  assert( ppStmt && *ppStmt==0 );
86322  assert( !db->mallocFailed );
86323  assert( sqlite3_mutex_held(db->mutex) );
86324
86325  /* Check to verify that it is possible to get a read lock on all
86326  ** database schemas.  The inability to get a read lock indicates that
86327  ** some other database connection is holding a write-lock, which in
86328  ** turn means that the other connection has made uncommitted changes
86329  ** to the schema.
86330  **
86331  ** Were we to proceed and prepare the statement against the uncommitted
86332  ** schema changes and if those schema changes are subsequently rolled
86333  ** back and different changes are made in their place, then when this
86334  ** prepared statement goes to run the schema cookie would fail to detect
86335  ** the schema change.  Disaster would follow.
86336  **
86337  ** This thread is currently holding mutexes on all Btrees (because
86338  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
86339  ** is not possible for another thread to start a new schema change
86340  ** while this routine is running.  Hence, we do not need to hold
86341  ** locks on the schema, we just need to make sure nobody else is
86342  ** holding them.
86343  **
86344  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
86345  ** but it does *not* override schema lock detection, so this all still
86346  ** works even if READ_UNCOMMITTED is set.
86347  */
86348  for(i=0; i<db->nDb; i++) {
86349    Btree *pBt = db->aDb[i].pBt;
86350    if( pBt ){
86351      assert( sqlite3BtreeHoldsMutex(pBt) );
86352      rc = sqlite3BtreeSchemaLocked(pBt);
86353      if( rc ){
86354        const char *zDb = db->aDb[i].zName;
86355        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
86356        testcase( db->flags & SQLITE_ReadUncommitted );
86357        goto end_prepare;
86358      }
86359    }
86360  }
86361
86362  sqlite3VtabUnlockList(db);
86363
86364  pParse->db = db;
86365  pParse->nQueryLoop = (double)1;
86366  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
86367    char *zSqlCopy;
86368    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
86369    testcase( nBytes==mxLen );
86370    testcase( nBytes==mxLen+1 );
86371    if( nBytes>mxLen ){
86372      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
86373      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
86374      goto end_prepare;
86375    }
86376    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
86377    if( zSqlCopy ){
86378      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
86379      sqlite3DbFree(db, zSqlCopy);
86380      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
86381    }else{
86382      pParse->zTail = &zSql[nBytes];
86383    }
86384  }else{
86385    sqlite3RunParser(pParse, zSql, &zErrMsg);
86386  }
86387  assert( 1==(int)pParse->nQueryLoop );
86388
86389  if( db->mallocFailed ){
86390    pParse->rc = SQLITE_NOMEM;
86391  }
86392  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
86393  if( pParse->checkSchema ){
86394    schemaIsValid(pParse);
86395  }
86396  if( pParse->rc==SQLITE_SCHEMA ){
86397    sqlite3ResetInternalSchema(db, 0);
86398  }
86399  if( db->mallocFailed ){
86400    pParse->rc = SQLITE_NOMEM;
86401  }
86402  if( pzTail ){
86403    *pzTail = pParse->zTail;
86404  }
86405  rc = pParse->rc;
86406
86407#ifndef SQLITE_OMIT_EXPLAIN
86408  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
86409    static const char * const azColName[] = {
86410       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
86411       "order", "from", "detail"
86412    };
86413    int iFirst, mx;
86414    if( pParse->explain==2 ){
86415      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
86416      iFirst = 8;
86417      mx = 11;
86418    }else{
86419      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
86420      iFirst = 0;
86421      mx = 8;
86422    }
86423    for(i=iFirst; i<mx; i++){
86424      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
86425                            azColName[i], SQLITE_STATIC);
86426    }
86427  }
86428#endif
86429
86430  assert( db->init.busy==0 || saveSqlFlag==0 );
86431  if( db->init.busy==0 ){
86432    Vdbe *pVdbe = pParse->pVdbe;
86433    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
86434  }
86435  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
86436    sqlite3VdbeFinalize(pParse->pVdbe);
86437    assert(!(*ppStmt));
86438  }else{
86439    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
86440  }
86441
86442  if( zErrMsg ){
86443    sqlite3Error(db, rc, "%s", zErrMsg);
86444    sqlite3DbFree(db, zErrMsg);
86445  }else{
86446    sqlite3Error(db, rc, 0);
86447  }
86448
86449  /* Delete any TriggerPrg structures allocated while parsing this statement. */
86450  while( pParse->pTriggerPrg ){
86451    TriggerPrg *pT = pParse->pTriggerPrg;
86452    pParse->pTriggerPrg = pT->pNext;
86453    sqlite3DbFree(db, pT);
86454  }
86455
86456end_prepare:
86457
86458  sqlite3StackFree(db, pParse);
86459  rc = sqlite3ApiExit(db, rc);
86460  assert( (rc&db->errMask)==rc );
86461  return rc;
86462}
86463static int sqlite3LockAndPrepare(
86464  sqlite3 *db,              /* Database handle. */
86465  const char *zSql,         /* UTF-8 encoded SQL statement. */
86466  int nBytes,               /* Length of zSql in bytes. */
86467  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
86468  Vdbe *pOld,               /* VM being reprepared */
86469  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86470  const char **pzTail       /* OUT: End of parsed string */
86471){
86472  int rc;
86473  assert( ppStmt!=0 );
86474  *ppStmt = 0;
86475  if( !sqlite3SafetyCheckOk(db) ){
86476    return SQLITE_MISUSE_BKPT;
86477  }
86478  sqlite3_mutex_enter(db->mutex);
86479  sqlite3BtreeEnterAll(db);
86480  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
86481  if( rc==SQLITE_SCHEMA ){
86482    sqlite3_finalize(*ppStmt);
86483    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
86484  }
86485  sqlite3BtreeLeaveAll(db);
86486  sqlite3_mutex_leave(db->mutex);
86487  return rc;
86488}
86489
86490/*
86491** Rerun the compilation of a statement after a schema change.
86492**
86493** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
86494** if the statement cannot be recompiled because another connection has
86495** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
86496** occurs, return SQLITE_SCHEMA.
86497*/
86498SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
86499  int rc;
86500  sqlite3_stmt *pNew;
86501  const char *zSql;
86502  sqlite3 *db;
86503
86504  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
86505  zSql = sqlite3_sql((sqlite3_stmt *)p);
86506  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
86507  db = sqlite3VdbeDb(p);
86508  assert( sqlite3_mutex_held(db->mutex) );
86509  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
86510  if( rc ){
86511    if( rc==SQLITE_NOMEM ){
86512      db->mallocFailed = 1;
86513    }
86514    assert( pNew==0 );
86515    return rc;
86516  }else{
86517    assert( pNew!=0 );
86518  }
86519  sqlite3VdbeSwap((Vdbe*)pNew, p);
86520  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
86521  sqlite3VdbeResetStepResult((Vdbe*)pNew);
86522  sqlite3VdbeFinalize((Vdbe*)pNew);
86523  return SQLITE_OK;
86524}
86525
86526
86527/*
86528** Two versions of the official API.  Legacy and new use.  In the legacy
86529** version, the original SQL text is not saved in the prepared statement
86530** and so if a schema change occurs, SQLITE_SCHEMA is returned by
86531** sqlite3_step().  In the new version, the original SQL text is retained
86532** and the statement is automatically recompiled if an schema change
86533** occurs.
86534*/
86535SQLITE_API int sqlite3_prepare(
86536  sqlite3 *db,              /* Database handle. */
86537  const char *zSql,         /* UTF-8 encoded SQL statement. */
86538  int nBytes,               /* Length of zSql in bytes. */
86539  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86540  const char **pzTail       /* OUT: End of parsed string */
86541){
86542  int rc;
86543  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
86544  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
86545  return rc;
86546}
86547SQLITE_API int sqlite3_prepare_v2(
86548  sqlite3 *db,              /* Database handle. */
86549  const char *zSql,         /* UTF-8 encoded SQL statement. */
86550  int nBytes,               /* Length of zSql in bytes. */
86551  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86552  const char **pzTail       /* OUT: End of parsed string */
86553){
86554  int rc;
86555  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
86556  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
86557  return rc;
86558}
86559
86560
86561#ifndef SQLITE_OMIT_UTF16
86562/*
86563** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
86564*/
86565static int sqlite3Prepare16(
86566  sqlite3 *db,              /* Database handle. */
86567  const void *zSql,         /* UTF-8 encoded SQL statement. */
86568  int nBytes,               /* Length of zSql in bytes. */
86569  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
86570  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86571  const void **pzTail       /* OUT: End of parsed string */
86572){
86573  /* This function currently works by first transforming the UTF-16
86574  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
86575  ** tricky bit is figuring out the pointer to return in *pzTail.
86576  */
86577  char *zSql8;
86578  const char *zTail8 = 0;
86579  int rc = SQLITE_OK;
86580
86581  assert( ppStmt );
86582  *ppStmt = 0;
86583  if( !sqlite3SafetyCheckOk(db) ){
86584    return SQLITE_MISUSE_BKPT;
86585  }
86586  sqlite3_mutex_enter(db->mutex);
86587  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
86588  if( zSql8 ){
86589    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
86590  }
86591
86592  if( zTail8 && pzTail ){
86593    /* If sqlite3_prepare returns a tail pointer, we calculate the
86594    ** equivalent pointer into the UTF-16 string by counting the unicode
86595    ** characters between zSql8 and zTail8, and then returning a pointer
86596    ** the same number of characters into the UTF-16 string.
86597    */
86598    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
86599    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
86600  }
86601  sqlite3DbFree(db, zSql8);
86602  rc = sqlite3ApiExit(db, rc);
86603  sqlite3_mutex_leave(db->mutex);
86604  return rc;
86605}
86606
86607/*
86608** Two versions of the official API.  Legacy and new use.  In the legacy
86609** version, the original SQL text is not saved in the prepared statement
86610** and so if a schema change occurs, SQLITE_SCHEMA is returned by
86611** sqlite3_step().  In the new version, the original SQL text is retained
86612** and the statement is automatically recompiled if an schema change
86613** occurs.
86614*/
86615SQLITE_API int sqlite3_prepare16(
86616  sqlite3 *db,              /* Database handle. */
86617  const void *zSql,         /* UTF-8 encoded SQL statement. */
86618  int nBytes,               /* Length of zSql in bytes. */
86619  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86620  const void **pzTail       /* OUT: End of parsed string */
86621){
86622  int rc;
86623  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
86624  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
86625  return rc;
86626}
86627SQLITE_API int sqlite3_prepare16_v2(
86628  sqlite3 *db,              /* Database handle. */
86629  const void *zSql,         /* UTF-8 encoded SQL statement. */
86630  int nBytes,               /* Length of zSql in bytes. */
86631  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
86632  const void **pzTail       /* OUT: End of parsed string */
86633){
86634  int rc;
86635  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
86636  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
86637  return rc;
86638}
86639
86640#endif /* SQLITE_OMIT_UTF16 */
86641
86642/************** End of prepare.c *********************************************/
86643/************** Begin file select.c ******************************************/
86644/*
86645** 2001 September 15
86646**
86647** The author disclaims copyright to this source code.  In place of
86648** a legal notice, here is a blessing:
86649**
86650**    May you do good and not evil.
86651**    May you find forgiveness for yourself and forgive others.
86652**    May you share freely, never taking more than you give.
86653**
86654*************************************************************************
86655** This file contains C code routines that are called by the parser
86656** to handle SELECT statements in SQLite.
86657*/
86658
86659
86660/*
86661** Delete all the content of a Select structure but do not deallocate
86662** the select structure itself.
86663*/
86664static void clearSelect(sqlite3 *db, Select *p){
86665  sqlite3ExprListDelete(db, p->pEList);
86666  sqlite3SrcListDelete(db, p->pSrc);
86667  sqlite3ExprDelete(db, p->pWhere);
86668  sqlite3ExprListDelete(db, p->pGroupBy);
86669  sqlite3ExprDelete(db, p->pHaving);
86670  sqlite3ExprListDelete(db, p->pOrderBy);
86671  sqlite3SelectDelete(db, p->pPrior);
86672  sqlite3ExprDelete(db, p->pLimit);
86673  sqlite3ExprDelete(db, p->pOffset);
86674}
86675
86676/*
86677** Initialize a SelectDest structure.
86678*/
86679SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
86680  pDest->eDest = (u8)eDest;
86681  pDest->iParm = iParm;
86682  pDest->affinity = 0;
86683  pDest->iMem = 0;
86684  pDest->nMem = 0;
86685}
86686
86687
86688/*
86689** Allocate a new Select structure and return a pointer to that
86690** structure.
86691*/
86692SQLITE_PRIVATE Select *sqlite3SelectNew(
86693  Parse *pParse,        /* Parsing context */
86694  ExprList *pEList,     /* which columns to include in the result */
86695  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
86696  Expr *pWhere,         /* the WHERE clause */
86697  ExprList *pGroupBy,   /* the GROUP BY clause */
86698  Expr *pHaving,        /* the HAVING clause */
86699  ExprList *pOrderBy,   /* the ORDER BY clause */
86700  int isDistinct,       /* true if the DISTINCT keyword is present */
86701  Expr *pLimit,         /* LIMIT value.  NULL means not used */
86702  Expr *pOffset         /* OFFSET value.  NULL means no offset */
86703){
86704  Select *pNew;
86705  Select standin;
86706  sqlite3 *db = pParse->db;
86707  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
86708  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
86709  if( pNew==0 ){
86710    pNew = &standin;
86711    memset(pNew, 0, sizeof(*pNew));
86712  }
86713  if( pEList==0 ){
86714    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
86715  }
86716  pNew->pEList = pEList;
86717  pNew->pSrc = pSrc;
86718  pNew->pWhere = pWhere;
86719  pNew->pGroupBy = pGroupBy;
86720  pNew->pHaving = pHaving;
86721  pNew->pOrderBy = pOrderBy;
86722  pNew->selFlags = isDistinct ? SF_Distinct : 0;
86723  pNew->op = TK_SELECT;
86724  pNew->pLimit = pLimit;
86725  pNew->pOffset = pOffset;
86726  assert( pOffset==0 || pLimit!=0 );
86727  pNew->addrOpenEphm[0] = -1;
86728  pNew->addrOpenEphm[1] = -1;
86729  pNew->addrOpenEphm[2] = -1;
86730  if( db->mallocFailed ) {
86731    clearSelect(db, pNew);
86732    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
86733    pNew = 0;
86734  }
86735  return pNew;
86736}
86737
86738/*
86739** Delete the given Select structure and all of its substructures.
86740*/
86741SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
86742  if( p ){
86743    clearSelect(db, p);
86744    sqlite3DbFree(db, p);
86745  }
86746}
86747
86748/*
86749** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
86750** type of join.  Return an integer constant that expresses that type
86751** in terms of the following bit values:
86752**
86753**     JT_INNER
86754**     JT_CROSS
86755**     JT_OUTER
86756**     JT_NATURAL
86757**     JT_LEFT
86758**     JT_RIGHT
86759**
86760** A full outer join is the combination of JT_LEFT and JT_RIGHT.
86761**
86762** If an illegal or unsupported join type is seen, then still return
86763** a join type, but put an error in the pParse structure.
86764*/
86765SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
86766  int jointype = 0;
86767  Token *apAll[3];
86768  Token *p;
86769                             /*   0123456789 123456789 123456789 123 */
86770  static const char zKeyText[] = "naturaleftouterightfullinnercross";
86771  static const struct {
86772    u8 i;        /* Beginning of keyword text in zKeyText[] */
86773    u8 nChar;    /* Length of the keyword in characters */
86774    u8 code;     /* Join type mask */
86775  } aKeyword[] = {
86776    /* natural */ { 0,  7, JT_NATURAL                },
86777    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
86778    /* outer   */ { 10, 5, JT_OUTER                  },
86779    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
86780    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
86781    /* inner   */ { 23, 5, JT_INNER                  },
86782    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
86783  };
86784  int i, j;
86785  apAll[0] = pA;
86786  apAll[1] = pB;
86787  apAll[2] = pC;
86788  for(i=0; i<3 && apAll[i]; i++){
86789    p = apAll[i];
86790    for(j=0; j<ArraySize(aKeyword); j++){
86791      if( p->n==aKeyword[j].nChar
86792          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
86793        jointype |= aKeyword[j].code;
86794        break;
86795      }
86796    }
86797    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
86798    if( j>=ArraySize(aKeyword) ){
86799      jointype |= JT_ERROR;
86800      break;
86801    }
86802  }
86803  if(
86804     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
86805     (jointype & JT_ERROR)!=0
86806  ){
86807    const char *zSp = " ";
86808    assert( pB!=0 );
86809    if( pC==0 ){ zSp++; }
86810    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
86811       "%T %T%s%T", pA, pB, zSp, pC);
86812    jointype = JT_INNER;
86813  }else if( (jointype & JT_OUTER)!=0
86814         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
86815    sqlite3ErrorMsg(pParse,
86816      "RIGHT and FULL OUTER JOINs are not currently supported");
86817    jointype = JT_INNER;
86818  }
86819  return jointype;
86820}
86821
86822/*
86823** Return the index of a column in a table.  Return -1 if the column
86824** is not contained in the table.
86825*/
86826static int columnIndex(Table *pTab, const char *zCol){
86827  int i;
86828  for(i=0; i<pTab->nCol; i++){
86829    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
86830  }
86831  return -1;
86832}
86833
86834/*
86835** Search the first N tables in pSrc, from left to right, looking for a
86836** table that has a column named zCol.
86837**
86838** When found, set *piTab and *piCol to the table index and column index
86839** of the matching column and return TRUE.
86840**
86841** If not found, return FALSE.
86842*/
86843static int tableAndColumnIndex(
86844  SrcList *pSrc,       /* Array of tables to search */
86845  int N,               /* Number of tables in pSrc->a[] to search */
86846  const char *zCol,    /* Name of the column we are looking for */
86847  int *piTab,          /* Write index of pSrc->a[] here */
86848  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
86849){
86850  int i;               /* For looping over tables in pSrc */
86851  int iCol;            /* Index of column matching zCol */
86852
86853  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
86854  for(i=0; i<N; i++){
86855    iCol = columnIndex(pSrc->a[i].pTab, zCol);
86856    if( iCol>=0 ){
86857      if( piTab ){
86858        *piTab = i;
86859        *piCol = iCol;
86860      }
86861      return 1;
86862    }
86863  }
86864  return 0;
86865}
86866
86867/*
86868** This function is used to add terms implied by JOIN syntax to the
86869** WHERE clause expression of a SELECT statement. The new term, which
86870** is ANDed with the existing WHERE clause, is of the form:
86871**
86872**    (tab1.col1 = tab2.col2)
86873**
86874** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
86875** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
86876** column iColRight of tab2.
86877*/
86878static void addWhereTerm(
86879  Parse *pParse,                  /* Parsing context */
86880  SrcList *pSrc,                  /* List of tables in FROM clause */
86881  int iLeft,                      /* Index of first table to join in pSrc */
86882  int iColLeft,                   /* Index of column in first table */
86883  int iRight,                     /* Index of second table in pSrc */
86884  int iColRight,                  /* Index of column in second table */
86885  int isOuterJoin,                /* True if this is an OUTER join */
86886  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
86887){
86888  sqlite3 *db = pParse->db;
86889  Expr *pE1;
86890  Expr *pE2;
86891  Expr *pEq;
86892
86893  assert( iLeft<iRight );
86894  assert( pSrc->nSrc>iRight );
86895  assert( pSrc->a[iLeft].pTab );
86896  assert( pSrc->a[iRight].pTab );
86897
86898  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
86899  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
86900
86901  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
86902  if( pEq && isOuterJoin ){
86903    ExprSetProperty(pEq, EP_FromJoin);
86904    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
86905    ExprSetIrreducible(pEq);
86906    pEq->iRightJoinTable = (i16)pE2->iTable;
86907  }
86908  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
86909}
86910
86911/*
86912** Set the EP_FromJoin property on all terms of the given expression.
86913** And set the Expr.iRightJoinTable to iTable for every term in the
86914** expression.
86915**
86916** The EP_FromJoin property is used on terms of an expression to tell
86917** the LEFT OUTER JOIN processing logic that this term is part of the
86918** join restriction specified in the ON or USING clause and not a part
86919** of the more general WHERE clause.  These terms are moved over to the
86920** WHERE clause during join processing but we need to remember that they
86921** originated in the ON or USING clause.
86922**
86923** The Expr.iRightJoinTable tells the WHERE clause processing that the
86924** expression depends on table iRightJoinTable even if that table is not
86925** explicitly mentioned in the expression.  That information is needed
86926** for cases like this:
86927**
86928**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
86929**
86930** The where clause needs to defer the handling of the t1.x=5
86931** term until after the t2 loop of the join.  In that way, a
86932** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
86933** defer the handling of t1.x=5, it will be processed immediately
86934** after the t1 loop and rows with t1.x!=5 will never appear in
86935** the output, which is incorrect.
86936*/
86937static void setJoinExpr(Expr *p, int iTable){
86938  while( p ){
86939    ExprSetProperty(p, EP_FromJoin);
86940    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
86941    ExprSetIrreducible(p);
86942    p->iRightJoinTable = (i16)iTable;
86943    setJoinExpr(p->pLeft, iTable);
86944    p = p->pRight;
86945  }
86946}
86947
86948/*
86949** This routine processes the join information for a SELECT statement.
86950** ON and USING clauses are converted into extra terms of the WHERE clause.
86951** NATURAL joins also create extra WHERE clause terms.
86952**
86953** The terms of a FROM clause are contained in the Select.pSrc structure.
86954** The left most table is the first entry in Select.pSrc.  The right-most
86955** table is the last entry.  The join operator is held in the entry to
86956** the left.  Thus entry 0 contains the join operator for the join between
86957** entries 0 and 1.  Any ON or USING clauses associated with the join are
86958** also attached to the left entry.
86959**
86960** This routine returns the number of errors encountered.
86961*/
86962static int sqliteProcessJoin(Parse *pParse, Select *p){
86963  SrcList *pSrc;                  /* All tables in the FROM clause */
86964  int i, j;                       /* Loop counters */
86965  struct SrcList_item *pLeft;     /* Left table being joined */
86966  struct SrcList_item *pRight;    /* Right table being joined */
86967
86968  pSrc = p->pSrc;
86969  pLeft = &pSrc->a[0];
86970  pRight = &pLeft[1];
86971  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
86972    Table *pLeftTab = pLeft->pTab;
86973    Table *pRightTab = pRight->pTab;
86974    int isOuter;
86975
86976    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
86977    isOuter = (pRight->jointype & JT_OUTER)!=0;
86978
86979    /* When the NATURAL keyword is present, add WHERE clause terms for
86980    ** every column that the two tables have in common.
86981    */
86982    if( pRight->jointype & JT_NATURAL ){
86983      if( pRight->pOn || pRight->pUsing ){
86984        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
86985           "an ON or USING clause", 0);
86986        return 1;
86987      }
86988      for(j=0; j<pRightTab->nCol; j++){
86989        char *zName;   /* Name of column in the right table */
86990        int iLeft;     /* Matching left table */
86991        int iLeftCol;  /* Matching column in the left table */
86992
86993        zName = pRightTab->aCol[j].zName;
86994        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
86995          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
86996                       isOuter, &p->pWhere);
86997        }
86998      }
86999    }
87000
87001    /* Disallow both ON and USING clauses in the same join
87002    */
87003    if( pRight->pOn && pRight->pUsing ){
87004      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
87005        "clauses in the same join");
87006      return 1;
87007    }
87008
87009    /* Add the ON clause to the end of the WHERE clause, connected by
87010    ** an AND operator.
87011    */
87012    if( pRight->pOn ){
87013      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
87014      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
87015      pRight->pOn = 0;
87016    }
87017
87018    /* Create extra terms on the WHERE clause for each column named
87019    ** in the USING clause.  Example: If the two tables to be joined are
87020    ** A and B and the USING clause names X, Y, and Z, then add this
87021    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
87022    ** Report an error if any column mentioned in the USING clause is
87023    ** not contained in both tables to be joined.
87024    */
87025    if( pRight->pUsing ){
87026      IdList *pList = pRight->pUsing;
87027      for(j=0; j<pList->nId; j++){
87028        char *zName;     /* Name of the term in the USING clause */
87029        int iLeft;       /* Table on the left with matching column name */
87030        int iLeftCol;    /* Column number of matching column on the left */
87031        int iRightCol;   /* Column number of matching column on the right */
87032
87033        zName = pList->a[j].zName;
87034        iRightCol = columnIndex(pRightTab, zName);
87035        if( iRightCol<0
87036         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
87037        ){
87038          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
87039            "not present in both tables", zName);
87040          return 1;
87041        }
87042        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
87043                     isOuter, &p->pWhere);
87044      }
87045    }
87046  }
87047  return 0;
87048}
87049
87050/*
87051** Insert code into "v" that will push the record on the top of the
87052** stack into the sorter.
87053*/
87054static void pushOntoSorter(
87055  Parse *pParse,         /* Parser context */
87056  ExprList *pOrderBy,    /* The ORDER BY clause */
87057  Select *pSelect,       /* The whole SELECT statement */
87058  int regData            /* Register holding data to be sorted */
87059){
87060  Vdbe *v = pParse->pVdbe;
87061  int nExpr = pOrderBy->nExpr;
87062  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
87063  int regRecord = sqlite3GetTempReg(pParse);
87064  sqlite3ExprCacheClear(pParse);
87065  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
87066  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
87067  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
87068  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
87069  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
87070  sqlite3ReleaseTempReg(pParse, regRecord);
87071  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
87072  if( pSelect->iLimit ){
87073    int addr1, addr2;
87074    int iLimit;
87075    if( pSelect->iOffset ){
87076      iLimit = pSelect->iOffset+1;
87077    }else{
87078      iLimit = pSelect->iLimit;
87079    }
87080    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
87081    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
87082    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
87083    sqlite3VdbeJumpHere(v, addr1);
87084    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
87085    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
87086    sqlite3VdbeJumpHere(v, addr2);
87087    pSelect->iLimit = 0;
87088  }
87089}
87090
87091/*
87092** Add code to implement the OFFSET
87093*/
87094static void codeOffset(
87095  Vdbe *v,          /* Generate code into this VM */
87096  Select *p,        /* The SELECT statement being coded */
87097  int iContinue     /* Jump here to skip the current record */
87098){
87099  if( p->iOffset && iContinue!=0 ){
87100    int addr;
87101    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
87102    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
87103    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
87104    VdbeComment((v, "skip OFFSET records"));
87105    sqlite3VdbeJumpHere(v, addr);
87106  }
87107}
87108
87109/*
87110** Add code that will check to make sure the N registers starting at iMem
87111** form a distinct entry.  iTab is a sorting index that holds previously
87112** seen combinations of the N values.  A new entry is made in iTab
87113** if the current N values are new.
87114**
87115** A jump to addrRepeat is made and the N+1 values are popped from the
87116** stack if the top N elements are not distinct.
87117*/
87118static void codeDistinct(
87119  Parse *pParse,     /* Parsing and code generating context */
87120  int iTab,          /* A sorting index used to test for distinctness */
87121  int addrRepeat,    /* Jump to here if not distinct */
87122  int N,             /* Number of elements */
87123  int iMem           /* First element */
87124){
87125  Vdbe *v;
87126  int r1;
87127
87128  v = pParse->pVdbe;
87129  r1 = sqlite3GetTempReg(pParse);
87130  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
87131  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
87132  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
87133  sqlite3ReleaseTempReg(pParse, r1);
87134}
87135
87136/*
87137** Generate an error message when a SELECT is used within a subexpression
87138** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
87139** column.  We do this in a subroutine because the error occurs in multiple
87140** places.
87141*/
87142static int checkForMultiColumnSelectError(
87143  Parse *pParse,       /* Parse context. */
87144  SelectDest *pDest,   /* Destination of SELECT results */
87145  int nExpr            /* Number of result columns returned by SELECT */
87146){
87147  int eDest = pDest->eDest;
87148  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
87149    sqlite3ErrorMsg(pParse, "only a single result allowed for "
87150       "a SELECT that is part of an expression");
87151    return 1;
87152  }else{
87153    return 0;
87154  }
87155}
87156
87157/*
87158** This routine generates the code for the inside of the inner loop
87159** of a SELECT.
87160**
87161** If srcTab and nColumn are both zero, then the pEList expressions
87162** are evaluated in order to get the data for this row.  If nColumn>0
87163** then data is pulled from srcTab and pEList is used only to get the
87164** datatypes for each column.
87165*/
87166static void selectInnerLoop(
87167  Parse *pParse,          /* The parser context */
87168  Select *p,              /* The complete select statement being coded */
87169  ExprList *pEList,       /* List of values being extracted */
87170  int srcTab,             /* Pull data from this table */
87171  int nColumn,            /* Number of columns in the source table */
87172  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
87173  int distinct,           /* If >=0, make sure results are distinct */
87174  SelectDest *pDest,      /* How to dispose of the results */
87175  int iContinue,          /* Jump here to continue with next row */
87176  int iBreak              /* Jump here to break out of the inner loop */
87177){
87178  Vdbe *v = pParse->pVdbe;
87179  int i;
87180  int hasDistinct;        /* True if the DISTINCT keyword is present */
87181  int regResult;              /* Start of memory holding result set */
87182  int eDest = pDest->eDest;   /* How to dispose of results */
87183  int iParm = pDest->iParm;   /* First argument to disposal method */
87184  int nResultCol;             /* Number of result columns */
87185
87186  assert( v );
87187  if( NEVER(v==0) ) return;
87188  assert( pEList!=0 );
87189  hasDistinct = distinct>=0;
87190  if( pOrderBy==0 && !hasDistinct ){
87191    codeOffset(v, p, iContinue);
87192  }
87193
87194  /* Pull the requested columns.
87195  */
87196  if( nColumn>0 ){
87197    nResultCol = nColumn;
87198  }else{
87199    nResultCol = pEList->nExpr;
87200  }
87201  if( pDest->iMem==0 ){
87202    pDest->iMem = pParse->nMem+1;
87203    pDest->nMem = nResultCol;
87204    pParse->nMem += nResultCol;
87205  }else{
87206    assert( pDest->nMem==nResultCol );
87207  }
87208  regResult = pDest->iMem;
87209  if( nColumn>0 ){
87210    for(i=0; i<nColumn; i++){
87211      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
87212    }
87213  }else if( eDest!=SRT_Exists ){
87214    /* If the destination is an EXISTS(...) expression, the actual
87215    ** values returned by the SELECT are not required.
87216    */
87217    sqlite3ExprCacheClear(pParse);
87218    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
87219  }
87220  nColumn = nResultCol;
87221
87222  /* If the DISTINCT keyword was present on the SELECT statement
87223  ** and this row has been seen before, then do not make this row
87224  ** part of the result.
87225  */
87226  if( hasDistinct ){
87227    assert( pEList!=0 );
87228    assert( pEList->nExpr==nColumn );
87229    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
87230    if( pOrderBy==0 ){
87231      codeOffset(v, p, iContinue);
87232    }
87233  }
87234
87235  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
87236    return;
87237  }
87238
87239  switch( eDest ){
87240    /* In this mode, write each query result to the key of the temporary
87241    ** table iParm.
87242    */
87243#ifndef SQLITE_OMIT_COMPOUND_SELECT
87244    case SRT_Union: {
87245      int r1;
87246      r1 = sqlite3GetTempReg(pParse);
87247      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
87248      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
87249      sqlite3ReleaseTempReg(pParse, r1);
87250      break;
87251    }
87252
87253    /* Construct a record from the query result, but instead of
87254    ** saving that record, use it as a key to delete elements from
87255    ** the temporary table iParm.
87256    */
87257    case SRT_Except: {
87258      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
87259      break;
87260    }
87261#endif
87262
87263    /* Store the result as data using a unique key.
87264    */
87265    case SRT_Table:
87266    case SRT_EphemTab: {
87267      int r1 = sqlite3GetTempReg(pParse);
87268      testcase( eDest==SRT_Table );
87269      testcase( eDest==SRT_EphemTab );
87270      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
87271      if( pOrderBy ){
87272        pushOntoSorter(pParse, pOrderBy, p, r1);
87273      }else{
87274        int r2 = sqlite3GetTempReg(pParse);
87275        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
87276        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
87277        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87278        sqlite3ReleaseTempReg(pParse, r2);
87279      }
87280      sqlite3ReleaseTempReg(pParse, r1);
87281      break;
87282    }
87283
87284#ifndef SQLITE_OMIT_SUBQUERY
87285    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
87286    ** then there should be a single item on the stack.  Write this
87287    ** item into the set table with bogus data.
87288    */
87289    case SRT_Set: {
87290      assert( nColumn==1 );
87291      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
87292      if( pOrderBy ){
87293        /* At first glance you would think we could optimize out the
87294        ** ORDER BY in this case since the order of entries in the set
87295        ** does not matter.  But there might be a LIMIT clause, in which
87296        ** case the order does matter */
87297        pushOntoSorter(pParse, pOrderBy, p, regResult);
87298      }else{
87299        int r1 = sqlite3GetTempReg(pParse);
87300        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
87301        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
87302        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
87303        sqlite3ReleaseTempReg(pParse, r1);
87304      }
87305      break;
87306    }
87307
87308    /* If any row exist in the result set, record that fact and abort.
87309    */
87310    case SRT_Exists: {
87311      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
87312      /* The LIMIT clause will terminate the loop for us */
87313      break;
87314    }
87315
87316    /* If this is a scalar select that is part of an expression, then
87317    ** store the results in the appropriate memory cell and break out
87318    ** of the scan loop.
87319    */
87320    case SRT_Mem: {
87321      assert( nColumn==1 );
87322      if( pOrderBy ){
87323        pushOntoSorter(pParse, pOrderBy, p, regResult);
87324      }else{
87325        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
87326        /* The LIMIT clause will jump out of the loop for us */
87327      }
87328      break;
87329    }
87330#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
87331
87332    /* Send the data to the callback function or to a subroutine.  In the
87333    ** case of a subroutine, the subroutine itself is responsible for
87334    ** popping the data from the stack.
87335    */
87336    case SRT_Coroutine:
87337    case SRT_Output: {
87338      testcase( eDest==SRT_Coroutine );
87339      testcase( eDest==SRT_Output );
87340      if( pOrderBy ){
87341        int r1 = sqlite3GetTempReg(pParse);
87342        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
87343        pushOntoSorter(pParse, pOrderBy, p, r1);
87344        sqlite3ReleaseTempReg(pParse, r1);
87345      }else if( eDest==SRT_Coroutine ){
87346        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
87347      }else{
87348        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
87349        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
87350      }
87351      break;
87352    }
87353
87354#if !defined(SQLITE_OMIT_TRIGGER)
87355    /* Discard the results.  This is used for SELECT statements inside
87356    ** the body of a TRIGGER.  The purpose of such selects is to call
87357    ** user-defined functions that have side effects.  We do not care
87358    ** about the actual results of the select.
87359    */
87360    default: {
87361      assert( eDest==SRT_Discard );
87362      break;
87363    }
87364#endif
87365  }
87366
87367  /* Jump to the end of the loop if the LIMIT is reached.
87368  */
87369  if( p->iLimit ){
87370    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
87371                            ** pushOntoSorter() would have cleared p->iLimit */
87372    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
87373  }
87374}
87375
87376/*
87377** Given an expression list, generate a KeyInfo structure that records
87378** the collating sequence for each expression in that expression list.
87379**
87380** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
87381** KeyInfo structure is appropriate for initializing a virtual index to
87382** implement that clause.  If the ExprList is the result set of a SELECT
87383** then the KeyInfo structure is appropriate for initializing a virtual
87384** index to implement a DISTINCT test.
87385**
87386** Space to hold the KeyInfo structure is obtain from malloc.  The calling
87387** function is responsible for seeing that this structure is eventually
87388** freed.  Add the KeyInfo structure to the P4 field of an opcode using
87389** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
87390*/
87391static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
87392  sqlite3 *db = pParse->db;
87393  int nExpr;
87394  KeyInfo *pInfo;
87395  struct ExprList_item *pItem;
87396  int i;
87397
87398  nExpr = pList->nExpr;
87399  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
87400  if( pInfo ){
87401    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
87402    pInfo->nField = (u16)nExpr;
87403    pInfo->enc = ENC(db);
87404    pInfo->db = db;
87405    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
87406      CollSeq *pColl;
87407      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
87408      if( !pColl ){
87409        pColl = db->pDfltColl;
87410      }
87411      pInfo->aColl[i] = pColl;
87412      pInfo->aSortOrder[i] = pItem->sortOrder;
87413    }
87414  }
87415  return pInfo;
87416}
87417
87418
87419/*
87420** If the inner loop was generated using a non-null pOrderBy argument,
87421** then the results were placed in a sorter.  After the loop is terminated
87422** we need to run the sorter and output the results.  The following
87423** routine generates the code needed to do that.
87424*/
87425static void generateSortTail(
87426  Parse *pParse,    /* Parsing context */
87427  Select *p,        /* The SELECT statement */
87428  Vdbe *v,          /* Generate code into this VDBE */
87429  int nColumn,      /* Number of columns of data */
87430  SelectDest *pDest /* Write the sorted results here */
87431){
87432  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
87433  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
87434  int addr;
87435  int iTab;
87436  int pseudoTab = 0;
87437  ExprList *pOrderBy = p->pOrderBy;
87438
87439  int eDest = pDest->eDest;
87440  int iParm = pDest->iParm;
87441
87442  int regRow;
87443  int regRowid;
87444
87445  iTab = pOrderBy->iECursor;
87446  regRow = sqlite3GetTempReg(pParse);
87447  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
87448    pseudoTab = pParse->nTab++;
87449    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
87450    regRowid = 0;
87451  }else{
87452    regRowid = sqlite3GetTempReg(pParse);
87453  }
87454  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
87455  codeOffset(v, p, addrContinue);
87456  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
87457  switch( eDest ){
87458    case SRT_Table:
87459    case SRT_EphemTab: {
87460      testcase( eDest==SRT_Table );
87461      testcase( eDest==SRT_EphemTab );
87462      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
87463      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
87464      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87465      break;
87466    }
87467#ifndef SQLITE_OMIT_SUBQUERY
87468    case SRT_Set: {
87469      assert( nColumn==1 );
87470      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
87471      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
87472      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
87473      break;
87474    }
87475    case SRT_Mem: {
87476      assert( nColumn==1 );
87477      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
87478      /* The LIMIT clause will terminate the loop for us */
87479      break;
87480    }
87481#endif
87482    default: {
87483      int i;
87484      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
87485      testcase( eDest==SRT_Output );
87486      testcase( eDest==SRT_Coroutine );
87487      for(i=0; i<nColumn; i++){
87488        assert( regRow!=pDest->iMem+i );
87489        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
87490        if( i==0 ){
87491          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
87492        }
87493      }
87494      if( eDest==SRT_Output ){
87495        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
87496        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
87497      }else{
87498        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
87499      }
87500      break;
87501    }
87502  }
87503  sqlite3ReleaseTempReg(pParse, regRow);
87504  sqlite3ReleaseTempReg(pParse, regRowid);
87505
87506  /* LIMIT has been implemented by the pushOntoSorter() routine.
87507  */
87508  assert( p->iLimit==0 );
87509
87510  /* The bottom of the loop
87511  */
87512  sqlite3VdbeResolveLabel(v, addrContinue);
87513  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
87514  sqlite3VdbeResolveLabel(v, addrBreak);
87515  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
87516    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
87517  }
87518}
87519
87520/*
87521** Return a pointer to a string containing the 'declaration type' of the
87522** expression pExpr. The string may be treated as static by the caller.
87523**
87524** The declaration type is the exact datatype definition extracted from the
87525** original CREATE TABLE statement if the expression is a column. The
87526** declaration type for a ROWID field is INTEGER. Exactly when an expression
87527** is considered a column can be complex in the presence of subqueries. The
87528** result-set expression in all of the following SELECT statements is
87529** considered a column by this function.
87530**
87531**   SELECT col FROM tbl;
87532**   SELECT (SELECT col FROM tbl;
87533**   SELECT (SELECT col FROM tbl);
87534**   SELECT abc FROM (SELECT col AS abc FROM tbl);
87535**
87536** The declaration type for any expression other than a column is NULL.
87537*/
87538static const char *columnType(
87539  NameContext *pNC,
87540  Expr *pExpr,
87541  const char **pzOriginDb,
87542  const char **pzOriginTab,
87543  const char **pzOriginCol
87544){
87545  char const *zType = 0;
87546  char const *zOriginDb = 0;
87547  char const *zOriginTab = 0;
87548  char const *zOriginCol = 0;
87549  int j;
87550  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
87551
87552  switch( pExpr->op ){
87553    case TK_AGG_COLUMN:
87554    case TK_COLUMN: {
87555      /* The expression is a column. Locate the table the column is being
87556      ** extracted from in NameContext.pSrcList. This table may be real
87557      ** database table or a subquery.
87558      */
87559      Table *pTab = 0;            /* Table structure column is extracted from */
87560      Select *pS = 0;             /* Select the column is extracted from */
87561      int iCol = pExpr->iColumn;  /* Index of column in pTab */
87562      testcase( pExpr->op==TK_AGG_COLUMN );
87563      testcase( pExpr->op==TK_COLUMN );
87564      while( pNC && !pTab ){
87565        SrcList *pTabList = pNC->pSrcList;
87566        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
87567        if( j<pTabList->nSrc ){
87568          pTab = pTabList->a[j].pTab;
87569          pS = pTabList->a[j].pSelect;
87570        }else{
87571          pNC = pNC->pNext;
87572        }
87573      }
87574
87575      if( pTab==0 ){
87576        /* At one time, code such as "SELECT new.x" within a trigger would
87577        ** cause this condition to run.  Since then, we have restructured how
87578        ** trigger code is generated and so this condition is no longer
87579        ** possible. However, it can still be true for statements like
87580        ** the following:
87581        **
87582        **   CREATE TABLE t1(col INTEGER);
87583        **   SELECT (SELECT t1.col) FROM FROM t1;
87584        **
87585        ** when columnType() is called on the expression "t1.col" in the
87586        ** sub-select. In this case, set the column type to NULL, even
87587        ** though it should really be "INTEGER".
87588        **
87589        ** This is not a problem, as the column type of "t1.col" is never
87590        ** used. When columnType() is called on the expression
87591        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
87592        ** branch below.  */
87593        break;
87594      }
87595
87596      assert( pTab && pExpr->pTab==pTab );
87597      if( pS ){
87598        /* The "table" is actually a sub-select or a view in the FROM clause
87599        ** of the SELECT statement. Return the declaration type and origin
87600        ** data for the result-set column of the sub-select.
87601        */
87602        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
87603          /* If iCol is less than zero, then the expression requests the
87604          ** rowid of the sub-select or view. This expression is legal (see
87605          ** test case misc2.2.2) - it always evaluates to NULL.
87606          */
87607          NameContext sNC;
87608          Expr *p = pS->pEList->a[iCol].pExpr;
87609          sNC.pSrcList = pS->pSrc;
87610          sNC.pNext = pNC;
87611          sNC.pParse = pNC->pParse;
87612          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
87613        }
87614      }else if( ALWAYS(pTab->pSchema) ){
87615        /* A real table */
87616        assert( !pS );
87617        if( iCol<0 ) iCol = pTab->iPKey;
87618        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
87619        if( iCol<0 ){
87620          zType = "INTEGER";
87621          zOriginCol = "rowid";
87622        }else{
87623          zType = pTab->aCol[iCol].zType;
87624          zOriginCol = pTab->aCol[iCol].zName;
87625        }
87626        zOriginTab = pTab->zName;
87627        if( pNC->pParse ){
87628          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
87629          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
87630        }
87631      }
87632      break;
87633    }
87634#ifndef SQLITE_OMIT_SUBQUERY
87635    case TK_SELECT: {
87636      /* The expression is a sub-select. Return the declaration type and
87637      ** origin info for the single column in the result set of the SELECT
87638      ** statement.
87639      */
87640      NameContext sNC;
87641      Select *pS = pExpr->x.pSelect;
87642      Expr *p = pS->pEList->a[0].pExpr;
87643      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
87644      sNC.pSrcList = pS->pSrc;
87645      sNC.pNext = pNC;
87646      sNC.pParse = pNC->pParse;
87647      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
87648      break;
87649    }
87650#endif
87651  }
87652
87653  if( pzOriginDb ){
87654    assert( pzOriginTab && pzOriginCol );
87655    *pzOriginDb = zOriginDb;
87656    *pzOriginTab = zOriginTab;
87657    *pzOriginCol = zOriginCol;
87658  }
87659  return zType;
87660}
87661
87662/*
87663** Generate code that will tell the VDBE the declaration types of columns
87664** in the result set.
87665*/
87666static void generateColumnTypes(
87667  Parse *pParse,      /* Parser context */
87668  SrcList *pTabList,  /* List of tables */
87669  ExprList *pEList    /* Expressions defining the result set */
87670){
87671#ifndef SQLITE_OMIT_DECLTYPE
87672  Vdbe *v = pParse->pVdbe;
87673  int i;
87674  NameContext sNC;
87675  sNC.pSrcList = pTabList;
87676  sNC.pParse = pParse;
87677  for(i=0; i<pEList->nExpr; i++){
87678    Expr *p = pEList->a[i].pExpr;
87679    const char *zType;
87680#ifdef SQLITE_ENABLE_COLUMN_METADATA
87681    const char *zOrigDb = 0;
87682    const char *zOrigTab = 0;
87683    const char *zOrigCol = 0;
87684    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
87685
87686    /* The vdbe must make its own copy of the column-type and other
87687    ** column specific strings, in case the schema is reset before this
87688    ** virtual machine is deleted.
87689    */
87690    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
87691    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
87692    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
87693#else
87694    zType = columnType(&sNC, p, 0, 0, 0);
87695#endif
87696    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
87697  }
87698#endif /* SQLITE_OMIT_DECLTYPE */
87699}
87700
87701/*
87702** Generate code that will tell the VDBE the names of columns
87703** in the result set.  This information is used to provide the
87704** azCol[] values in the callback.
87705*/
87706static void generateColumnNames(
87707  Parse *pParse,      /* Parser context */
87708  SrcList *pTabList,  /* List of tables */
87709  ExprList *pEList    /* Expressions defining the result set */
87710){
87711  Vdbe *v = pParse->pVdbe;
87712  int i, j;
87713  sqlite3 *db = pParse->db;
87714  int fullNames, shortNames;
87715
87716#ifndef SQLITE_OMIT_EXPLAIN
87717  /* If this is an EXPLAIN, skip this step */
87718  if( pParse->explain ){
87719    return;
87720  }
87721#endif
87722
87723  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
87724  pParse->colNamesSet = 1;
87725  fullNames = (db->flags & SQLITE_FullColNames)!=0;
87726  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
87727  sqlite3VdbeSetNumCols(v, pEList->nExpr);
87728  for(i=0; i<pEList->nExpr; i++){
87729    Expr *p;
87730    p = pEList->a[i].pExpr;
87731    if( NEVER(p==0) ) continue;
87732    if( pEList->a[i].zName ){
87733      char *zName = pEList->a[i].zName;
87734      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
87735    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
87736      Table *pTab;
87737      char *zCol;
87738      int iCol = p->iColumn;
87739      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
87740        if( pTabList->a[j].iCursor==p->iTable ) break;
87741      }
87742      assert( j<pTabList->nSrc );
87743      pTab = pTabList->a[j].pTab;
87744      if( iCol<0 ) iCol = pTab->iPKey;
87745      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
87746      if( iCol<0 ){
87747        zCol = "rowid";
87748      }else{
87749        zCol = pTab->aCol[iCol].zName;
87750      }
87751      if( !shortNames && !fullNames ){
87752        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
87753            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
87754      }else if( fullNames ){
87755        char *zName = 0;
87756        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
87757        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
87758      }else{
87759        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
87760      }
87761    }else{
87762      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
87763          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
87764    }
87765  }
87766  generateColumnTypes(pParse, pTabList, pEList);
87767}
87768
87769#ifndef SQLITE_OMIT_COMPOUND_SELECT
87770/*
87771** Name of the connection operator, used for error messages.
87772*/
87773static const char *selectOpName(int id){
87774  char *z;
87775  switch( id ){
87776    case TK_ALL:       z = "UNION ALL";   break;
87777    case TK_INTERSECT: z = "INTERSECT";   break;
87778    case TK_EXCEPT:    z = "EXCEPT";      break;
87779    default:           z = "UNION";       break;
87780  }
87781  return z;
87782}
87783#endif /* SQLITE_OMIT_COMPOUND_SELECT */
87784
87785/*
87786** Given a an expression list (which is really the list of expressions
87787** that form the result set of a SELECT statement) compute appropriate
87788** column names for a table that would hold the expression list.
87789**
87790** All column names will be unique.
87791**
87792** Only the column names are computed.  Column.zType, Column.zColl,
87793** and other fields of Column are zeroed.
87794**
87795** Return SQLITE_OK on success.  If a memory allocation error occurs,
87796** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
87797*/
87798static int selectColumnsFromExprList(
87799  Parse *pParse,          /* Parsing context */
87800  ExprList *pEList,       /* Expr list from which to derive column names */
87801  int *pnCol,             /* Write the number of columns here */
87802  Column **paCol          /* Write the new column list here */
87803){
87804  sqlite3 *db = pParse->db;   /* Database connection */
87805  int i, j;                   /* Loop counters */
87806  int cnt;                    /* Index added to make the name unique */
87807  Column *aCol, *pCol;        /* For looping over result columns */
87808  int nCol;                   /* Number of columns in the result set */
87809  Expr *p;                    /* Expression for a single result column */
87810  char *zName;                /* Column name */
87811  int nName;                  /* Size of name in zName[] */
87812
87813  *pnCol = nCol = pEList->nExpr;
87814  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
87815  if( aCol==0 ) return SQLITE_NOMEM;
87816  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
87817    /* Get an appropriate name for the column
87818    */
87819    p = pEList->a[i].pExpr;
87820    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
87821               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
87822    if( (zName = pEList->a[i].zName)!=0 ){
87823      /* If the column contains an "AS <name>" phrase, use <name> as the name */
87824      zName = sqlite3DbStrDup(db, zName);
87825    }else{
87826      Expr *pColExpr = p;  /* The expression that is the result column name */
87827      Table *pTab;         /* Table associated with this expression */
87828      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
87829      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
87830        /* For columns use the column name name */
87831        int iCol = pColExpr->iColumn;
87832        pTab = pColExpr->pTab;
87833        if( iCol<0 ) iCol = pTab->iPKey;
87834        zName = sqlite3MPrintf(db, "%s",
87835                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
87836      }else if( pColExpr->op==TK_ID ){
87837        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
87838        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
87839      }else{
87840        /* Use the original text of the column expression as its name */
87841        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
87842      }
87843    }
87844    if( db->mallocFailed ){
87845      sqlite3DbFree(db, zName);
87846      break;
87847    }
87848
87849    /* Make sure the column name is unique.  If the name is not unique,
87850    ** append a integer to the name so that it becomes unique.
87851    */
87852    nName = sqlite3Strlen30(zName);
87853    for(j=cnt=0; j<i; j++){
87854      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
87855        char *zNewName;
87856        zName[nName] = 0;
87857        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
87858        sqlite3DbFree(db, zName);
87859        zName = zNewName;
87860        j = -1;
87861        if( zName==0 ) break;
87862      }
87863    }
87864    pCol->zName = zName;
87865  }
87866  if( db->mallocFailed ){
87867    for(j=0; j<i; j++){
87868      sqlite3DbFree(db, aCol[j].zName);
87869    }
87870    sqlite3DbFree(db, aCol);
87871    *paCol = 0;
87872    *pnCol = 0;
87873    return SQLITE_NOMEM;
87874  }
87875  return SQLITE_OK;
87876}
87877
87878/*
87879** Add type and collation information to a column list based on
87880** a SELECT statement.
87881**
87882** The column list presumably came from selectColumnNamesFromExprList().
87883** The column list has only names, not types or collations.  This
87884** routine goes through and adds the types and collations.
87885**
87886** This routine requires that all identifiers in the SELECT
87887** statement be resolved.
87888*/
87889static void selectAddColumnTypeAndCollation(
87890  Parse *pParse,        /* Parsing contexts */
87891  int nCol,             /* Number of columns */
87892  Column *aCol,         /* List of columns */
87893  Select *pSelect       /* SELECT used to determine types and collations */
87894){
87895  sqlite3 *db = pParse->db;
87896  NameContext sNC;
87897  Column *pCol;
87898  CollSeq *pColl;
87899  int i;
87900  Expr *p;
87901  struct ExprList_item *a;
87902
87903  assert( pSelect!=0 );
87904  assert( (pSelect->selFlags & SF_Resolved)!=0 );
87905  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
87906  if( db->mallocFailed ) return;
87907  memset(&sNC, 0, sizeof(sNC));
87908  sNC.pSrcList = pSelect->pSrc;
87909  a = pSelect->pEList->a;
87910  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
87911    p = a[i].pExpr;
87912    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
87913    pCol->affinity = sqlite3ExprAffinity(p);
87914    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
87915    pColl = sqlite3ExprCollSeq(pParse, p);
87916    if( pColl ){
87917      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
87918    }
87919  }
87920}
87921
87922/*
87923** Given a SELECT statement, generate a Table structure that describes
87924** the result set of that SELECT.
87925*/
87926SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
87927  Table *pTab;
87928  sqlite3 *db = pParse->db;
87929  int savedFlags;
87930
87931  savedFlags = db->flags;
87932  db->flags &= ~SQLITE_FullColNames;
87933  db->flags |= SQLITE_ShortColNames;
87934  sqlite3SelectPrep(pParse, pSelect, 0);
87935  if( pParse->nErr ) return 0;
87936  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
87937  db->flags = savedFlags;
87938  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
87939  if( pTab==0 ){
87940    return 0;
87941  }
87942  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
87943  ** is disabled */
87944  assert( db->lookaside.bEnabled==0 );
87945  pTab->nRef = 1;
87946  pTab->zName = 0;
87947  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
87948  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
87949  pTab->iPKey = -1;
87950  if( db->mallocFailed ){
87951    sqlite3DeleteTable(db, pTab);
87952    return 0;
87953  }
87954  return pTab;
87955}
87956
87957/*
87958** Get a VDBE for the given parser context.  Create a new one if necessary.
87959** If an error occurs, return NULL and leave a message in pParse.
87960*/
87961SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
87962  Vdbe *v = pParse->pVdbe;
87963  if( v==0 ){
87964    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
87965#ifndef SQLITE_OMIT_TRACE
87966    if( v ){
87967      sqlite3VdbeAddOp0(v, OP_Trace);
87968    }
87969#endif
87970  }
87971  return v;
87972}
87973
87974
87975/*
87976** Compute the iLimit and iOffset fields of the SELECT based on the
87977** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
87978** that appear in the original SQL statement after the LIMIT and OFFSET
87979** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
87980** are the integer memory register numbers for counters used to compute
87981** the limit and offset.  If there is no limit and/or offset, then
87982** iLimit and iOffset are negative.
87983**
87984** This routine changes the values of iLimit and iOffset only if
87985** a limit or offset is defined by pLimit and pOffset.  iLimit and
87986** iOffset should have been preset to appropriate default values
87987** (usually but not always -1) prior to calling this routine.
87988** Only if pLimit!=0 or pOffset!=0 do the limit registers get
87989** redefined.  The UNION ALL operator uses this property to force
87990** the reuse of the same limit and offset registers across multiple
87991** SELECT statements.
87992*/
87993static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
87994  Vdbe *v = 0;
87995  int iLimit = 0;
87996  int iOffset;
87997  int addr1, n;
87998  if( p->iLimit ) return;
87999
88000  /*
88001  ** "LIMIT -1" always shows all rows.  There is some
88002  ** contraversy about what the correct behavior should be.
88003  ** The current implementation interprets "LIMIT 0" to mean
88004  ** no rows.
88005  */
88006  sqlite3ExprCacheClear(pParse);
88007  assert( p->pOffset==0 || p->pLimit!=0 );
88008  if( p->pLimit ){
88009    p->iLimit = iLimit = ++pParse->nMem;
88010    v = sqlite3GetVdbe(pParse);
88011    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
88012    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
88013      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
88014      VdbeComment((v, "LIMIT counter"));
88015      if( n==0 ){
88016        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
88017      }
88018    }else{
88019      sqlite3ExprCode(pParse, p->pLimit, iLimit);
88020      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
88021      VdbeComment((v, "LIMIT counter"));
88022      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
88023    }
88024    if( p->pOffset ){
88025      p->iOffset = iOffset = ++pParse->nMem;
88026      pParse->nMem++;   /* Allocate an extra register for limit+offset */
88027      sqlite3ExprCode(pParse, p->pOffset, iOffset);
88028      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
88029      VdbeComment((v, "OFFSET counter"));
88030      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
88031      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
88032      sqlite3VdbeJumpHere(v, addr1);
88033      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
88034      VdbeComment((v, "LIMIT+OFFSET"));
88035      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
88036      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
88037      sqlite3VdbeJumpHere(v, addr1);
88038    }
88039  }
88040}
88041
88042#ifndef SQLITE_OMIT_COMPOUND_SELECT
88043/*
88044** Return the appropriate collating sequence for the iCol-th column of
88045** the result set for the compound-select statement "p".  Return NULL if
88046** the column has no default collating sequence.
88047**
88048** The collating sequence for the compound select is taken from the
88049** left-most term of the select that has a collating sequence.
88050*/
88051static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
88052  CollSeq *pRet;
88053  if( p->pPrior ){
88054    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
88055  }else{
88056    pRet = 0;
88057  }
88058  assert( iCol>=0 );
88059  if( pRet==0 && iCol<p->pEList->nExpr ){
88060    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
88061  }
88062  return pRet;
88063}
88064#endif /* SQLITE_OMIT_COMPOUND_SELECT */
88065
88066/* Forward reference */
88067static int multiSelectOrderBy(
88068  Parse *pParse,        /* Parsing context */
88069  Select *p,            /* The right-most of SELECTs to be coded */
88070  SelectDest *pDest     /* What to do with query results */
88071);
88072
88073
88074#ifndef SQLITE_OMIT_COMPOUND_SELECT
88075/*
88076** This routine is called to process a compound query form from
88077** two or more separate queries using UNION, UNION ALL, EXCEPT, or
88078** INTERSECT
88079**
88080** "p" points to the right-most of the two queries.  the query on the
88081** left is p->pPrior.  The left query could also be a compound query
88082** in which case this routine will be called recursively.
88083**
88084** The results of the total query are to be written into a destination
88085** of type eDest with parameter iParm.
88086**
88087** Example 1:  Consider a three-way compound SQL statement.
88088**
88089**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
88090**
88091** This statement is parsed up as follows:
88092**
88093**     SELECT c FROM t3
88094**      |
88095**      `----->  SELECT b FROM t2
88096**                |
88097**                `------>  SELECT a FROM t1
88098**
88099** The arrows in the diagram above represent the Select.pPrior pointer.
88100** So if this routine is called with p equal to the t3 query, then
88101** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
88102**
88103** Notice that because of the way SQLite parses compound SELECTs, the
88104** individual selects always group from left to right.
88105*/
88106static int multiSelect(
88107  Parse *pParse,        /* Parsing context */
88108  Select *p,            /* The right-most of SELECTs to be coded */
88109  SelectDest *pDest     /* What to do with query results */
88110){
88111  int rc = SQLITE_OK;   /* Success code from a subroutine */
88112  Select *pPrior;       /* Another SELECT immediately to our left */
88113  Vdbe *v;              /* Generate code to this VDBE */
88114  SelectDest dest;      /* Alternative data destination */
88115  Select *pDelete = 0;  /* Chain of simple selects to delete */
88116  sqlite3 *db;          /* Database connection */
88117
88118  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
88119  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
88120  */
88121  assert( p && p->pPrior );  /* Calling function guarantees this much */
88122  db = pParse->db;
88123  pPrior = p->pPrior;
88124  assert( pPrior->pRightmost!=pPrior );
88125  assert( pPrior->pRightmost==p->pRightmost );
88126  dest = *pDest;
88127  if( pPrior->pOrderBy ){
88128    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
88129      selectOpName(p->op));
88130    rc = 1;
88131    goto multi_select_end;
88132  }
88133  if( pPrior->pLimit ){
88134    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
88135      selectOpName(p->op));
88136    rc = 1;
88137    goto multi_select_end;
88138  }
88139
88140  v = sqlite3GetVdbe(pParse);
88141  assert( v!=0 );  /* The VDBE already created by calling function */
88142
88143  /* Create the destination temporary table if necessary
88144  */
88145  if( dest.eDest==SRT_EphemTab ){
88146    assert( p->pEList );
88147    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
88148    dest.eDest = SRT_Table;
88149  }
88150
88151  /* Make sure all SELECTs in the statement have the same number of elements
88152  ** in their result sets.
88153  */
88154  assert( p->pEList && pPrior->pEList );
88155  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
88156    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
88157      " do not have the same number of result columns", selectOpName(p->op));
88158    rc = 1;
88159    goto multi_select_end;
88160  }
88161
88162  /* Compound SELECTs that have an ORDER BY clause are handled separately.
88163  */
88164  if( p->pOrderBy ){
88165    return multiSelectOrderBy(pParse, p, pDest);
88166  }
88167
88168  /* Generate code for the left and right SELECT statements.
88169  */
88170  switch( p->op ){
88171    case TK_ALL: {
88172      int addr = 0;
88173      assert( !pPrior->pLimit );
88174      pPrior->pLimit = p->pLimit;
88175      pPrior->pOffset = p->pOffset;
88176      rc = sqlite3Select(pParse, pPrior, &dest);
88177      p->pLimit = 0;
88178      p->pOffset = 0;
88179      if( rc ){
88180        goto multi_select_end;
88181      }
88182      p->pPrior = 0;
88183      p->iLimit = pPrior->iLimit;
88184      p->iOffset = pPrior->iOffset;
88185      if( p->iLimit ){
88186        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
88187        VdbeComment((v, "Jump ahead if LIMIT reached"));
88188      }
88189      rc = sqlite3Select(pParse, p, &dest);
88190      testcase( rc!=SQLITE_OK );
88191      pDelete = p->pPrior;
88192      p->pPrior = pPrior;
88193      if( addr ){
88194        sqlite3VdbeJumpHere(v, addr);
88195      }
88196      break;
88197    }
88198    case TK_EXCEPT:
88199    case TK_UNION: {
88200      int unionTab;    /* Cursor number of the temporary table holding result */
88201      u8 op = 0;       /* One of the SRT_ operations to apply to self */
88202      int priorOp;     /* The SRT_ operation to apply to prior selects */
88203      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
88204      int addr;
88205      SelectDest uniondest;
88206
88207      testcase( p->op==TK_EXCEPT );
88208      testcase( p->op==TK_UNION );
88209      priorOp = SRT_Union;
88210      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
88211        /* We can reuse a temporary table generated by a SELECT to our
88212        ** right.
88213        */
88214        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
88215                                     ** of a 3-way or more compound */
88216        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
88217        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
88218        unionTab = dest.iParm;
88219      }else{
88220        /* We will need to create our own temporary table to hold the
88221        ** intermediate results.
88222        */
88223        unionTab = pParse->nTab++;
88224        assert( p->pOrderBy==0 );
88225        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
88226        assert( p->addrOpenEphm[0] == -1 );
88227        p->addrOpenEphm[0] = addr;
88228        p->pRightmost->selFlags |= SF_UsesEphemeral;
88229        assert( p->pEList );
88230      }
88231
88232      /* Code the SELECT statements to our left
88233      */
88234      assert( !pPrior->pOrderBy );
88235      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
88236      rc = sqlite3Select(pParse, pPrior, &uniondest);
88237      if( rc ){
88238        goto multi_select_end;
88239      }
88240
88241      /* Code the current SELECT statement
88242      */
88243      if( p->op==TK_EXCEPT ){
88244        op = SRT_Except;
88245      }else{
88246        assert( p->op==TK_UNION );
88247        op = SRT_Union;
88248      }
88249      p->pPrior = 0;
88250      pLimit = p->pLimit;
88251      p->pLimit = 0;
88252      pOffset = p->pOffset;
88253      p->pOffset = 0;
88254      uniondest.eDest = op;
88255      rc = sqlite3Select(pParse, p, &uniondest);
88256      testcase( rc!=SQLITE_OK );
88257      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
88258      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
88259      sqlite3ExprListDelete(db, p->pOrderBy);
88260      pDelete = p->pPrior;
88261      p->pPrior = pPrior;
88262      p->pOrderBy = 0;
88263      sqlite3ExprDelete(db, p->pLimit);
88264      p->pLimit = pLimit;
88265      p->pOffset = pOffset;
88266      p->iLimit = 0;
88267      p->iOffset = 0;
88268
88269      /* Convert the data in the temporary table into whatever form
88270      ** it is that we currently need.
88271      */
88272      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
88273      if( dest.eDest!=priorOp ){
88274        int iCont, iBreak, iStart;
88275        assert( p->pEList );
88276        if( dest.eDest==SRT_Output ){
88277          Select *pFirst = p;
88278          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
88279          generateColumnNames(pParse, 0, pFirst->pEList);
88280        }
88281        iBreak = sqlite3VdbeMakeLabel(v);
88282        iCont = sqlite3VdbeMakeLabel(v);
88283        computeLimitRegisters(pParse, p, iBreak);
88284        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
88285        iStart = sqlite3VdbeCurrentAddr(v);
88286        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
88287                        0, -1, &dest, iCont, iBreak);
88288        sqlite3VdbeResolveLabel(v, iCont);
88289        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
88290        sqlite3VdbeResolveLabel(v, iBreak);
88291        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
88292      }
88293      break;
88294    }
88295    default: assert( p->op==TK_INTERSECT ); {
88296      int tab1, tab2;
88297      int iCont, iBreak, iStart;
88298      Expr *pLimit, *pOffset;
88299      int addr;
88300      SelectDest intersectdest;
88301      int r1;
88302
88303      /* INTERSECT is different from the others since it requires
88304      ** two temporary tables.  Hence it has its own case.  Begin
88305      ** by allocating the tables we will need.
88306      */
88307      tab1 = pParse->nTab++;
88308      tab2 = pParse->nTab++;
88309      assert( p->pOrderBy==0 );
88310
88311      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
88312      assert( p->addrOpenEphm[0] == -1 );
88313      p->addrOpenEphm[0] = addr;
88314      p->pRightmost->selFlags |= SF_UsesEphemeral;
88315      assert( p->pEList );
88316
88317      /* Code the SELECTs to our left into temporary table "tab1".
88318      */
88319      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
88320      rc = sqlite3Select(pParse, pPrior, &intersectdest);
88321      if( rc ){
88322        goto multi_select_end;
88323      }
88324
88325      /* Code the current SELECT into temporary table "tab2"
88326      */
88327      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
88328      assert( p->addrOpenEphm[1] == -1 );
88329      p->addrOpenEphm[1] = addr;
88330      p->pPrior = 0;
88331      pLimit = p->pLimit;
88332      p->pLimit = 0;
88333      pOffset = p->pOffset;
88334      p->pOffset = 0;
88335      intersectdest.iParm = tab2;
88336      rc = sqlite3Select(pParse, p, &intersectdest);
88337      testcase( rc!=SQLITE_OK );
88338      pDelete = p->pPrior;
88339      p->pPrior = pPrior;
88340      sqlite3ExprDelete(db, p->pLimit);
88341      p->pLimit = pLimit;
88342      p->pOffset = pOffset;
88343
88344      /* Generate code to take the intersection of the two temporary
88345      ** tables.
88346      */
88347      assert( p->pEList );
88348      if( dest.eDest==SRT_Output ){
88349        Select *pFirst = p;
88350        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
88351        generateColumnNames(pParse, 0, pFirst->pEList);
88352      }
88353      iBreak = sqlite3VdbeMakeLabel(v);
88354      iCont = sqlite3VdbeMakeLabel(v);
88355      computeLimitRegisters(pParse, p, iBreak);
88356      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
88357      r1 = sqlite3GetTempReg(pParse);
88358      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
88359      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
88360      sqlite3ReleaseTempReg(pParse, r1);
88361      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
88362                      0, -1, &dest, iCont, iBreak);
88363      sqlite3VdbeResolveLabel(v, iCont);
88364      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
88365      sqlite3VdbeResolveLabel(v, iBreak);
88366      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
88367      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
88368      break;
88369    }
88370  }
88371
88372  /* Compute collating sequences used by
88373  ** temporary tables needed to implement the compound select.
88374  ** Attach the KeyInfo structure to all temporary tables.
88375  **
88376  ** This section is run by the right-most SELECT statement only.
88377  ** SELECT statements to the left always skip this part.  The right-most
88378  ** SELECT might also skip this part if it has no ORDER BY clause and
88379  ** no temp tables are required.
88380  */
88381  if( p->selFlags & SF_UsesEphemeral ){
88382    int i;                        /* Loop counter */
88383    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
88384    Select *pLoop;                /* For looping through SELECT statements */
88385    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
88386    int nCol;                     /* Number of columns in result set */
88387
88388    assert( p->pRightmost==p );
88389    nCol = p->pEList->nExpr;
88390    pKeyInfo = sqlite3DbMallocZero(db,
88391                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
88392    if( !pKeyInfo ){
88393      rc = SQLITE_NOMEM;
88394      goto multi_select_end;
88395    }
88396
88397    pKeyInfo->enc = ENC(db);
88398    pKeyInfo->nField = (u16)nCol;
88399
88400    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
88401      *apColl = multiSelectCollSeq(pParse, p, i);
88402      if( 0==*apColl ){
88403        *apColl = db->pDfltColl;
88404      }
88405    }
88406
88407    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
88408      for(i=0; i<2; i++){
88409        int addr = pLoop->addrOpenEphm[i];
88410        if( addr<0 ){
88411          /* If [0] is unused then [1] is also unused.  So we can
88412          ** always safely abort as soon as the first unused slot is found */
88413          assert( pLoop->addrOpenEphm[1]<0 );
88414          break;
88415        }
88416        sqlite3VdbeChangeP2(v, addr, nCol);
88417        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
88418        pLoop->addrOpenEphm[i] = -1;
88419      }
88420    }
88421    sqlite3DbFree(db, pKeyInfo);
88422  }
88423
88424multi_select_end:
88425  pDest->iMem = dest.iMem;
88426  pDest->nMem = dest.nMem;
88427  sqlite3SelectDelete(db, pDelete);
88428  return rc;
88429}
88430#endif /* SQLITE_OMIT_COMPOUND_SELECT */
88431
88432/*
88433** Code an output subroutine for a coroutine implementation of a
88434** SELECT statment.
88435**
88436** The data to be output is contained in pIn->iMem.  There are
88437** pIn->nMem columns to be output.  pDest is where the output should
88438** be sent.
88439**
88440** regReturn is the number of the register holding the subroutine
88441** return address.
88442**
88443** If regPrev>0 then it is the first register in a vector that
88444** records the previous output.  mem[regPrev] is a flag that is false
88445** if there has been no previous output.  If regPrev>0 then code is
88446** generated to suppress duplicates.  pKeyInfo is used for comparing
88447** keys.
88448**
88449** If the LIMIT found in p->iLimit is reached, jump immediately to
88450** iBreak.
88451*/
88452static int generateOutputSubroutine(
88453  Parse *pParse,          /* Parsing context */
88454  Select *p,              /* The SELECT statement */
88455  SelectDest *pIn,        /* Coroutine supplying data */
88456  SelectDest *pDest,      /* Where to send the data */
88457  int regReturn,          /* The return address register */
88458  int regPrev,            /* Previous result register.  No uniqueness if 0 */
88459  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
88460  int p4type,             /* The p4 type for pKeyInfo */
88461  int iBreak              /* Jump here if we hit the LIMIT */
88462){
88463  Vdbe *v = pParse->pVdbe;
88464  int iContinue;
88465  int addr;
88466
88467  addr = sqlite3VdbeCurrentAddr(v);
88468  iContinue = sqlite3VdbeMakeLabel(v);
88469
88470  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
88471  */
88472  if( regPrev ){
88473    int j1, j2;
88474    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
88475    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
88476                              (char*)pKeyInfo, p4type);
88477    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
88478    sqlite3VdbeJumpHere(v, j1);
88479    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
88480    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
88481  }
88482  if( pParse->db->mallocFailed ) return 0;
88483
88484  /* Suppress the the first OFFSET entries if there is an OFFSET clause
88485  */
88486  codeOffset(v, p, iContinue);
88487
88488  switch( pDest->eDest ){
88489    /* Store the result as data using a unique key.
88490    */
88491    case SRT_Table:
88492    case SRT_EphemTab: {
88493      int r1 = sqlite3GetTempReg(pParse);
88494      int r2 = sqlite3GetTempReg(pParse);
88495      testcase( pDest->eDest==SRT_Table );
88496      testcase( pDest->eDest==SRT_EphemTab );
88497      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
88498      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
88499      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
88500      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88501      sqlite3ReleaseTempReg(pParse, r2);
88502      sqlite3ReleaseTempReg(pParse, r1);
88503      break;
88504    }
88505
88506#ifndef SQLITE_OMIT_SUBQUERY
88507    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
88508    ** then there should be a single item on the stack.  Write this
88509    ** item into the set table with bogus data.
88510    */
88511    case SRT_Set: {
88512      int r1;
88513      assert( pIn->nMem==1 );
88514      p->affinity =
88515         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
88516      r1 = sqlite3GetTempReg(pParse);
88517      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
88518      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
88519      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
88520      sqlite3ReleaseTempReg(pParse, r1);
88521      break;
88522    }
88523
88524#if 0  /* Never occurs on an ORDER BY query */
88525    /* If any row exist in the result set, record that fact and abort.
88526    */
88527    case SRT_Exists: {
88528      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
88529      /* The LIMIT clause will terminate the loop for us */
88530      break;
88531    }
88532#endif
88533
88534    /* If this is a scalar select that is part of an expression, then
88535    ** store the results in the appropriate memory cell and break out
88536    ** of the scan loop.
88537    */
88538    case SRT_Mem: {
88539      assert( pIn->nMem==1 );
88540      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
88541      /* The LIMIT clause will jump out of the loop for us */
88542      break;
88543    }
88544#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
88545
88546    /* The results are stored in a sequence of registers
88547    ** starting at pDest->iMem.  Then the co-routine yields.
88548    */
88549    case SRT_Coroutine: {
88550      if( pDest->iMem==0 ){
88551        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
88552        pDest->nMem = pIn->nMem;
88553      }
88554      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
88555      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
88556      break;
88557    }
88558
88559    /* If none of the above, then the result destination must be
88560    ** SRT_Output.  This routine is never called with any other
88561    ** destination other than the ones handled above or SRT_Output.
88562    **
88563    ** For SRT_Output, results are stored in a sequence of registers.
88564    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
88565    ** return the next row of result.
88566    */
88567    default: {
88568      assert( pDest->eDest==SRT_Output );
88569      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
88570      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
88571      break;
88572    }
88573  }
88574
88575  /* Jump to the end of the loop if the LIMIT is reached.
88576  */
88577  if( p->iLimit ){
88578    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
88579  }
88580
88581  /* Generate the subroutine return
88582  */
88583  sqlite3VdbeResolveLabel(v, iContinue);
88584  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
88585
88586  return addr;
88587}
88588
88589/*
88590** Alternative compound select code generator for cases when there
88591** is an ORDER BY clause.
88592**
88593** We assume a query of the following form:
88594**
88595**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
88596**
88597** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
88598** is to code both <selectA> and <selectB> with the ORDER BY clause as
88599** co-routines.  Then run the co-routines in parallel and merge the results
88600** into the output.  In addition to the two coroutines (called selectA and
88601** selectB) there are 7 subroutines:
88602**
88603**    outA:    Move the output of the selectA coroutine into the output
88604**             of the compound query.
88605**
88606**    outB:    Move the output of the selectB coroutine into the output
88607**             of the compound query.  (Only generated for UNION and
88608**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
88609**             appears only in B.)
88610**
88611**    AltB:    Called when there is data from both coroutines and A<B.
88612**
88613**    AeqB:    Called when there is data from both coroutines and A==B.
88614**
88615**    AgtB:    Called when there is data from both coroutines and A>B.
88616**
88617**    EofA:    Called when data is exhausted from selectA.
88618**
88619**    EofB:    Called when data is exhausted from selectB.
88620**
88621** The implementation of the latter five subroutines depend on which
88622** <operator> is used:
88623**
88624**
88625**             UNION ALL         UNION            EXCEPT          INTERSECT
88626**          -------------  -----------------  --------------  -----------------
88627**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
88628**
88629**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
88630**
88631**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
88632**
88633**   EofA:   outB, nextB      outB, nextB          halt             halt
88634**
88635**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
88636**
88637** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
88638** causes an immediate jump to EofA and an EOF on B following nextB causes
88639** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
88640** following nextX causes a jump to the end of the select processing.
88641**
88642** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
88643** within the output subroutine.  The regPrev register set holds the previously
88644** output value.  A comparison is made against this value and the output
88645** is skipped if the next results would be the same as the previous.
88646**
88647** The implementation plan is to implement the two coroutines and seven
88648** subroutines first, then put the control logic at the bottom.  Like this:
88649**
88650**          goto Init
88651**     coA: coroutine for left query (A)
88652**     coB: coroutine for right query (B)
88653**    outA: output one row of A
88654**    outB: output one row of B (UNION and UNION ALL only)
88655**    EofA: ...
88656**    EofB: ...
88657**    AltB: ...
88658**    AeqB: ...
88659**    AgtB: ...
88660**    Init: initialize coroutine registers
88661**          yield coA
88662**          if eof(A) goto EofA
88663**          yield coB
88664**          if eof(B) goto EofB
88665**    Cmpr: Compare A, B
88666**          Jump AltB, AeqB, AgtB
88667**     End: ...
88668**
88669** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
88670** actually called using Gosub and they do not Return.  EofA and EofB loop
88671** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
88672** and AgtB jump to either L2 or to one of EofA or EofB.
88673*/
88674#ifndef SQLITE_OMIT_COMPOUND_SELECT
88675static int multiSelectOrderBy(
88676  Parse *pParse,        /* Parsing context */
88677  Select *p,            /* The right-most of SELECTs to be coded */
88678  SelectDest *pDest     /* What to do with query results */
88679){
88680  int i, j;             /* Loop counters */
88681  Select *pPrior;       /* Another SELECT immediately to our left */
88682  Vdbe *v;              /* Generate code to this VDBE */
88683  SelectDest destA;     /* Destination for coroutine A */
88684  SelectDest destB;     /* Destination for coroutine B */
88685  int regAddrA;         /* Address register for select-A coroutine */
88686  int regEofA;          /* Flag to indicate when select-A is complete */
88687  int regAddrB;         /* Address register for select-B coroutine */
88688  int regEofB;          /* Flag to indicate when select-B is complete */
88689  int addrSelectA;      /* Address of the select-A coroutine */
88690  int addrSelectB;      /* Address of the select-B coroutine */
88691  int regOutA;          /* Address register for the output-A subroutine */
88692  int regOutB;          /* Address register for the output-B subroutine */
88693  int addrOutA;         /* Address of the output-A subroutine */
88694  int addrOutB = 0;     /* Address of the output-B subroutine */
88695  int addrEofA;         /* Address of the select-A-exhausted subroutine */
88696  int addrEofB;         /* Address of the select-B-exhausted subroutine */
88697  int addrAltB;         /* Address of the A<B subroutine */
88698  int addrAeqB;         /* Address of the A==B subroutine */
88699  int addrAgtB;         /* Address of the A>B subroutine */
88700  int regLimitA;        /* Limit register for select-A */
88701  int regLimitB;        /* Limit register for select-A */
88702  int regPrev;          /* A range of registers to hold previous output */
88703  int savedLimit;       /* Saved value of p->iLimit */
88704  int savedOffset;      /* Saved value of p->iOffset */
88705  int labelCmpr;        /* Label for the start of the merge algorithm */
88706  int labelEnd;         /* Label for the end of the overall SELECT stmt */
88707  int j1;               /* Jump instructions that get retargetted */
88708  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
88709  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
88710  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
88711  sqlite3 *db;          /* Database connection */
88712  ExprList *pOrderBy;   /* The ORDER BY clause */
88713  int nOrderBy;         /* Number of terms in the ORDER BY clause */
88714  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
88715
88716  assert( p->pOrderBy!=0 );
88717  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
88718  db = pParse->db;
88719  v = pParse->pVdbe;
88720  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
88721  labelEnd = sqlite3VdbeMakeLabel(v);
88722  labelCmpr = sqlite3VdbeMakeLabel(v);
88723
88724
88725  /* Patch up the ORDER BY clause
88726  */
88727  op = p->op;
88728  pPrior = p->pPrior;
88729  assert( pPrior->pOrderBy==0 );
88730  pOrderBy = p->pOrderBy;
88731  assert( pOrderBy );
88732  nOrderBy = pOrderBy->nExpr;
88733
88734  /* For operators other than UNION ALL we have to make sure that
88735  ** the ORDER BY clause covers every term of the result set.  Add
88736  ** terms to the ORDER BY clause as necessary.
88737  */
88738  if( op!=TK_ALL ){
88739    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
88740      struct ExprList_item *pItem;
88741      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
88742        assert( pItem->iCol>0 );
88743        if( pItem->iCol==i ) break;
88744      }
88745      if( j==nOrderBy ){
88746        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
88747        if( pNew==0 ) return SQLITE_NOMEM;
88748        pNew->flags |= EP_IntValue;
88749        pNew->u.iValue = i;
88750        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
88751        pOrderBy->a[nOrderBy++].iCol = (u16)i;
88752      }
88753    }
88754  }
88755
88756  /* Compute the comparison permutation and keyinfo that is used with
88757  ** the permutation used to determine if the next
88758  ** row of results comes from selectA or selectB.  Also add explicit
88759  ** collations to the ORDER BY clause terms so that when the subqueries
88760  ** to the right and the left are evaluated, they use the correct
88761  ** collation.
88762  */
88763  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
88764  if( aPermute ){
88765    struct ExprList_item *pItem;
88766    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
88767      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
88768      aPermute[i] = pItem->iCol - 1;
88769    }
88770    pKeyMerge =
88771      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
88772    if( pKeyMerge ){
88773      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
88774      pKeyMerge->nField = (u16)nOrderBy;
88775      pKeyMerge->enc = ENC(db);
88776      for(i=0; i<nOrderBy; i++){
88777        CollSeq *pColl;
88778        Expr *pTerm = pOrderBy->a[i].pExpr;
88779        if( pTerm->flags & EP_ExpCollate ){
88780          pColl = pTerm->pColl;
88781        }else{
88782          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
88783          pTerm->flags |= EP_ExpCollate;
88784          pTerm->pColl = pColl;
88785        }
88786        pKeyMerge->aColl[i] = pColl;
88787        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
88788      }
88789    }
88790  }else{
88791    pKeyMerge = 0;
88792  }
88793
88794  /* Reattach the ORDER BY clause to the query.
88795  */
88796  p->pOrderBy = pOrderBy;
88797  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
88798
88799  /* Allocate a range of temporary registers and the KeyInfo needed
88800  ** for the logic that removes duplicate result rows when the
88801  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
88802  */
88803  if( op==TK_ALL ){
88804    regPrev = 0;
88805  }else{
88806    int nExpr = p->pEList->nExpr;
88807    assert( nOrderBy>=nExpr || db->mallocFailed );
88808    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
88809    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
88810    pKeyDup = sqlite3DbMallocZero(db,
88811                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
88812    if( pKeyDup ){
88813      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
88814      pKeyDup->nField = (u16)nExpr;
88815      pKeyDup->enc = ENC(db);
88816      for(i=0; i<nExpr; i++){
88817        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
88818        pKeyDup->aSortOrder[i] = 0;
88819      }
88820    }
88821  }
88822
88823  /* Separate the left and the right query from one another
88824  */
88825  p->pPrior = 0;
88826  pPrior->pRightmost = 0;
88827  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
88828  if( pPrior->pPrior==0 ){
88829    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
88830  }
88831
88832  /* Compute the limit registers */
88833  computeLimitRegisters(pParse, p, labelEnd);
88834  if( p->iLimit && op==TK_ALL ){
88835    regLimitA = ++pParse->nMem;
88836    regLimitB = ++pParse->nMem;
88837    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
88838                                  regLimitA);
88839    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
88840  }else{
88841    regLimitA = regLimitB = 0;
88842  }
88843  sqlite3ExprDelete(db, p->pLimit);
88844  p->pLimit = 0;
88845  sqlite3ExprDelete(db, p->pOffset);
88846  p->pOffset = 0;
88847
88848  regAddrA = ++pParse->nMem;
88849  regEofA = ++pParse->nMem;
88850  regAddrB = ++pParse->nMem;
88851  regEofB = ++pParse->nMem;
88852  regOutA = ++pParse->nMem;
88853  regOutB = ++pParse->nMem;
88854  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
88855  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
88856
88857  /* Jump past the various subroutines and coroutines to the main
88858  ** merge loop
88859  */
88860  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
88861  addrSelectA = sqlite3VdbeCurrentAddr(v);
88862
88863
88864  /* Generate a coroutine to evaluate the SELECT statement to the
88865  ** left of the compound operator - the "A" select.
88866  */
88867  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
88868  pPrior->iLimit = regLimitA;
88869  sqlite3Select(pParse, pPrior, &destA);
88870  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
88871  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88872  VdbeNoopComment((v, "End coroutine for left SELECT"));
88873
88874  /* Generate a coroutine to evaluate the SELECT statement on
88875  ** the right - the "B" select
88876  */
88877  addrSelectB = sqlite3VdbeCurrentAddr(v);
88878  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
88879  savedLimit = p->iLimit;
88880  savedOffset = p->iOffset;
88881  p->iLimit = regLimitB;
88882  p->iOffset = 0;
88883  sqlite3Select(pParse, p, &destB);
88884  p->iLimit = savedLimit;
88885  p->iOffset = savedOffset;
88886  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
88887  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
88888  VdbeNoopComment((v, "End coroutine for right SELECT"));
88889
88890  /* Generate a subroutine that outputs the current row of the A
88891  ** select as the next output row of the compound select.
88892  */
88893  VdbeNoopComment((v, "Output routine for A"));
88894  addrOutA = generateOutputSubroutine(pParse,
88895                 p, &destA, pDest, regOutA,
88896                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
88897
88898  /* Generate a subroutine that outputs the current row of the B
88899  ** select as the next output row of the compound select.
88900  */
88901  if( op==TK_ALL || op==TK_UNION ){
88902    VdbeNoopComment((v, "Output routine for B"));
88903    addrOutB = generateOutputSubroutine(pParse,
88904                 p, &destB, pDest, regOutB,
88905                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
88906  }
88907
88908  /* Generate a subroutine to run when the results from select A
88909  ** are exhausted and only data in select B remains.
88910  */
88911  VdbeNoopComment((v, "eof-A subroutine"));
88912  if( op==TK_EXCEPT || op==TK_INTERSECT ){
88913    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
88914  }else{
88915    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
88916    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
88917    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
88918    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
88919  }
88920
88921  /* Generate a subroutine to run when the results from select B
88922  ** are exhausted and only data in select A remains.
88923  */
88924  if( op==TK_INTERSECT ){
88925    addrEofB = addrEofA;
88926  }else{
88927    VdbeNoopComment((v, "eof-B subroutine"));
88928    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
88929    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
88930    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88931    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
88932  }
88933
88934  /* Generate code to handle the case of A<B
88935  */
88936  VdbeNoopComment((v, "A-lt-B subroutine"));
88937  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
88938  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88939  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88940  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88941
88942  /* Generate code to handle the case of A==B
88943  */
88944  if( op==TK_ALL ){
88945    addrAeqB = addrAltB;
88946  }else if( op==TK_INTERSECT ){
88947    addrAeqB = addrAltB;
88948    addrAltB++;
88949  }else{
88950    VdbeNoopComment((v, "A-eq-B subroutine"));
88951    addrAeqB =
88952    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
88953    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88954    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88955  }
88956
88957  /* Generate code to handle the case of A>B
88958  */
88959  VdbeNoopComment((v, "A-gt-B subroutine"));
88960  addrAgtB = sqlite3VdbeCurrentAddr(v);
88961  if( op==TK_ALL || op==TK_UNION ){
88962    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
88963  }
88964  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
88965  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
88966  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
88967
88968  /* This code runs once to initialize everything.
88969  */
88970  sqlite3VdbeJumpHere(v, j1);
88971  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
88972  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
88973  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
88974  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
88975  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
88976  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
88977
88978  /* Implement the main merge loop
88979  */
88980  sqlite3VdbeResolveLabel(v, labelCmpr);
88981  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
88982  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
88983                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
88984  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
88985
88986  /* Release temporary registers
88987  */
88988  if( regPrev ){
88989    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
88990  }
88991
88992  /* Jump to the this point in order to terminate the query.
88993  */
88994  sqlite3VdbeResolveLabel(v, labelEnd);
88995
88996  /* Set the number of output columns
88997  */
88998  if( pDest->eDest==SRT_Output ){
88999    Select *pFirst = pPrior;
89000    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
89001    generateColumnNames(pParse, 0, pFirst->pEList);
89002  }
89003
89004  /* Reassembly the compound query so that it will be freed correctly
89005  ** by the calling function */
89006  if( p->pPrior ){
89007    sqlite3SelectDelete(db, p->pPrior);
89008  }
89009  p->pPrior = pPrior;
89010
89011  /*** TBD:  Insert subroutine calls to close cursors on incomplete
89012  **** subqueries ****/
89013  return SQLITE_OK;
89014}
89015#endif
89016
89017#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89018/* Forward Declarations */
89019static void substExprList(sqlite3*, ExprList*, int, ExprList*);
89020static void substSelect(sqlite3*, Select *, int, ExprList *);
89021
89022/*
89023** Scan through the expression pExpr.  Replace every reference to
89024** a column in table number iTable with a copy of the iColumn-th
89025** entry in pEList.  (But leave references to the ROWID column
89026** unchanged.)
89027**
89028** This routine is part of the flattening procedure.  A subquery
89029** whose result set is defined by pEList appears as entry in the
89030** FROM clause of a SELECT such that the VDBE cursor assigned to that
89031** FORM clause entry is iTable.  This routine make the necessary
89032** changes to pExpr so that it refers directly to the source table
89033** of the subquery rather the result set of the subquery.
89034*/
89035static Expr *substExpr(
89036  sqlite3 *db,        /* Report malloc errors to this connection */
89037  Expr *pExpr,        /* Expr in which substitution occurs */
89038  int iTable,         /* Table to be substituted */
89039  ExprList *pEList    /* Substitute expressions */
89040){
89041  if( pExpr==0 ) return 0;
89042  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
89043    if( pExpr->iColumn<0 ){
89044      pExpr->op = TK_NULL;
89045    }else{
89046      Expr *pNew;
89047      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
89048      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
89049      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
89050      if( pNew && pExpr->pColl ){
89051        pNew->pColl = pExpr->pColl;
89052      }
89053      sqlite3ExprDelete(db, pExpr);
89054      pExpr = pNew;
89055    }
89056  }else{
89057    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
89058    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
89059    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89060      substSelect(db, pExpr->x.pSelect, iTable, pEList);
89061    }else{
89062      substExprList(db, pExpr->x.pList, iTable, pEList);
89063    }
89064  }
89065  return pExpr;
89066}
89067static void substExprList(
89068  sqlite3 *db,         /* Report malloc errors here */
89069  ExprList *pList,     /* List to scan and in which to make substitutes */
89070  int iTable,          /* Table to be substituted */
89071  ExprList *pEList     /* Substitute values */
89072){
89073  int i;
89074  if( pList==0 ) return;
89075  for(i=0; i<pList->nExpr; i++){
89076    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
89077  }
89078}
89079static void substSelect(
89080  sqlite3 *db,         /* Report malloc errors here */
89081  Select *p,           /* SELECT statement in which to make substitutions */
89082  int iTable,          /* Table to be replaced */
89083  ExprList *pEList     /* Substitute values */
89084){
89085  SrcList *pSrc;
89086  struct SrcList_item *pItem;
89087  int i;
89088  if( !p ) return;
89089  substExprList(db, p->pEList, iTable, pEList);
89090  substExprList(db, p->pGroupBy, iTable, pEList);
89091  substExprList(db, p->pOrderBy, iTable, pEList);
89092  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
89093  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
89094  substSelect(db, p->pPrior, iTable, pEList);
89095  pSrc = p->pSrc;
89096  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
89097  if( ALWAYS(pSrc) ){
89098    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
89099      substSelect(db, pItem->pSelect, iTable, pEList);
89100    }
89101  }
89102}
89103#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
89104
89105#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
89106/*
89107** This routine attempts to flatten subqueries in order to speed
89108** execution.  It returns 1 if it makes changes and 0 if no flattening
89109** occurs.
89110**
89111** To understand the concept of flattening, consider the following
89112** query:
89113**
89114**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
89115**
89116** The default way of implementing this query is to execute the
89117** subquery first and store the results in a temporary table, then
89118** run the outer query on that temporary table.  This requires two
89119** passes over the data.  Furthermore, because the temporary table
89120** has no indices, the WHERE clause on the outer query cannot be
89121** optimized.
89122**
89123** This routine attempts to rewrite queries such as the above into
89124** a single flat select, like this:
89125**
89126**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
89127**
89128** The code generated for this simpification gives the same result
89129** but only has to scan the data once.  And because indices might
89130** exist on the table t1, a complete scan of the data might be
89131** avoided.
89132**
89133** Flattening is only attempted if all of the following are true:
89134**
89135**   (1)  The subquery and the outer query do not both use aggregates.
89136**
89137**   (2)  The subquery is not an aggregate or the outer query is not a join.
89138**
89139**   (3)  The subquery is not the right operand of a left outer join
89140**        (Originally ticket #306.  Strengthened by ticket #3300)
89141**
89142**   (4)  The subquery is not DISTINCT.
89143**
89144**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
89145**        sub-queries that were excluded from this optimization. Restriction
89146**        (4) has since been expanded to exclude all DISTINCT subqueries.
89147**
89148**   (6)  The subquery does not use aggregates or the outer query is not
89149**        DISTINCT.
89150**
89151**   (7)  The subquery has a FROM clause.
89152**
89153**   (8)  The subquery does not use LIMIT or the outer query is not a join.
89154**
89155**   (9)  The subquery does not use LIMIT or the outer query does not use
89156**        aggregates.
89157**
89158**  (10)  The subquery does not use aggregates or the outer query does not
89159**        use LIMIT.
89160**
89161**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
89162**
89163**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
89164**        a separate restriction deriving from ticket #350.
89165**
89166**  (13)  The subquery and outer query do not both use LIMIT.
89167**
89168**  (14)  The subquery does not use OFFSET.
89169**
89170**  (15)  The outer query is not part of a compound select or the
89171**        subquery does not have a LIMIT clause.
89172**        (See ticket #2339 and ticket [02a8e81d44]).
89173**
89174**  (16)  The outer query is not an aggregate or the subquery does
89175**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
89176**        until we introduced the group_concat() function.
89177**
89178**  (17)  The sub-query is not a compound select, or it is a UNION ALL
89179**        compound clause made up entirely of non-aggregate queries, and
89180**        the parent query:
89181**
89182**          * is not itself part of a compound select,
89183**          * is not an aggregate or DISTINCT query, and
89184**          * has no other tables or sub-selects in the FROM clause.
89185**
89186**        The parent and sub-query may contain WHERE clauses. Subject to
89187**        rules (11), (13) and (14), they may also contain ORDER BY,
89188**        LIMIT and OFFSET clauses.
89189**
89190**  (18)  If the sub-query is a compound select, then all terms of the
89191**        ORDER by clause of the parent must be simple references to
89192**        columns of the sub-query.
89193**
89194**  (19)  The subquery does not use LIMIT or the outer query does not
89195**        have a WHERE clause.
89196**
89197**  (20)  If the sub-query is a compound select, then it must not use
89198**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
89199**        somewhat by saying that the terms of the ORDER BY clause must
89200**        appear as unmodified result columns in the outer query.  But
89201**        have other optimizations in mind to deal with that case.
89202**
89203** In this routine, the "p" parameter is a pointer to the outer query.
89204** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
89205** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
89206**
89207** If flattening is not attempted, this routine is a no-op and returns 0.
89208** If flattening is attempted this routine returns 1.
89209**
89210** All of the expression analysis must occur on both the outer query and
89211** the subquery before this routine runs.
89212*/
89213static int flattenSubquery(
89214  Parse *pParse,       /* Parsing context */
89215  Select *p,           /* The parent or outer SELECT statement */
89216  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
89217  int isAgg,           /* True if outer SELECT uses aggregate functions */
89218  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
89219){
89220  const char *zSavedAuthContext = pParse->zAuthContext;
89221  Select *pParent;
89222  Select *pSub;       /* The inner query or "subquery" */
89223  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
89224  SrcList *pSrc;      /* The FROM clause of the outer query */
89225  SrcList *pSubSrc;   /* The FROM clause of the subquery */
89226  ExprList *pList;    /* The result set of the outer query */
89227  int iParent;        /* VDBE cursor number of the pSub result set temp table */
89228  int i;              /* Loop counter */
89229  Expr *pWhere;                    /* The WHERE clause */
89230  struct SrcList_item *pSubitem;   /* The subquery */
89231  sqlite3 *db = pParse->db;
89232
89233  /* Check to see if flattening is permitted.  Return 0 if not.
89234  */
89235  assert( p!=0 );
89236  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
89237  if( db->flags & SQLITE_QueryFlattener ) return 0;
89238  pSrc = p->pSrc;
89239  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
89240  pSubitem = &pSrc->a[iFrom];
89241  iParent = pSubitem->iCursor;
89242  pSub = pSubitem->pSelect;
89243  assert( pSub!=0 );
89244  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
89245  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
89246  pSubSrc = pSub->pSrc;
89247  assert( pSubSrc );
89248  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
89249  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
89250  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
89251  ** became arbitrary expressions, we were forced to add restrictions (13)
89252  ** and (14). */
89253  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
89254  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
89255  if( p->pRightmost && pSub->pLimit ){
89256    return 0;                                            /* Restriction (15) */
89257  }
89258  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
89259  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
89260  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
89261     return 0;         /* Restrictions (8)(9) */
89262  }
89263  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
89264     return 0;         /* Restriction (6)  */
89265  }
89266  if( p->pOrderBy && pSub->pOrderBy ){
89267     return 0;                                           /* Restriction (11) */
89268  }
89269  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
89270  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
89271
89272  /* OBSOLETE COMMENT 1:
89273  ** Restriction 3:  If the subquery is a join, make sure the subquery is
89274  ** not used as the right operand of an outer join.  Examples of why this
89275  ** is not allowed:
89276  **
89277  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
89278  **
89279  ** If we flatten the above, we would get
89280  **
89281  **         (t1 LEFT OUTER JOIN t2) JOIN t3
89282  **
89283  ** which is not at all the same thing.
89284  **
89285  ** OBSOLETE COMMENT 2:
89286  ** Restriction 12:  If the subquery is the right operand of a left outer
89287  ** join, make sure the subquery has no WHERE clause.
89288  ** An examples of why this is not allowed:
89289  **
89290  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
89291  **
89292  ** If we flatten the above, we would get
89293  **
89294  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
89295  **
89296  ** But the t2.x>0 test will always fail on a NULL row of t2, which
89297  ** effectively converts the OUTER JOIN into an INNER JOIN.
89298  **
89299  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
89300  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
89301  ** is fraught with danger.  Best to avoid the whole thing.  If the
89302  ** subquery is the right term of a LEFT JOIN, then do not flatten.
89303  */
89304  if( (pSubitem->jointype & JT_OUTER)!=0 ){
89305    return 0;
89306  }
89307
89308  /* Restriction 17: If the sub-query is a compound SELECT, then it must
89309  ** use only the UNION ALL operator. And none of the simple select queries
89310  ** that make up the compound SELECT are allowed to be aggregate or distinct
89311  ** queries.
89312  */
89313  if( pSub->pPrior ){
89314    if( pSub->pOrderBy ){
89315      return 0;  /* Restriction 20 */
89316    }
89317    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
89318      return 0;
89319    }
89320    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
89321      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
89322      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
89323      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
89324       || (pSub1->pPrior && pSub1->op!=TK_ALL)
89325       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
89326      ){
89327        return 0;
89328      }
89329    }
89330
89331    /* Restriction 18. */
89332    if( p->pOrderBy ){
89333      int ii;
89334      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
89335        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
89336      }
89337    }
89338  }
89339
89340  /***** If we reach this point, flattening is permitted. *****/
89341
89342  /* Authorize the subquery */
89343  pParse->zAuthContext = pSubitem->zName;
89344  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
89345  pParse->zAuthContext = zSavedAuthContext;
89346
89347  /* If the sub-query is a compound SELECT statement, then (by restrictions
89348  ** 17 and 18 above) it must be a UNION ALL and the parent query must
89349  ** be of the form:
89350  **
89351  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
89352  **
89353  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
89354  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
89355  ** OFFSET clauses and joins them to the left-hand-side of the original
89356  ** using UNION ALL operators. In this case N is the number of simple
89357  ** select statements in the compound sub-query.
89358  **
89359  ** Example:
89360  **
89361  **     SELECT a+1 FROM (
89362  **        SELECT x FROM tab
89363  **        UNION ALL
89364  **        SELECT y FROM tab
89365  **        UNION ALL
89366  **        SELECT abs(z*2) FROM tab2
89367  **     ) WHERE a!=5 ORDER BY 1
89368  **
89369  ** Transformed into:
89370  **
89371  **     SELECT x+1 FROM tab WHERE x+1!=5
89372  **     UNION ALL
89373  **     SELECT y+1 FROM tab WHERE y+1!=5
89374  **     UNION ALL
89375  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
89376  **     ORDER BY 1
89377  **
89378  ** We call this the "compound-subquery flattening".
89379  */
89380  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
89381    Select *pNew;
89382    ExprList *pOrderBy = p->pOrderBy;
89383    Expr *pLimit = p->pLimit;
89384    Select *pPrior = p->pPrior;
89385    p->pOrderBy = 0;
89386    p->pSrc = 0;
89387    p->pPrior = 0;
89388    p->pLimit = 0;
89389    pNew = sqlite3SelectDup(db, p, 0);
89390    p->pLimit = pLimit;
89391    p->pOrderBy = pOrderBy;
89392    p->pSrc = pSrc;
89393    p->op = TK_ALL;
89394    p->pRightmost = 0;
89395    if( pNew==0 ){
89396      pNew = pPrior;
89397    }else{
89398      pNew->pPrior = pPrior;
89399      pNew->pRightmost = 0;
89400    }
89401    p->pPrior = pNew;
89402    if( db->mallocFailed ) return 1;
89403  }
89404
89405  /* Begin flattening the iFrom-th entry of the FROM clause
89406  ** in the outer query.
89407  */
89408  pSub = pSub1 = pSubitem->pSelect;
89409
89410  /* Delete the transient table structure associated with the
89411  ** subquery
89412  */
89413  sqlite3DbFree(db, pSubitem->zDatabase);
89414  sqlite3DbFree(db, pSubitem->zName);
89415  sqlite3DbFree(db, pSubitem->zAlias);
89416  pSubitem->zDatabase = 0;
89417  pSubitem->zName = 0;
89418  pSubitem->zAlias = 0;
89419  pSubitem->pSelect = 0;
89420
89421  /* Defer deleting the Table object associated with the
89422  ** subquery until code generation is
89423  ** complete, since there may still exist Expr.pTab entries that
89424  ** refer to the subquery even after flattening.  Ticket #3346.
89425  **
89426  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
89427  */
89428  if( ALWAYS(pSubitem->pTab!=0) ){
89429    Table *pTabToDel = pSubitem->pTab;
89430    if( pTabToDel->nRef==1 ){
89431      Parse *pToplevel = sqlite3ParseToplevel(pParse);
89432      pTabToDel->pNextZombie = pToplevel->pZombieTab;
89433      pToplevel->pZombieTab = pTabToDel;
89434    }else{
89435      pTabToDel->nRef--;
89436    }
89437    pSubitem->pTab = 0;
89438  }
89439
89440  /* The following loop runs once for each term in a compound-subquery
89441  ** flattening (as described above).  If we are doing a different kind
89442  ** of flattening - a flattening other than a compound-subquery flattening -
89443  ** then this loop only runs once.
89444  **
89445  ** This loop moves all of the FROM elements of the subquery into the
89446  ** the FROM clause of the outer query.  Before doing this, remember
89447  ** the cursor number for the original outer query FROM element in
89448  ** iParent.  The iParent cursor will never be used.  Subsequent code
89449  ** will scan expressions looking for iParent references and replace
89450  ** those references with expressions that resolve to the subquery FROM
89451  ** elements we are now copying in.
89452  */
89453  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
89454    int nSubSrc;
89455    u8 jointype = 0;
89456    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
89457    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
89458    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
89459
89460    if( pSrc ){
89461      assert( pParent==p );  /* First time through the loop */
89462      jointype = pSubitem->jointype;
89463    }else{
89464      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
89465      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
89466      if( pSrc==0 ){
89467        assert( db->mallocFailed );
89468        break;
89469      }
89470    }
89471
89472    /* The subquery uses a single slot of the FROM clause of the outer
89473    ** query.  If the subquery has more than one element in its FROM clause,
89474    ** then expand the outer query to make space for it to hold all elements
89475    ** of the subquery.
89476    **
89477    ** Example:
89478    **
89479    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
89480    **
89481    ** The outer query has 3 slots in its FROM clause.  One slot of the
89482    ** outer query (the middle slot) is used by the subquery.  The next
89483    ** block of code will expand the out query to 4 slots.  The middle
89484    ** slot is expanded to two slots in order to make space for the
89485    ** two elements in the FROM clause of the subquery.
89486    */
89487    if( nSubSrc>1 ){
89488      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
89489      if( db->mallocFailed ){
89490        break;
89491      }
89492    }
89493
89494    /* Transfer the FROM clause terms from the subquery into the
89495    ** outer query.
89496    */
89497    for(i=0; i<nSubSrc; i++){
89498      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
89499      pSrc->a[i+iFrom] = pSubSrc->a[i];
89500      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
89501    }
89502    pSrc->a[iFrom].jointype = jointype;
89503
89504    /* Now begin substituting subquery result set expressions for
89505    ** references to the iParent in the outer query.
89506    **
89507    ** Example:
89508    **
89509    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
89510    **   \                     \_____________ subquery __________/          /
89511    **    \_____________________ outer query ______________________________/
89512    **
89513    ** We look at every expression in the outer query and every place we see
89514    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
89515    */
89516    pList = pParent->pEList;
89517    for(i=0; i<pList->nExpr; i++){
89518      if( pList->a[i].zName==0 ){
89519        const char *zSpan = pList->a[i].zSpan;
89520        if( ALWAYS(zSpan) ){
89521          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
89522        }
89523      }
89524    }
89525    substExprList(db, pParent->pEList, iParent, pSub->pEList);
89526    if( isAgg ){
89527      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
89528      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
89529    }
89530    if( pSub->pOrderBy ){
89531      assert( pParent->pOrderBy==0 );
89532      pParent->pOrderBy = pSub->pOrderBy;
89533      pSub->pOrderBy = 0;
89534    }else if( pParent->pOrderBy ){
89535      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
89536    }
89537    if( pSub->pWhere ){
89538      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
89539    }else{
89540      pWhere = 0;
89541    }
89542    if( subqueryIsAgg ){
89543      assert( pParent->pHaving==0 );
89544      pParent->pHaving = pParent->pWhere;
89545      pParent->pWhere = pWhere;
89546      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
89547      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
89548                                  sqlite3ExprDup(db, pSub->pHaving, 0));
89549      assert( pParent->pGroupBy==0 );
89550      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
89551    }else{
89552      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
89553      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
89554    }
89555
89556    /* The flattened query is distinct if either the inner or the
89557    ** outer query is distinct.
89558    */
89559    pParent->selFlags |= pSub->selFlags & SF_Distinct;
89560
89561    /*
89562    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
89563    **
89564    ** One is tempted to try to add a and b to combine the limits.  But this
89565    ** does not work if either limit is negative.
89566    */
89567    if( pSub->pLimit ){
89568      pParent->pLimit = pSub->pLimit;
89569      pSub->pLimit = 0;
89570    }
89571  }
89572
89573  /* Finially, delete what is left of the subquery and return
89574  ** success.
89575  */
89576  sqlite3SelectDelete(db, pSub1);
89577
89578  return 1;
89579}
89580#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
89581
89582/*
89583** Analyze the SELECT statement passed as an argument to see if it
89584** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
89585** it is, or 0 otherwise. At present, a query is considered to be
89586** a min()/max() query if:
89587**
89588**   1. There is a single object in the FROM clause.
89589**
89590**   2. There is a single expression in the result set, and it is
89591**      either min(x) or max(x), where x is a column reference.
89592*/
89593static u8 minMaxQuery(Select *p){
89594  Expr *pExpr;
89595  ExprList *pEList = p->pEList;
89596
89597  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
89598  pExpr = pEList->a[0].pExpr;
89599  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
89600  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
89601  pEList = pExpr->x.pList;
89602  if( pEList==0 || pEList->nExpr!=1 ) return 0;
89603  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
89604  assert( !ExprHasProperty(pExpr, EP_IntValue) );
89605  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
89606    return WHERE_ORDERBY_MIN;
89607  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
89608    return WHERE_ORDERBY_MAX;
89609  }
89610  return WHERE_ORDERBY_NORMAL;
89611}
89612
89613/*
89614** The select statement passed as the first argument is an aggregate query.
89615** The second argment is the associated aggregate-info object. This
89616** function tests if the SELECT is of the form:
89617**
89618**   SELECT count(*) FROM <tbl>
89619**
89620** where table is a database table, not a sub-select or view. If the query
89621** does match this pattern, then a pointer to the Table object representing
89622** <tbl> is returned. Otherwise, 0 is returned.
89623*/
89624static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
89625  Table *pTab;
89626  Expr *pExpr;
89627
89628  assert( !p->pGroupBy );
89629
89630  if( p->pWhere || p->pEList->nExpr!=1
89631   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
89632  ){
89633    return 0;
89634  }
89635  pTab = p->pSrc->a[0].pTab;
89636  pExpr = p->pEList->a[0].pExpr;
89637  assert( pTab && !pTab->pSelect && pExpr );
89638
89639  if( IsVirtual(pTab) ) return 0;
89640  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
89641  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
89642  if( pExpr->flags&EP_Distinct ) return 0;
89643
89644  return pTab;
89645}
89646
89647/*
89648** If the source-list item passed as an argument was augmented with an
89649** INDEXED BY clause, then try to locate the specified index. If there
89650** was such a clause and the named index cannot be found, return
89651** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
89652** pFrom->pIndex and return SQLITE_OK.
89653*/
89654SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
89655  if( pFrom->pTab && pFrom->zIndex ){
89656    Table *pTab = pFrom->pTab;
89657    char *zIndex = pFrom->zIndex;
89658    Index *pIdx;
89659    for(pIdx=pTab->pIndex;
89660        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
89661        pIdx=pIdx->pNext
89662    );
89663    if( !pIdx ){
89664      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
89665      pParse->checkSchema = 1;
89666      return SQLITE_ERROR;
89667    }
89668    pFrom->pIndex = pIdx;
89669  }
89670  return SQLITE_OK;
89671}
89672
89673/*
89674** This routine is a Walker callback for "expanding" a SELECT statement.
89675** "Expanding" means to do the following:
89676**
89677**    (1)  Make sure VDBE cursor numbers have been assigned to every
89678**         element of the FROM clause.
89679**
89680**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
89681**         defines FROM clause.  When views appear in the FROM clause,
89682**         fill pTabList->a[].pSelect with a copy of the SELECT statement
89683**         that implements the view.  A copy is made of the view's SELECT
89684**         statement so that we can freely modify or delete that statement
89685**         without worrying about messing up the presistent representation
89686**         of the view.
89687**
89688**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
89689**         on joins and the ON and USING clause of joins.
89690**
89691**    (4)  Scan the list of columns in the result set (pEList) looking
89692**         for instances of the "*" operator or the TABLE.* operator.
89693**         If found, expand each "*" to be every column in every table
89694**         and TABLE.* to be every column in TABLE.
89695**
89696*/
89697static int selectExpander(Walker *pWalker, Select *p){
89698  Parse *pParse = pWalker->pParse;
89699  int i, j, k;
89700  SrcList *pTabList;
89701  ExprList *pEList;
89702  struct SrcList_item *pFrom;
89703  sqlite3 *db = pParse->db;
89704
89705  if( db->mallocFailed  ){
89706    return WRC_Abort;
89707  }
89708  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
89709    return WRC_Prune;
89710  }
89711  p->selFlags |= SF_Expanded;
89712  pTabList = p->pSrc;
89713  pEList = p->pEList;
89714
89715  /* Make sure cursor numbers have been assigned to all entries in
89716  ** the FROM clause of the SELECT statement.
89717  */
89718  sqlite3SrcListAssignCursors(pParse, pTabList);
89719
89720  /* Look up every table named in the FROM clause of the select.  If
89721  ** an entry of the FROM clause is a subquery instead of a table or view,
89722  ** then create a transient table structure to describe the subquery.
89723  */
89724  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
89725    Table *pTab;
89726    if( pFrom->pTab!=0 ){
89727      /* This statement has already been prepared.  There is no need
89728      ** to go further. */
89729      assert( i==0 );
89730      return WRC_Prune;
89731    }
89732    if( pFrom->zName==0 ){
89733#ifndef SQLITE_OMIT_SUBQUERY
89734      Select *pSel = pFrom->pSelect;
89735      /* A sub-query in the FROM clause of a SELECT */
89736      assert( pSel!=0 );
89737      assert( pFrom->pTab==0 );
89738      sqlite3WalkSelect(pWalker, pSel);
89739      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
89740      if( pTab==0 ) return WRC_Abort;
89741      pTab->nRef = 1;
89742      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
89743      while( pSel->pPrior ){ pSel = pSel->pPrior; }
89744      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
89745      pTab->iPKey = -1;
89746      pTab->tabFlags |= TF_Ephemeral;
89747#endif
89748    }else{
89749      /* An ordinary table or view name in the FROM clause */
89750      assert( pFrom->pTab==0 );
89751      pFrom->pTab = pTab =
89752        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
89753      if( pTab==0 ) return WRC_Abort;
89754      pTab->nRef++;
89755#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
89756      if( pTab->pSelect || IsVirtual(pTab) ){
89757        /* We reach here if the named table is a really a view */
89758        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
89759        assert( pFrom->pSelect==0 );
89760        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
89761        sqlite3WalkSelect(pWalker, pFrom->pSelect);
89762      }
89763#endif
89764    }
89765
89766    /* Locate the index named by the INDEXED BY clause, if any. */
89767    if( sqlite3IndexedByLookup(pParse, pFrom) ){
89768      return WRC_Abort;
89769    }
89770  }
89771
89772  /* Process NATURAL keywords, and ON and USING clauses of joins.
89773  */
89774  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
89775    return WRC_Abort;
89776  }
89777
89778  /* For every "*" that occurs in the column list, insert the names of
89779  ** all columns in all tables.  And for every TABLE.* insert the names
89780  ** of all columns in TABLE.  The parser inserted a special expression
89781  ** with the TK_ALL operator for each "*" that it found in the column list.
89782  ** The following code just has to locate the TK_ALL expressions and expand
89783  ** each one to the list of all columns in all tables.
89784  **
89785  ** The first loop just checks to see if there are any "*" operators
89786  ** that need expanding.
89787  */
89788  for(k=0; k<pEList->nExpr; k++){
89789    Expr *pE = pEList->a[k].pExpr;
89790    if( pE->op==TK_ALL ) break;
89791    assert( pE->op!=TK_DOT || pE->pRight!=0 );
89792    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
89793    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
89794  }
89795  if( k<pEList->nExpr ){
89796    /*
89797    ** If we get here it means the result set contains one or more "*"
89798    ** operators that need to be expanded.  Loop through each expression
89799    ** in the result set and expand them one by one.
89800    */
89801    struct ExprList_item *a = pEList->a;
89802    ExprList *pNew = 0;
89803    int flags = pParse->db->flags;
89804    int longNames = (flags & SQLITE_FullColNames)!=0
89805                      && (flags & SQLITE_ShortColNames)==0;
89806
89807    for(k=0; k<pEList->nExpr; k++){
89808      Expr *pE = a[k].pExpr;
89809      assert( pE->op!=TK_DOT || pE->pRight!=0 );
89810      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
89811        /* This particular expression does not need to be expanded.
89812        */
89813        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
89814        if( pNew ){
89815          pNew->a[pNew->nExpr-1].zName = a[k].zName;
89816          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
89817          a[k].zName = 0;
89818          a[k].zSpan = 0;
89819        }
89820        a[k].pExpr = 0;
89821      }else{
89822        /* This expression is a "*" or a "TABLE.*" and needs to be
89823        ** expanded. */
89824        int tableSeen = 0;      /* Set to 1 when TABLE matches */
89825        char *zTName;            /* text of name of TABLE */
89826        if( pE->op==TK_DOT ){
89827          assert( pE->pLeft!=0 );
89828          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
89829          zTName = pE->pLeft->u.zToken;
89830        }else{
89831          zTName = 0;
89832        }
89833        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
89834          Table *pTab = pFrom->pTab;
89835          char *zTabName = pFrom->zAlias;
89836          if( zTabName==0 ){
89837            zTabName = pTab->zName;
89838          }
89839          if( db->mallocFailed ) break;
89840          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
89841            continue;
89842          }
89843          tableSeen = 1;
89844          for(j=0; j<pTab->nCol; j++){
89845            Expr *pExpr, *pRight;
89846            char *zName = pTab->aCol[j].zName;
89847            char *zColname;  /* The computed column name */
89848            char *zToFree;   /* Malloced string that needs to be freed */
89849            Token sColname;  /* Computed column name as a token */
89850
89851            /* If a column is marked as 'hidden' (currently only possible
89852            ** for virtual tables), do not include it in the expanded
89853            ** result-set list.
89854            */
89855            if( IsHiddenColumn(&pTab->aCol[j]) ){
89856              assert(IsVirtual(pTab));
89857              continue;
89858            }
89859
89860            if( i>0 && zTName==0 ){
89861              if( (pFrom->jointype & JT_NATURAL)!=0
89862                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
89863              ){
89864                /* In a NATURAL join, omit the join columns from the
89865                ** table to the right of the join */
89866                continue;
89867              }
89868              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
89869                /* In a join with a USING clause, omit columns in the
89870                ** using clause from the table on the right. */
89871                continue;
89872              }
89873            }
89874            pRight = sqlite3Expr(db, TK_ID, zName);
89875            zColname = zName;
89876            zToFree = 0;
89877            if( longNames || pTabList->nSrc>1 ){
89878              Expr *pLeft;
89879              pLeft = sqlite3Expr(db, TK_ID, zTabName);
89880              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
89881              if( longNames ){
89882                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
89883                zToFree = zColname;
89884              }
89885            }else{
89886              pExpr = pRight;
89887            }
89888            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
89889            sColname.z = zColname;
89890            sColname.n = sqlite3Strlen30(zColname);
89891            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
89892            sqlite3DbFree(db, zToFree);
89893          }
89894        }
89895        if( !tableSeen ){
89896          if( zTName ){
89897            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
89898          }else{
89899            sqlite3ErrorMsg(pParse, "no tables specified");
89900          }
89901        }
89902      }
89903    }
89904    sqlite3ExprListDelete(db, pEList);
89905    p->pEList = pNew;
89906  }
89907#if SQLITE_MAX_COLUMN
89908  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89909    sqlite3ErrorMsg(pParse, "too many columns in result set");
89910  }
89911#endif
89912  return WRC_Continue;
89913}
89914
89915/*
89916** No-op routine for the parse-tree walker.
89917**
89918** When this routine is the Walker.xExprCallback then expression trees
89919** are walked without any actions being taken at each node.  Presumably,
89920** when this routine is used for Walker.xExprCallback then
89921** Walker.xSelectCallback is set to do something useful for every
89922** subquery in the parser tree.
89923*/
89924static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
89925  UNUSED_PARAMETER2(NotUsed, NotUsed2);
89926  return WRC_Continue;
89927}
89928
89929/*
89930** This routine "expands" a SELECT statement and all of its subqueries.
89931** For additional information on what it means to "expand" a SELECT
89932** statement, see the comment on the selectExpand worker callback above.
89933**
89934** Expanding a SELECT statement is the first step in processing a
89935** SELECT statement.  The SELECT statement must be expanded before
89936** name resolution is performed.
89937**
89938** If anything goes wrong, an error message is written into pParse.
89939** The calling function can detect the problem by looking at pParse->nErr
89940** and/or pParse->db->mallocFailed.
89941*/
89942static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
89943  Walker w;
89944  w.xSelectCallback = selectExpander;
89945  w.xExprCallback = exprWalkNoop;
89946  w.pParse = pParse;
89947  sqlite3WalkSelect(&w, pSelect);
89948}
89949
89950
89951#ifndef SQLITE_OMIT_SUBQUERY
89952/*
89953** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
89954** interface.
89955**
89956** For each FROM-clause subquery, add Column.zType and Column.zColl
89957** information to the Table structure that represents the result set
89958** of that subquery.
89959**
89960** The Table structure that represents the result set was constructed
89961** by selectExpander() but the type and collation information was omitted
89962** at that point because identifiers had not yet been resolved.  This
89963** routine is called after identifier resolution.
89964*/
89965static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
89966  Parse *pParse;
89967  int i;
89968  SrcList *pTabList;
89969  struct SrcList_item *pFrom;
89970
89971  assert( p->selFlags & SF_Resolved );
89972  if( (p->selFlags & SF_HasTypeInfo)==0 ){
89973    p->selFlags |= SF_HasTypeInfo;
89974    pParse = pWalker->pParse;
89975    pTabList = p->pSrc;
89976    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
89977      Table *pTab = pFrom->pTab;
89978      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
89979        /* A sub-query in the FROM clause of a SELECT */
89980        Select *pSel = pFrom->pSelect;
89981        assert( pSel );
89982        while( pSel->pPrior ) pSel = pSel->pPrior;
89983        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
89984      }
89985    }
89986  }
89987  return WRC_Continue;
89988}
89989#endif
89990
89991
89992/*
89993** This routine adds datatype and collating sequence information to
89994** the Table structures of all FROM-clause subqueries in a
89995** SELECT statement.
89996**
89997** Use this routine after name resolution.
89998*/
89999static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
90000#ifndef SQLITE_OMIT_SUBQUERY
90001  Walker w;
90002  w.xSelectCallback = selectAddSubqueryTypeInfo;
90003  w.xExprCallback = exprWalkNoop;
90004  w.pParse = pParse;
90005  sqlite3WalkSelect(&w, pSelect);
90006#endif
90007}
90008
90009
90010/*
90011** This routine sets of a SELECT statement for processing.  The
90012** following is accomplished:
90013**
90014**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
90015**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
90016**     *  ON and USING clauses are shifted into WHERE statements
90017**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
90018**     *  Identifiers in expression are matched to tables.
90019**
90020** This routine acts recursively on all subqueries within the SELECT.
90021*/
90022SQLITE_PRIVATE void sqlite3SelectPrep(
90023  Parse *pParse,         /* The parser context */
90024  Select *p,             /* The SELECT statement being coded. */
90025  NameContext *pOuterNC  /* Name context for container */
90026){
90027  sqlite3 *db;
90028  if( NEVER(p==0) ) return;
90029  db = pParse->db;
90030  if( p->selFlags & SF_HasTypeInfo ) return;
90031  sqlite3SelectExpand(pParse, p);
90032  if( pParse->nErr || db->mallocFailed ) return;
90033  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
90034  if( pParse->nErr || db->mallocFailed ) return;
90035  sqlite3SelectAddTypeInfo(pParse, p);
90036}
90037
90038/*
90039** Reset the aggregate accumulator.
90040**
90041** The aggregate accumulator is a set of memory cells that hold
90042** intermediate results while calculating an aggregate.  This
90043** routine simply stores NULLs in all of those memory cells.
90044*/
90045static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
90046  Vdbe *v = pParse->pVdbe;
90047  int i;
90048  struct AggInfo_func *pFunc;
90049  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
90050    return;
90051  }
90052  for(i=0; i<pAggInfo->nColumn; i++){
90053    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
90054  }
90055  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
90056    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
90057    if( pFunc->iDistinct>=0 ){
90058      Expr *pE = pFunc->pExpr;
90059      assert( !ExprHasProperty(pE, EP_xIsSelect) );
90060      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
90061        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
90062           "argument");
90063        pFunc->iDistinct = -1;
90064      }else{
90065        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
90066        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
90067                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90068      }
90069    }
90070  }
90071}
90072
90073/*
90074** Invoke the OP_AggFinalize opcode for every aggregate function
90075** in the AggInfo structure.
90076*/
90077static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
90078  Vdbe *v = pParse->pVdbe;
90079  int i;
90080  struct AggInfo_func *pF;
90081  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
90082    ExprList *pList = pF->pExpr->x.pList;
90083    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
90084    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
90085                      (void*)pF->pFunc, P4_FUNCDEF);
90086  }
90087}
90088
90089/*
90090** Update the accumulator memory cells for an aggregate based on
90091** the current cursor position.
90092*/
90093static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
90094  Vdbe *v = pParse->pVdbe;
90095  int i;
90096  struct AggInfo_func *pF;
90097  struct AggInfo_col *pC;
90098
90099  pAggInfo->directMode = 1;
90100  sqlite3ExprCacheClear(pParse);
90101  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
90102    int nArg;
90103    int addrNext = 0;
90104    int regAgg;
90105    ExprList *pList = pF->pExpr->x.pList;
90106    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
90107    if( pList ){
90108      nArg = pList->nExpr;
90109      regAgg = sqlite3GetTempRange(pParse, nArg);
90110      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
90111    }else{
90112      nArg = 0;
90113      regAgg = 0;
90114    }
90115    if( pF->iDistinct>=0 ){
90116      addrNext = sqlite3VdbeMakeLabel(v);
90117      assert( nArg==1 );
90118      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
90119    }
90120    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
90121      CollSeq *pColl = 0;
90122      struct ExprList_item *pItem;
90123      int j;
90124      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
90125      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
90126        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
90127      }
90128      if( !pColl ){
90129        pColl = pParse->db->pDfltColl;
90130      }
90131      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
90132    }
90133    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
90134                      (void*)pF->pFunc, P4_FUNCDEF);
90135    sqlite3VdbeChangeP5(v, (u8)nArg);
90136    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
90137    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
90138    if( addrNext ){
90139      sqlite3VdbeResolveLabel(v, addrNext);
90140      sqlite3ExprCacheClear(pParse);
90141    }
90142  }
90143
90144  /* Before populating the accumulator registers, clear the column cache.
90145  ** Otherwise, if any of the required column values are already present
90146  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
90147  ** to pC->iMem. But by the time the value is used, the original register
90148  ** may have been used, invalidating the underlying buffer holding the
90149  ** text or blob value. See ticket [883034dcb5].
90150  **
90151  ** Another solution would be to change the OP_SCopy used to copy cached
90152  ** values to an OP_Copy.
90153  */
90154  sqlite3ExprCacheClear(pParse);
90155  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
90156    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
90157  }
90158  pAggInfo->directMode = 0;
90159  sqlite3ExprCacheClear(pParse);
90160}
90161
90162/*
90163** Generate code for the SELECT statement given in the p argument.
90164**
90165** The results are distributed in various ways depending on the
90166** contents of the SelectDest structure pointed to by argument pDest
90167** as follows:
90168**
90169**     pDest->eDest    Result
90170**     ------------    -------------------------------------------
90171**     SRT_Output      Generate a row of output (using the OP_ResultRow
90172**                     opcode) for each row in the result set.
90173**
90174**     SRT_Mem         Only valid if the result is a single column.
90175**                     Store the first column of the first result row
90176**                     in register pDest->iParm then abandon the rest
90177**                     of the query.  This destination implies "LIMIT 1".
90178**
90179**     SRT_Set         The result must be a single column.  Store each
90180**                     row of result as the key in table pDest->iParm.
90181**                     Apply the affinity pDest->affinity before storing
90182**                     results.  Used to implement "IN (SELECT ...)".
90183**
90184**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
90185**
90186**     SRT_Except      Remove results from the temporary table pDest->iParm.
90187**
90188**     SRT_Table       Store results in temporary table pDest->iParm.
90189**                     This is like SRT_EphemTab except that the table
90190**                     is assumed to already be open.
90191**
90192**     SRT_EphemTab    Create an temporary table pDest->iParm and store
90193**                     the result there. The cursor is left open after
90194**                     returning.  This is like SRT_Table except that
90195**                     this destination uses OP_OpenEphemeral to create
90196**                     the table first.
90197**
90198**     SRT_Coroutine   Generate a co-routine that returns a new row of
90199**                     results each time it is invoked.  The entry point
90200**                     of the co-routine is stored in register pDest->iParm.
90201**
90202**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
90203**                     set is not empty.
90204**
90205**     SRT_Discard     Throw the results away.  This is used by SELECT
90206**                     statements within triggers whose only purpose is
90207**                     the side-effects of functions.
90208**
90209** This routine returns the number of errors.  If any errors are
90210** encountered, then an appropriate error message is left in
90211** pParse->zErrMsg.
90212**
90213** This routine does NOT free the Select structure passed in.  The
90214** calling function needs to do that.
90215*/
90216SQLITE_PRIVATE int sqlite3Select(
90217  Parse *pParse,         /* The parser context */
90218  Select *p,             /* The SELECT statement being coded. */
90219  SelectDest *pDest      /* What to do with the query results */
90220){
90221  int i, j;              /* Loop counters */
90222  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
90223  Vdbe *v;               /* The virtual machine under construction */
90224  int isAgg;             /* True for select lists like "count(*)" */
90225  ExprList *pEList;      /* List of columns to extract. */
90226  SrcList *pTabList;     /* List of tables to select from */
90227  Expr *pWhere;          /* The WHERE clause.  May be NULL */
90228  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
90229  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
90230  Expr *pHaving;         /* The HAVING clause.  May be NULL */
90231  int isDistinct;        /* True if the DISTINCT keyword is present */
90232  int distinct;          /* Table to use for the distinct set */
90233  int rc = 1;            /* Value to return from this function */
90234  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
90235  AggInfo sAggInfo;      /* Information used by aggregate queries */
90236  int iEnd;              /* Address of the end of the query */
90237  sqlite3 *db;           /* The database connection */
90238
90239  db = pParse->db;
90240  if( p==0 || db->mallocFailed || pParse->nErr ){
90241    return 1;
90242  }
90243  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
90244  memset(&sAggInfo, 0, sizeof(sAggInfo));
90245
90246  if( IgnorableOrderby(pDest) ){
90247    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
90248           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
90249    /* If ORDER BY makes no difference in the output then neither does
90250    ** DISTINCT so it can be removed too. */
90251    sqlite3ExprListDelete(db, p->pOrderBy);
90252    p->pOrderBy = 0;
90253    p->selFlags &= ~SF_Distinct;
90254  }
90255  sqlite3SelectPrep(pParse, p, 0);
90256  pOrderBy = p->pOrderBy;
90257  pTabList = p->pSrc;
90258  pEList = p->pEList;
90259  if( pParse->nErr || db->mallocFailed ){
90260    goto select_end;
90261  }
90262  isAgg = (p->selFlags & SF_Aggregate)!=0;
90263  assert( pEList!=0 );
90264
90265  /* Begin generating code.
90266  */
90267  v = sqlite3GetVdbe(pParse);
90268  if( v==0 ) goto select_end;
90269
90270  /* Generate code for all sub-queries in the FROM clause
90271  */
90272#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90273  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
90274    struct SrcList_item *pItem = &pTabList->a[i];
90275    SelectDest dest;
90276    Select *pSub = pItem->pSelect;
90277    int isAggSub;
90278
90279    if( pSub==0 || pItem->isPopulated ) continue;
90280
90281    /* Increment Parse.nHeight by the height of the largest expression
90282    ** tree refered to by this, the parent select. The child select
90283    ** may contain expression trees of at most
90284    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
90285    ** more conservative than necessary, but much easier than enforcing
90286    ** an exact limit.
90287    */
90288    pParse->nHeight += sqlite3SelectExprHeight(p);
90289
90290    /* Check to see if the subquery can be absorbed into the parent. */
90291    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
90292    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
90293      if( isAggSub ){
90294        isAgg = 1;
90295        p->selFlags |= SF_Aggregate;
90296      }
90297      i = -1;
90298    }else{
90299      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
90300      assert( pItem->isPopulated==0 );
90301      sqlite3Select(pParse, pSub, &dest);
90302      pItem->isPopulated = 1;
90303    }
90304    if( /*pParse->nErr ||*/ db->mallocFailed ){
90305      goto select_end;
90306    }
90307    pParse->nHeight -= sqlite3SelectExprHeight(p);
90308    pTabList = p->pSrc;
90309    if( !IgnorableOrderby(pDest) ){
90310      pOrderBy = p->pOrderBy;
90311    }
90312  }
90313  pEList = p->pEList;
90314#endif
90315  pWhere = p->pWhere;
90316  pGroupBy = p->pGroupBy;
90317  pHaving = p->pHaving;
90318  isDistinct = (p->selFlags & SF_Distinct)!=0;
90319
90320#ifndef SQLITE_OMIT_COMPOUND_SELECT
90321  /* If there is are a sequence of queries, do the earlier ones first.
90322  */
90323  if( p->pPrior ){
90324    if( p->pRightmost==0 ){
90325      Select *pLoop, *pRight = 0;
90326      int cnt = 0;
90327      int mxSelect;
90328      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
90329        pLoop->pRightmost = p;
90330        pLoop->pNext = pRight;
90331        pRight = pLoop;
90332      }
90333      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
90334      if( mxSelect && cnt>mxSelect ){
90335        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
90336        return 1;
90337      }
90338    }
90339    return multiSelect(pParse, p, pDest);
90340  }
90341#endif
90342
90343  /* If writing to memory or generating a set
90344  ** only a single column may be output.
90345  */
90346#ifndef SQLITE_OMIT_SUBQUERY
90347  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
90348    goto select_end;
90349  }
90350#endif
90351
90352  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
90353  ** GROUP BY might use an index, DISTINCT never does.
90354  */
90355  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
90356  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
90357    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
90358    pGroupBy = p->pGroupBy;
90359    p->selFlags &= ~SF_Distinct;
90360    isDistinct = 0;
90361  }
90362
90363  /* If there is both a GROUP BY and an ORDER BY clause and they are
90364  ** identical, then disable the ORDER BY clause since the GROUP BY
90365  ** will cause elements to come out in the correct order.  This is
90366  ** an optimization - the correct answer should result regardless.
90367  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
90368  ** to disable this optimization for testing purposes.
90369  */
90370  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
90371         && (db->flags & SQLITE_GroupByOrder)==0 ){
90372    pOrderBy = 0;
90373  }
90374
90375  /* If there is an ORDER BY clause, then this sorting
90376  ** index might end up being unused if the data can be
90377  ** extracted in pre-sorted order.  If that is the case, then the
90378  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
90379  ** we figure out that the sorting index is not needed.  The addrSortIndex
90380  ** variable is used to facilitate that change.
90381  */
90382  if( pOrderBy ){
90383    KeyInfo *pKeyInfo;
90384    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
90385    pOrderBy->iECursor = pParse->nTab++;
90386    p->addrOpenEphm[2] = addrSortIndex =
90387      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
90388                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
90389                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90390  }else{
90391    addrSortIndex = -1;
90392  }
90393
90394  /* If the output is destined for a temporary table, open that table.
90395  */
90396  if( pDest->eDest==SRT_EphemTab ){
90397    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
90398  }
90399
90400  /* Set the limiter.
90401  */
90402  iEnd = sqlite3VdbeMakeLabel(v);
90403  computeLimitRegisters(pParse, p, iEnd);
90404
90405  /* Open a virtual index to use for the distinct set.
90406  */
90407  if( isDistinct ){
90408    KeyInfo *pKeyInfo;
90409    assert( isAgg || pGroupBy );
90410    distinct = pParse->nTab++;
90411    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
90412    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
90413                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90414  }else{
90415    distinct = -1;
90416  }
90417
90418  /* Aggregate and non-aggregate queries are handled differently */
90419  if( !isAgg && pGroupBy==0 ){
90420    /* This case is for non-aggregate queries
90421    ** Begin the database scan
90422    */
90423    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
90424    if( pWInfo==0 ) goto select_end;
90425
90426    /* If sorting index that was created by a prior OP_OpenEphemeral
90427    ** instruction ended up not being needed, then change the OP_OpenEphemeral
90428    ** into an OP_Noop.
90429    */
90430    if( addrSortIndex>=0 && pOrderBy==0 ){
90431      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
90432      p->addrOpenEphm[2] = -1;
90433    }
90434
90435    /* Use the standard inner loop
90436    */
90437    assert(!isDistinct);
90438    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
90439                    pWInfo->iContinue, pWInfo->iBreak);
90440
90441    /* End the database scan loop.
90442    */
90443    sqlite3WhereEnd(pWInfo);
90444  }else{
90445    /* This is the processing for aggregate queries */
90446    NameContext sNC;    /* Name context for processing aggregate information */
90447    int iAMem;          /* First Mem address for storing current GROUP BY */
90448    int iBMem;          /* First Mem address for previous GROUP BY */
90449    int iUseFlag;       /* Mem address holding flag indicating that at least
90450                        ** one row of the input to the aggregator has been
90451                        ** processed */
90452    int iAbortFlag;     /* Mem address which causes query abort if positive */
90453    int groupBySort;    /* Rows come from source in GROUP BY order */
90454    int addrEnd;        /* End of processing for this SELECT */
90455
90456    /* Remove any and all aliases between the result set and the
90457    ** GROUP BY clause.
90458    */
90459    if( pGroupBy ){
90460      int k;                        /* Loop counter */
90461      struct ExprList_item *pItem;  /* For looping over expression in a list */
90462
90463      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
90464        pItem->iAlias = 0;
90465      }
90466      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
90467        pItem->iAlias = 0;
90468      }
90469    }
90470
90471
90472    /* Create a label to jump to when we want to abort the query */
90473    addrEnd = sqlite3VdbeMakeLabel(v);
90474
90475    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
90476    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
90477    ** SELECT statement.
90478    */
90479    memset(&sNC, 0, sizeof(sNC));
90480    sNC.pParse = pParse;
90481    sNC.pSrcList = pTabList;
90482    sNC.pAggInfo = &sAggInfo;
90483    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
90484    sAggInfo.pGroupBy = pGroupBy;
90485    sqlite3ExprAnalyzeAggList(&sNC, pEList);
90486    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
90487    if( pHaving ){
90488      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
90489    }
90490    sAggInfo.nAccumulator = sAggInfo.nColumn;
90491    for(i=0; i<sAggInfo.nFunc; i++){
90492      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
90493      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
90494    }
90495    if( db->mallocFailed ) goto select_end;
90496
90497    /* Processing for aggregates with GROUP BY is very different and
90498    ** much more complex than aggregates without a GROUP BY.
90499    */
90500    if( pGroupBy ){
90501      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
90502      int j1;             /* A-vs-B comparision jump */
90503      int addrOutputRow;  /* Start of subroutine that outputs a result row */
90504      int regOutputRow;   /* Return address register for output subroutine */
90505      int addrSetAbort;   /* Set the abort flag and return */
90506      int addrTopOfLoop;  /* Top of the input loop */
90507      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
90508      int addrReset;      /* Subroutine for resetting the accumulator */
90509      int regReset;       /* Return address register for reset subroutine */
90510
90511      /* If there is a GROUP BY clause we might need a sorting index to
90512      ** implement it.  Allocate that sorting index now.  If it turns out
90513      ** that we do not need it after all, the OpenEphemeral instruction
90514      ** will be converted into a Noop.
90515      */
90516      sAggInfo.sortingIdx = pParse->nTab++;
90517      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
90518      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
90519          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
90520          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
90521
90522      /* Initialize memory locations used by GROUP BY aggregate processing
90523      */
90524      iUseFlag = ++pParse->nMem;
90525      iAbortFlag = ++pParse->nMem;
90526      regOutputRow = ++pParse->nMem;
90527      addrOutputRow = sqlite3VdbeMakeLabel(v);
90528      regReset = ++pParse->nMem;
90529      addrReset = sqlite3VdbeMakeLabel(v);
90530      iAMem = pParse->nMem + 1;
90531      pParse->nMem += pGroupBy->nExpr;
90532      iBMem = pParse->nMem + 1;
90533      pParse->nMem += pGroupBy->nExpr;
90534      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
90535      VdbeComment((v, "clear abort flag"));
90536      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
90537      VdbeComment((v, "indicate accumulator empty"));
90538
90539      /* Begin a loop that will extract all source rows in GROUP BY order.
90540      ** This might involve two separate loops with an OP_Sort in between, or
90541      ** it might be a single loop that uses an index to extract information
90542      ** in the right order to begin with.
90543      */
90544      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
90545      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
90546      if( pWInfo==0 ) goto select_end;
90547      if( pGroupBy==0 ){
90548        /* The optimizer is able to deliver rows in group by order so
90549        ** we do not have to sort.  The OP_OpenEphemeral table will be
90550        ** cancelled later because we still need to use the pKeyInfo
90551        */
90552        pGroupBy = p->pGroupBy;
90553        groupBySort = 0;
90554      }else{
90555        /* Rows are coming out in undetermined order.  We have to push
90556        ** each row into a sorting index, terminate the first loop,
90557        ** then loop over the sorting index in order to get the output
90558        ** in sorted order
90559        */
90560        int regBase;
90561        int regRecord;
90562        int nCol;
90563        int nGroupBy;
90564
90565        groupBySort = 1;
90566        nGroupBy = pGroupBy->nExpr;
90567        nCol = nGroupBy + 1;
90568        j = nGroupBy+1;
90569        for(i=0; i<sAggInfo.nColumn; i++){
90570          if( sAggInfo.aCol[i].iSorterColumn>=j ){
90571            nCol++;
90572            j++;
90573          }
90574        }
90575        regBase = sqlite3GetTempRange(pParse, nCol);
90576        sqlite3ExprCacheClear(pParse);
90577        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
90578        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
90579        j = nGroupBy+1;
90580        for(i=0; i<sAggInfo.nColumn; i++){
90581          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
90582          if( pCol->iSorterColumn>=j ){
90583            int r1 = j + regBase;
90584            int r2;
90585
90586            r2 = sqlite3ExprCodeGetColumn(pParse,
90587                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
90588            if( r1!=r2 ){
90589              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
90590            }
90591            j++;
90592          }
90593        }
90594        regRecord = sqlite3GetTempReg(pParse);
90595        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
90596        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
90597        sqlite3ReleaseTempReg(pParse, regRecord);
90598        sqlite3ReleaseTempRange(pParse, regBase, nCol);
90599        sqlite3WhereEnd(pWInfo);
90600        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
90601        VdbeComment((v, "GROUP BY sort"));
90602        sAggInfo.useSortingIdx = 1;
90603        sqlite3ExprCacheClear(pParse);
90604      }
90605
90606      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
90607      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
90608      ** Then compare the current GROUP BY terms against the GROUP BY terms
90609      ** from the previous row currently stored in a0, a1, a2...
90610      */
90611      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
90612      sqlite3ExprCacheClear(pParse);
90613      for(j=0; j<pGroupBy->nExpr; j++){
90614        if( groupBySort ){
90615          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
90616        }else{
90617          sAggInfo.directMode = 1;
90618          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
90619        }
90620      }
90621      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
90622                          (char*)pKeyInfo, P4_KEYINFO);
90623      j1 = sqlite3VdbeCurrentAddr(v);
90624      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
90625
90626      /* Generate code that runs whenever the GROUP BY changes.
90627      ** Changes in the GROUP BY are detected by the previous code
90628      ** block.  If there were no changes, this block is skipped.
90629      **
90630      ** This code copies current group by terms in b0,b1,b2,...
90631      ** over to a0,a1,a2.  It then calls the output subroutine
90632      ** and resets the aggregate accumulator registers in preparation
90633      ** for the next GROUP BY batch.
90634      */
90635      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
90636      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
90637      VdbeComment((v, "output one row"));
90638      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
90639      VdbeComment((v, "check abort flag"));
90640      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
90641      VdbeComment((v, "reset accumulator"));
90642
90643      /* Update the aggregate accumulators based on the content of
90644      ** the current row
90645      */
90646      sqlite3VdbeJumpHere(v, j1);
90647      updateAccumulator(pParse, &sAggInfo);
90648      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
90649      VdbeComment((v, "indicate data in accumulator"));
90650
90651      /* End of the loop
90652      */
90653      if( groupBySort ){
90654        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
90655      }else{
90656        sqlite3WhereEnd(pWInfo);
90657        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
90658      }
90659
90660      /* Output the final row of result
90661      */
90662      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
90663      VdbeComment((v, "output final row"));
90664
90665      /* Jump over the subroutines
90666      */
90667      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
90668
90669      /* Generate a subroutine that outputs a single row of the result
90670      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
90671      ** is less than or equal to zero, the subroutine is a no-op.  If
90672      ** the processing calls for the query to abort, this subroutine
90673      ** increments the iAbortFlag memory location before returning in
90674      ** order to signal the caller to abort.
90675      */
90676      addrSetAbort = sqlite3VdbeCurrentAddr(v);
90677      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
90678      VdbeComment((v, "set abort flag"));
90679      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
90680      sqlite3VdbeResolveLabel(v, addrOutputRow);
90681      addrOutputRow = sqlite3VdbeCurrentAddr(v);
90682      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
90683      VdbeComment((v, "Groupby result generator entry point"));
90684      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
90685      finalizeAggFunctions(pParse, &sAggInfo);
90686      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
90687      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
90688                      distinct, pDest,
90689                      addrOutputRow+1, addrSetAbort);
90690      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
90691      VdbeComment((v, "end groupby result generator"));
90692
90693      /* Generate a subroutine that will reset the group-by accumulator
90694      */
90695      sqlite3VdbeResolveLabel(v, addrReset);
90696      resetAccumulator(pParse, &sAggInfo);
90697      sqlite3VdbeAddOp1(v, OP_Return, regReset);
90698
90699    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
90700    else {
90701      ExprList *pDel = 0;
90702#ifndef SQLITE_OMIT_BTREECOUNT
90703      Table *pTab;
90704      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
90705        /* If isSimpleCount() returns a pointer to a Table structure, then
90706        ** the SQL statement is of the form:
90707        **
90708        **   SELECT count(*) FROM <tbl>
90709        **
90710        ** where the Table structure returned represents table <tbl>.
90711        **
90712        ** This statement is so common that it is optimized specially. The
90713        ** OP_Count instruction is executed either on the intkey table that
90714        ** contains the data for table <tbl> or on one of its indexes. It
90715        ** is better to execute the op on an index, as indexes are almost
90716        ** always spread across less pages than their corresponding tables.
90717        */
90718        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90719        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
90720        Index *pIdx;                         /* Iterator variable */
90721        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
90722        Index *pBest = 0;                    /* Best index found so far */
90723        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
90724
90725        sqlite3CodeVerifySchema(pParse, iDb);
90726        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90727
90728        /* Search for the index that has the least amount of columns. If
90729        ** there is such an index, and it has less columns than the table
90730        ** does, then we can assume that it consumes less space on disk and
90731        ** will therefore be cheaper to scan to determine the query result.
90732        ** In this case set iRoot to the root page number of the index b-tree
90733        ** and pKeyInfo to the KeyInfo structure required to navigate the
90734        ** index.
90735        **
90736        ** In practice the KeyInfo structure will not be used. It is only
90737        ** passed to keep OP_OpenRead happy.
90738        */
90739        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90740          if( !pBest || pIdx->nColumn<pBest->nColumn ){
90741            pBest = pIdx;
90742          }
90743        }
90744        if( pBest && pBest->nColumn<pTab->nCol ){
90745          iRoot = pBest->tnum;
90746          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
90747        }
90748
90749        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
90750        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
90751        if( pKeyInfo ){
90752          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
90753        }
90754        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
90755        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
90756      }else
90757#endif /* SQLITE_OMIT_BTREECOUNT */
90758      {
90759        /* Check if the query is of one of the following forms:
90760        **
90761        **   SELECT min(x) FROM ...
90762        **   SELECT max(x) FROM ...
90763        **
90764        ** If it is, then ask the code in where.c to attempt to sort results
90765        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
90766        ** If where.c is able to produce results sorted in this order, then
90767        ** add vdbe code to break out of the processing loop after the
90768        ** first iteration (since the first iteration of the loop is
90769        ** guaranteed to operate on the row with the minimum or maximum
90770        ** value of x, the only row required).
90771        **
90772        ** A special flag must be passed to sqlite3WhereBegin() to slightly
90773        ** modify behaviour as follows:
90774        **
90775        **   + If the query is a "SELECT min(x)", then the loop coded by
90776        **     where.c should not iterate over any values with a NULL value
90777        **     for x.
90778        **
90779        **   + The optimizer code in where.c (the thing that decides which
90780        **     index or indices to use) should place a different priority on
90781        **     satisfying the 'ORDER BY' clause than it does in other cases.
90782        **     Refer to code and comments in where.c for details.
90783        */
90784        ExprList *pMinMax = 0;
90785        u8 flag = minMaxQuery(p);
90786        if( flag ){
90787          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
90788          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
90789          pDel = pMinMax;
90790          if( pMinMax && !db->mallocFailed ){
90791            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
90792            pMinMax->a[0].pExpr->op = TK_COLUMN;
90793          }
90794        }
90795
90796        /* This case runs if the aggregate has no GROUP BY clause.  The
90797        ** processing is much simpler since there is only a single row
90798        ** of output.
90799        */
90800        resetAccumulator(pParse, &sAggInfo);
90801        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
90802        if( pWInfo==0 ){
90803          sqlite3ExprListDelete(db, pDel);
90804          goto select_end;
90805        }
90806        updateAccumulator(pParse, &sAggInfo);
90807        if( !pMinMax && flag ){
90808          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
90809          VdbeComment((v, "%s() by index",
90810                (flag==WHERE_ORDERBY_MIN?"min":"max")));
90811        }
90812        sqlite3WhereEnd(pWInfo);
90813        finalizeAggFunctions(pParse, &sAggInfo);
90814      }
90815
90816      pOrderBy = 0;
90817      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
90818      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
90819                      pDest, addrEnd, addrEnd);
90820      sqlite3ExprListDelete(db, pDel);
90821    }
90822    sqlite3VdbeResolveLabel(v, addrEnd);
90823
90824  } /* endif aggregate query */
90825
90826  /* If there is an ORDER BY clause, then we need to sort the results
90827  ** and send them to the callback one by one.
90828  */
90829  if( pOrderBy ){
90830    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
90831  }
90832
90833  /* Jump here to skip this query
90834  */
90835  sqlite3VdbeResolveLabel(v, iEnd);
90836
90837  /* The SELECT was successfully coded.   Set the return code to 0
90838  ** to indicate no errors.
90839  */
90840  rc = 0;
90841
90842  /* Control jumps to here if an error is encountered above, or upon
90843  ** successful coding of the SELECT.
90844  */
90845select_end:
90846
90847  /* Identify column names if results of the SELECT are to be output.
90848  */
90849  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
90850    generateColumnNames(pParse, pTabList, pEList);
90851  }
90852
90853  sqlite3DbFree(db, sAggInfo.aCol);
90854  sqlite3DbFree(db, sAggInfo.aFunc);
90855  return rc;
90856}
90857
90858#if defined(SQLITE_DEBUG)
90859/*
90860*******************************************************************************
90861** The following code is used for testing and debugging only.  The code
90862** that follows does not appear in normal builds.
90863**
90864** These routines are used to print out the content of all or part of a
90865** parse structures such as Select or Expr.  Such printouts are useful
90866** for helping to understand what is happening inside the code generator
90867** during the execution of complex SELECT statements.
90868**
90869** These routine are not called anywhere from within the normal
90870** code base.  Then are intended to be called from within the debugger
90871** or from temporary "printf" statements inserted for debugging.
90872*/
90873SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
90874  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90875    sqlite3DebugPrintf("(%s", p->u.zToken);
90876  }else{
90877    sqlite3DebugPrintf("(%d", p->op);
90878  }
90879  if( p->pLeft ){
90880    sqlite3DebugPrintf(" ");
90881    sqlite3PrintExpr(p->pLeft);
90882  }
90883  if( p->pRight ){
90884    sqlite3DebugPrintf(" ");
90885    sqlite3PrintExpr(p->pRight);
90886  }
90887  sqlite3DebugPrintf(")");
90888}
90889SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
90890  int i;
90891  for(i=0; i<pList->nExpr; i++){
90892    sqlite3PrintExpr(pList->a[i].pExpr);
90893    if( i<pList->nExpr-1 ){
90894      sqlite3DebugPrintf(", ");
90895    }
90896  }
90897}
90898SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
90899  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
90900  sqlite3PrintExprList(p->pEList);
90901  sqlite3DebugPrintf("\n");
90902  if( p->pSrc ){
90903    char *zPrefix;
90904    int i;
90905    zPrefix = "FROM";
90906    for(i=0; i<p->pSrc->nSrc; i++){
90907      struct SrcList_item *pItem = &p->pSrc->a[i];
90908      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
90909      zPrefix = "";
90910      if( pItem->pSelect ){
90911        sqlite3DebugPrintf("(\n");
90912        sqlite3PrintSelect(pItem->pSelect, indent+10);
90913        sqlite3DebugPrintf("%*s)", indent+8, "");
90914      }else if( pItem->zName ){
90915        sqlite3DebugPrintf("%s", pItem->zName);
90916      }
90917      if( pItem->pTab ){
90918        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
90919      }
90920      if( pItem->zAlias ){
90921        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
90922      }
90923      if( i<p->pSrc->nSrc-1 ){
90924        sqlite3DebugPrintf(",");
90925      }
90926      sqlite3DebugPrintf("\n");
90927    }
90928  }
90929  if( p->pWhere ){
90930    sqlite3DebugPrintf("%*s WHERE ", indent, "");
90931    sqlite3PrintExpr(p->pWhere);
90932    sqlite3DebugPrintf("\n");
90933  }
90934  if( p->pGroupBy ){
90935    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
90936    sqlite3PrintExprList(p->pGroupBy);
90937    sqlite3DebugPrintf("\n");
90938  }
90939  if( p->pHaving ){
90940    sqlite3DebugPrintf("%*s HAVING ", indent, "");
90941    sqlite3PrintExpr(p->pHaving);
90942    sqlite3DebugPrintf("\n");
90943  }
90944  if( p->pOrderBy ){
90945    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
90946    sqlite3PrintExprList(p->pOrderBy);
90947    sqlite3DebugPrintf("\n");
90948  }
90949}
90950/* End of the structure debug printing code
90951*****************************************************************************/
90952#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
90953
90954/************** End of select.c **********************************************/
90955/************** Begin file table.c *******************************************/
90956/*
90957** 2001 September 15
90958**
90959** The author disclaims copyright to this source code.  In place of
90960** a legal notice, here is a blessing:
90961**
90962**    May you do good and not evil.
90963**    May you find forgiveness for yourself and forgive others.
90964**    May you share freely, never taking more than you give.
90965**
90966*************************************************************************
90967** This file contains the sqlite3_get_table() and sqlite3_free_table()
90968** interface routines.  These are just wrappers around the main
90969** interface routine of sqlite3_exec().
90970**
90971** These routines are in a separate files so that they will not be linked
90972** if they are not used.
90973*/
90974
90975#ifndef SQLITE_OMIT_GET_TABLE
90976
90977/*
90978** This structure is used to pass data from sqlite3_get_table() through
90979** to the callback function is uses to build the result.
90980*/
90981typedef struct TabResult {
90982  char **azResult;   /* Accumulated output */
90983  char *zErrMsg;     /* Error message text, if an error occurs */
90984  int nAlloc;        /* Slots allocated for azResult[] */
90985  int nRow;          /* Number of rows in the result */
90986  int nColumn;       /* Number of columns in the result */
90987  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
90988  int rc;            /* Return code from sqlite3_exec() */
90989} TabResult;
90990
90991/*
90992** This routine is called once for each row in the result table.  Its job
90993** is to fill in the TabResult structure appropriately, allocating new
90994** memory as necessary.
90995*/
90996static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
90997  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
90998  int need;                         /* Slots needed in p->azResult[] */
90999  int i;                            /* Loop counter */
91000  char *z;                          /* A single column of result */
91001
91002  /* Make sure there is enough space in p->azResult to hold everything
91003  ** we need to remember from this invocation of the callback.
91004  */
91005  if( p->nRow==0 && argv!=0 ){
91006    need = nCol*2;
91007  }else{
91008    need = nCol;
91009  }
91010  if( p->nData + need > p->nAlloc ){
91011    char **azNew;
91012    p->nAlloc = p->nAlloc*2 + need;
91013    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
91014    if( azNew==0 ) goto malloc_failed;
91015    p->azResult = azNew;
91016  }
91017
91018  /* If this is the first row, then generate an extra row containing
91019  ** the names of all columns.
91020  */
91021  if( p->nRow==0 ){
91022    p->nColumn = nCol;
91023    for(i=0; i<nCol; i++){
91024      z = sqlite3_mprintf("%s", colv[i]);
91025      if( z==0 ) goto malloc_failed;
91026      p->azResult[p->nData++] = z;
91027    }
91028  }else if( p->nColumn!=nCol ){
91029    sqlite3_free(p->zErrMsg);
91030    p->zErrMsg = sqlite3_mprintf(
91031       "sqlite3_get_table() called with two or more incompatible queries"
91032    );
91033    p->rc = SQLITE_ERROR;
91034    return 1;
91035  }
91036
91037  /* Copy over the row data
91038  */
91039  if( argv!=0 ){
91040    for(i=0; i<nCol; i++){
91041      if( argv[i]==0 ){
91042        z = 0;
91043      }else{
91044        int n = sqlite3Strlen30(argv[i])+1;
91045        z = sqlite3_malloc( n );
91046        if( z==0 ) goto malloc_failed;
91047        memcpy(z, argv[i], n);
91048      }
91049      p->azResult[p->nData++] = z;
91050    }
91051    p->nRow++;
91052  }
91053  return 0;
91054
91055malloc_failed:
91056  p->rc = SQLITE_NOMEM;
91057  return 1;
91058}
91059
91060/*
91061** Query the database.  But instead of invoking a callback for each row,
91062** malloc() for space to hold the result and return the entire results
91063** at the conclusion of the call.
91064**
91065** The result that is written to ***pazResult is held in memory obtained
91066** from malloc().  But the caller cannot free this memory directly.
91067** Instead, the entire table should be passed to sqlite3_free_table() when
91068** the calling procedure is finished using it.
91069*/
91070SQLITE_API int sqlite3_get_table(
91071  sqlite3 *db,                /* The database on which the SQL executes */
91072  const char *zSql,           /* The SQL to be executed */
91073  char ***pazResult,          /* Write the result table here */
91074  int *pnRow,                 /* Write the number of rows in the result here */
91075  int *pnColumn,              /* Write the number of columns of result here */
91076  char **pzErrMsg             /* Write error messages here */
91077){
91078  int rc;
91079  TabResult res;
91080
91081  *pazResult = 0;
91082  if( pnColumn ) *pnColumn = 0;
91083  if( pnRow ) *pnRow = 0;
91084  if( pzErrMsg ) *pzErrMsg = 0;
91085  res.zErrMsg = 0;
91086  res.nRow = 0;
91087  res.nColumn = 0;
91088  res.nData = 1;
91089  res.nAlloc = 20;
91090  res.rc = SQLITE_OK;
91091  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
91092  if( res.azResult==0 ){
91093     db->errCode = SQLITE_NOMEM;
91094     return SQLITE_NOMEM;
91095  }
91096  res.azResult[0] = 0;
91097  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
91098  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
91099  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
91100  if( (rc&0xff)==SQLITE_ABORT ){
91101    sqlite3_free_table(&res.azResult[1]);
91102    if( res.zErrMsg ){
91103      if( pzErrMsg ){
91104        sqlite3_free(*pzErrMsg);
91105        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
91106      }
91107      sqlite3_free(res.zErrMsg);
91108    }
91109    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
91110    return res.rc;
91111  }
91112  sqlite3_free(res.zErrMsg);
91113  if( rc!=SQLITE_OK ){
91114    sqlite3_free_table(&res.azResult[1]);
91115    return rc;
91116  }
91117  if( res.nAlloc>res.nData ){
91118    char **azNew;
91119    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
91120    if( azNew==0 ){
91121      sqlite3_free_table(&res.azResult[1]);
91122      db->errCode = SQLITE_NOMEM;
91123      return SQLITE_NOMEM;
91124    }
91125    res.azResult = azNew;
91126  }
91127  *pazResult = &res.azResult[1];
91128  if( pnColumn ) *pnColumn = res.nColumn;
91129  if( pnRow ) *pnRow = res.nRow;
91130  return rc;
91131}
91132
91133/*
91134** This routine frees the space the sqlite3_get_table() malloced.
91135*/
91136SQLITE_API void sqlite3_free_table(
91137  char **azResult            /* Result returned from from sqlite3_get_table() */
91138){
91139  if( azResult ){
91140    int i, n;
91141    azResult--;
91142    assert( azResult!=0 );
91143    n = SQLITE_PTR_TO_INT(azResult[0]);
91144    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
91145    sqlite3_free(azResult);
91146  }
91147}
91148
91149#endif /* SQLITE_OMIT_GET_TABLE */
91150
91151/************** End of table.c ***********************************************/
91152/************** Begin file trigger.c *****************************************/
91153/*
91154**
91155** The author disclaims copyright to this source code.  In place of
91156** a legal notice, here is a blessing:
91157**
91158**    May you do good and not evil.
91159**    May you find forgiveness for yourself and forgive others.
91160**    May you share freely, never taking more than you give.
91161**
91162*************************************************************************
91163** This file contains the implementation for TRIGGERs
91164*/
91165
91166#ifndef SQLITE_OMIT_TRIGGER
91167/*
91168** Delete a linked list of TriggerStep structures.
91169*/
91170SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
91171  while( pTriggerStep ){
91172    TriggerStep * pTmp = pTriggerStep;
91173    pTriggerStep = pTriggerStep->pNext;
91174
91175    sqlite3ExprDelete(db, pTmp->pWhere);
91176    sqlite3ExprListDelete(db, pTmp->pExprList);
91177    sqlite3SelectDelete(db, pTmp->pSelect);
91178    sqlite3IdListDelete(db, pTmp->pIdList);
91179
91180    sqlite3DbFree(db, pTmp);
91181  }
91182}
91183
91184/*
91185** Given table pTab, return a list of all the triggers attached to
91186** the table. The list is connected by Trigger.pNext pointers.
91187**
91188** All of the triggers on pTab that are in the same database as pTab
91189** are already attached to pTab->pTrigger.  But there might be additional
91190** triggers on pTab in the TEMP schema.  This routine prepends all
91191** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
91192** and returns the combined list.
91193**
91194** To state it another way:  This routine returns a list of all triggers
91195** that fire off of pTab.  The list will include any TEMP triggers on
91196** pTab as well as the triggers lised in pTab->pTrigger.
91197*/
91198SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
91199  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
91200  Trigger *pList = 0;                  /* List of triggers to return */
91201
91202  if( pParse->disableTriggers ){
91203    return 0;
91204  }
91205
91206  if( pTmpSchema!=pTab->pSchema ){
91207    HashElem *p;
91208    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
91209      Trigger *pTrig = (Trigger *)sqliteHashData(p);
91210      if( pTrig->pTabSchema==pTab->pSchema
91211       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
91212      ){
91213        pTrig->pNext = (pList ? pList : pTab->pTrigger);
91214        pList = pTrig;
91215      }
91216    }
91217  }
91218
91219  return (pList ? pList : pTab->pTrigger);
91220}
91221
91222/*
91223** This is called by the parser when it sees a CREATE TRIGGER statement
91224** up to the point of the BEGIN before the trigger actions.  A Trigger
91225** structure is generated based on the information available and stored
91226** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
91227** sqlite3FinishTrigger() function is called to complete the trigger
91228** construction process.
91229*/
91230SQLITE_PRIVATE void sqlite3BeginTrigger(
91231  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
91232  Token *pName1,      /* The name of the trigger */
91233  Token *pName2,      /* The name of the trigger */
91234  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
91235  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
91236  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
91237  SrcList *pTableName,/* The name of the table/view the trigger applies to */
91238  Expr *pWhen,        /* WHEN clause */
91239  int isTemp,         /* True if the TEMPORARY keyword is present */
91240  int noErr           /* Suppress errors if the trigger already exists */
91241){
91242  Trigger *pTrigger = 0;  /* The new trigger */
91243  Table *pTab;            /* Table that the trigger fires off of */
91244  char *zName = 0;        /* Name of the trigger */
91245  sqlite3 *db = pParse->db;  /* The database connection */
91246  int iDb;                /* The database to store the trigger in */
91247  Token *pName;           /* The unqualified db name */
91248  DbFixer sFix;           /* State vector for the DB fixer */
91249  int iTabDb;             /* Index of the database holding pTab */
91250
91251  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
91252  assert( pName2!=0 );
91253  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
91254  assert( op>0 && op<0xff );
91255  if( isTemp ){
91256    /* If TEMP was specified, then the trigger name may not be qualified. */
91257    if( pName2->n>0 ){
91258      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
91259      goto trigger_cleanup;
91260    }
91261    iDb = 1;
91262    pName = pName1;
91263  }else{
91264    /* Figure out the db that the the trigger will be created in */
91265    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91266    if( iDb<0 ){
91267      goto trigger_cleanup;
91268    }
91269  }
91270
91271  /* If the trigger name was unqualified, and the table is a temp table,
91272  ** then set iDb to 1 to create the trigger in the temporary database.
91273  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
91274  ** exist, the error is caught by the block below.
91275  */
91276  if( !pTableName || db->mallocFailed ){
91277    goto trigger_cleanup;
91278  }
91279  pTab = sqlite3SrcListLookup(pParse, pTableName);
91280  if( db->init.busy==0 && pName2->n==0 && pTab
91281        && pTab->pSchema==db->aDb[1].pSchema ){
91282    iDb = 1;
91283  }
91284
91285  /* Ensure the table name matches database name and that the table exists */
91286  if( db->mallocFailed ) goto trigger_cleanup;
91287  assert( pTableName->nSrc==1 );
91288  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
91289      sqlite3FixSrcList(&sFix, pTableName) ){
91290    goto trigger_cleanup;
91291  }
91292  pTab = sqlite3SrcListLookup(pParse, pTableName);
91293  if( !pTab ){
91294    /* The table does not exist. */
91295    if( db->init.iDb==1 ){
91296      /* Ticket #3810.
91297      ** Normally, whenever a table is dropped, all associated triggers are
91298      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
91299      ** and the table is dropped by a different database connection, the
91300      ** trigger is not visible to the database connection that does the
91301      ** drop so the trigger cannot be dropped.  This results in an
91302      ** "orphaned trigger" - a trigger whose associated table is missing.
91303      */
91304      db->init.orphanTrigger = 1;
91305    }
91306    goto trigger_cleanup;
91307  }
91308  if( IsVirtual(pTab) ){
91309    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
91310    goto trigger_cleanup;
91311  }
91312
91313  /* Check that the trigger name is not reserved and that no trigger of the
91314  ** specified name exists */
91315  zName = sqlite3NameFromToken(db, pName);
91316  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91317    goto trigger_cleanup;
91318  }
91319  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
91320                      zName, sqlite3Strlen30(zName)) ){
91321    if( !noErr ){
91322      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
91323    }
91324    goto trigger_cleanup;
91325  }
91326
91327  /* Do not create a trigger on a system table */
91328  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
91329    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
91330    pParse->nErr++;
91331    goto trigger_cleanup;
91332  }
91333
91334  /* INSTEAD of triggers are only for views and views only support INSTEAD
91335  ** of triggers.
91336  */
91337  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
91338    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
91339        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
91340    goto trigger_cleanup;
91341  }
91342  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
91343    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
91344        " trigger on table: %S", pTableName, 0);
91345    goto trigger_cleanup;
91346  }
91347  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91348
91349#ifndef SQLITE_OMIT_AUTHORIZATION
91350  {
91351    int code = SQLITE_CREATE_TRIGGER;
91352    const char *zDb = db->aDb[iTabDb].zName;
91353    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
91354    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
91355    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
91356      goto trigger_cleanup;
91357    }
91358    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
91359      goto trigger_cleanup;
91360    }
91361  }
91362#endif
91363
91364  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
91365  ** cannot appear on views.  So we might as well translate every
91366  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
91367  ** elsewhere.
91368  */
91369  if (tr_tm == TK_INSTEAD){
91370    tr_tm = TK_BEFORE;
91371  }
91372
91373  /* Build the Trigger object */
91374  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
91375  if( pTrigger==0 ) goto trigger_cleanup;
91376  pTrigger->zName = zName;
91377  zName = 0;
91378  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
91379  pTrigger->pSchema = db->aDb[iDb].pSchema;
91380  pTrigger->pTabSchema = pTab->pSchema;
91381  pTrigger->op = (u8)op;
91382  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
91383  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
91384  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
91385  assert( pParse->pNewTrigger==0 );
91386  pParse->pNewTrigger = pTrigger;
91387
91388trigger_cleanup:
91389  sqlite3DbFree(db, zName);
91390  sqlite3SrcListDelete(db, pTableName);
91391  sqlite3IdListDelete(db, pColumns);
91392  sqlite3ExprDelete(db, pWhen);
91393  if( !pParse->pNewTrigger ){
91394    sqlite3DeleteTrigger(db, pTrigger);
91395  }else{
91396    assert( pParse->pNewTrigger==pTrigger );
91397  }
91398}
91399
91400/*
91401** This routine is called after all of the trigger actions have been parsed
91402** in order to complete the process of building the trigger.
91403*/
91404SQLITE_PRIVATE void sqlite3FinishTrigger(
91405  Parse *pParse,          /* Parser context */
91406  TriggerStep *pStepList, /* The triggered program */
91407  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
91408){
91409  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
91410  char *zName;                            /* Name of trigger */
91411  sqlite3 *db = pParse->db;               /* The database */
91412  DbFixer sFix;                           /* Fixer object */
91413  int iDb;                                /* Database containing the trigger */
91414  Token nameToken;                        /* Trigger name for error reporting */
91415
91416  pTrig = pParse->pNewTrigger;
91417  pParse->pNewTrigger = 0;
91418  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
91419  zName = pTrig->zName;
91420  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
91421  pTrig->step_list = pStepList;
91422  while( pStepList ){
91423    pStepList->pTrig = pTrig;
91424    pStepList = pStepList->pNext;
91425  }
91426  nameToken.z = pTrig->zName;
91427  nameToken.n = sqlite3Strlen30(nameToken.z);
91428  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
91429          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
91430    goto triggerfinish_cleanup;
91431  }
91432
91433  /* if we are not initializing,
91434  ** build the sqlite_master entry
91435  */
91436  if( !db->init.busy ){
91437    Vdbe *v;
91438    char *z;
91439
91440    /* Make an entry in the sqlite_master table */
91441    v = sqlite3GetVdbe(pParse);
91442    if( v==0 ) goto triggerfinish_cleanup;
91443    sqlite3BeginWriteOperation(pParse, 0, iDb);
91444    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
91445    sqlite3NestedParse(pParse,
91446       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
91447       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
91448       pTrig->table, z);
91449    sqlite3DbFree(db, z);
91450    sqlite3ChangeCookie(pParse, iDb);
91451    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
91452        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
91453    );
91454  }
91455
91456  if( db->init.busy ){
91457    Trigger *pLink = pTrig;
91458    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
91459    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
91460    if( pTrig ){
91461      db->mallocFailed = 1;
91462    }else if( pLink->pSchema==pLink->pTabSchema ){
91463      Table *pTab;
91464      int n = sqlite3Strlen30(pLink->table);
91465      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
91466      assert( pTab!=0 );
91467      pLink->pNext = pTab->pTrigger;
91468      pTab->pTrigger = pLink;
91469    }
91470  }
91471
91472triggerfinish_cleanup:
91473  sqlite3DeleteTrigger(db, pTrig);
91474  assert( !pParse->pNewTrigger );
91475  sqlite3DeleteTriggerStep(db, pStepList);
91476}
91477
91478/*
91479** Turn a SELECT statement (that the pSelect parameter points to) into
91480** a trigger step.  Return a pointer to a TriggerStep structure.
91481**
91482** The parser calls this routine when it finds a SELECT statement in
91483** body of a TRIGGER.
91484*/
91485SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
91486  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
91487  if( pTriggerStep==0 ) {
91488    sqlite3SelectDelete(db, pSelect);
91489    return 0;
91490  }
91491  pTriggerStep->op = TK_SELECT;
91492  pTriggerStep->pSelect = pSelect;
91493  pTriggerStep->orconf = OE_Default;
91494  return pTriggerStep;
91495}
91496
91497/*
91498** Allocate space to hold a new trigger step.  The allocated space
91499** holds both the TriggerStep object and the TriggerStep.target.z string.
91500**
91501** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
91502*/
91503static TriggerStep *triggerStepAllocate(
91504  sqlite3 *db,                /* Database connection */
91505  u8 op,                      /* Trigger opcode */
91506  Token *pName                /* The target name */
91507){
91508  TriggerStep *pTriggerStep;
91509
91510  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
91511  if( pTriggerStep ){
91512    char *z = (char*)&pTriggerStep[1];
91513    memcpy(z, pName->z, pName->n);
91514    pTriggerStep->target.z = z;
91515    pTriggerStep->target.n = pName->n;
91516    pTriggerStep->op = op;
91517  }
91518  return pTriggerStep;
91519}
91520
91521/*
91522** Build a trigger step out of an INSERT statement.  Return a pointer
91523** to the new trigger step.
91524**
91525** The parser calls this routine when it sees an INSERT inside the
91526** body of a trigger.
91527*/
91528SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
91529  sqlite3 *db,        /* The database connection */
91530  Token *pTableName,  /* Name of the table into which we insert */
91531  IdList *pColumn,    /* List of columns in pTableName to insert into */
91532  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
91533  Select *pSelect,    /* A SELECT statement that supplies values */
91534  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
91535){
91536  TriggerStep *pTriggerStep;
91537
91538  assert(pEList == 0 || pSelect == 0);
91539  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
91540
91541  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
91542  if( pTriggerStep ){
91543    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
91544    pTriggerStep->pIdList = pColumn;
91545    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
91546    pTriggerStep->orconf = orconf;
91547  }else{
91548    sqlite3IdListDelete(db, pColumn);
91549  }
91550  sqlite3ExprListDelete(db, pEList);
91551  sqlite3SelectDelete(db, pSelect);
91552
91553  return pTriggerStep;
91554}
91555
91556/*
91557** Construct a trigger step that implements an UPDATE statement and return
91558** a pointer to that trigger step.  The parser calls this routine when it
91559** sees an UPDATE statement inside the body of a CREATE TRIGGER.
91560*/
91561SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
91562  sqlite3 *db,         /* The database connection */
91563  Token *pTableName,   /* Name of the table to be updated */
91564  ExprList *pEList,    /* The SET clause: list of column and new values */
91565  Expr *pWhere,        /* The WHERE clause */
91566  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
91567){
91568  TriggerStep *pTriggerStep;
91569
91570  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
91571  if( pTriggerStep ){
91572    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
91573    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
91574    pTriggerStep->orconf = orconf;
91575  }
91576  sqlite3ExprListDelete(db, pEList);
91577  sqlite3ExprDelete(db, pWhere);
91578  return pTriggerStep;
91579}
91580
91581/*
91582** Construct a trigger step that implements a DELETE statement and return
91583** a pointer to that trigger step.  The parser calls this routine when it
91584** sees a DELETE statement inside the body of a CREATE TRIGGER.
91585*/
91586SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
91587  sqlite3 *db,            /* Database connection */
91588  Token *pTableName,      /* The table from which rows are deleted */
91589  Expr *pWhere            /* The WHERE clause */
91590){
91591  TriggerStep *pTriggerStep;
91592
91593  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
91594  if( pTriggerStep ){
91595    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
91596    pTriggerStep->orconf = OE_Default;
91597  }
91598  sqlite3ExprDelete(db, pWhere);
91599  return pTriggerStep;
91600}
91601
91602/*
91603** Recursively delete a Trigger structure
91604*/
91605SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
91606  if( pTrigger==0 ) return;
91607  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
91608  sqlite3DbFree(db, pTrigger->zName);
91609  sqlite3DbFree(db, pTrigger->table);
91610  sqlite3ExprDelete(db, pTrigger->pWhen);
91611  sqlite3IdListDelete(db, pTrigger->pColumns);
91612  sqlite3DbFree(db, pTrigger);
91613}
91614
91615/*
91616** This function is called to drop a trigger from the database schema.
91617**
91618** This may be called directly from the parser and therefore identifies
91619** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
91620** same job as this routine except it takes a pointer to the trigger
91621** instead of the trigger name.
91622**/
91623SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
91624  Trigger *pTrigger = 0;
91625  int i;
91626  const char *zDb;
91627  const char *zName;
91628  int nName;
91629  sqlite3 *db = pParse->db;
91630
91631  if( db->mallocFailed ) goto drop_trigger_cleanup;
91632  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91633    goto drop_trigger_cleanup;
91634  }
91635
91636  assert( pName->nSrc==1 );
91637  zDb = pName->a[0].zDatabase;
91638  zName = pName->a[0].zName;
91639  nName = sqlite3Strlen30(zName);
91640  for(i=OMIT_TEMPDB; i<db->nDb; i++){
91641    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
91642    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
91643    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
91644    if( pTrigger ) break;
91645  }
91646  if( !pTrigger ){
91647    if( !noErr ){
91648      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
91649    }
91650    pParse->checkSchema = 1;
91651    goto drop_trigger_cleanup;
91652  }
91653  sqlite3DropTriggerPtr(pParse, pTrigger);
91654
91655drop_trigger_cleanup:
91656  sqlite3SrcListDelete(db, pName);
91657}
91658
91659/*
91660** Return a pointer to the Table structure for the table that a trigger
91661** is set on.
91662*/
91663static Table *tableOfTrigger(Trigger *pTrigger){
91664  int n = sqlite3Strlen30(pTrigger->table);
91665  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
91666}
91667
91668
91669/*
91670** Drop a trigger given a pointer to that trigger.
91671*/
91672SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
91673  Table   *pTable;
91674  Vdbe *v;
91675  sqlite3 *db = pParse->db;
91676  int iDb;
91677
91678  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
91679  assert( iDb>=0 && iDb<db->nDb );
91680  pTable = tableOfTrigger(pTrigger);
91681  assert( pTable );
91682  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
91683#ifndef SQLITE_OMIT_AUTHORIZATION
91684  {
91685    int code = SQLITE_DROP_TRIGGER;
91686    const char *zDb = db->aDb[iDb].zName;
91687    const char *zTab = SCHEMA_TABLE(iDb);
91688    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
91689    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
91690      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
91691      return;
91692    }
91693  }
91694#endif
91695
91696  /* Generate code to destroy the database record of the trigger.
91697  */
91698  assert( pTable!=0 );
91699  if( (v = sqlite3GetVdbe(pParse))!=0 ){
91700    int base;
91701    static const VdbeOpList dropTrigger[] = {
91702      { OP_Rewind,     0, ADDR(9),  0},
91703      { OP_String8,    0, 1,        0}, /* 1 */
91704      { OP_Column,     0, 1,        2},
91705      { OP_Ne,         2, ADDR(8),  1},
91706      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
91707      { OP_Column,     0, 0,        2},
91708      { OP_Ne,         2, ADDR(8),  1},
91709      { OP_Delete,     0, 0,        0},
91710      { OP_Next,       0, ADDR(1),  0}, /* 8 */
91711    };
91712
91713    sqlite3BeginWriteOperation(pParse, 0, iDb);
91714    sqlite3OpenMasterTable(pParse, iDb);
91715    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
91716    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
91717    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
91718    sqlite3ChangeCookie(pParse, iDb);
91719    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
91720    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
91721    if( pParse->nMem<3 ){
91722      pParse->nMem = 3;
91723    }
91724  }
91725}
91726
91727/*
91728** Remove a trigger from the hash tables of the sqlite* pointer.
91729*/
91730SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
91731  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
91732  Trigger *pTrigger;
91733  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
91734  if( ALWAYS(pTrigger) ){
91735    if( pTrigger->pSchema==pTrigger->pTabSchema ){
91736      Table *pTab = tableOfTrigger(pTrigger);
91737      Trigger **pp;
91738      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
91739      *pp = (*pp)->pNext;
91740    }
91741    sqlite3DeleteTrigger(db, pTrigger);
91742    db->flags |= SQLITE_InternChanges;
91743  }
91744}
91745
91746/*
91747** pEList is the SET clause of an UPDATE statement.  Each entry
91748** in pEList is of the format <id>=<expr>.  If any of the entries
91749** in pEList have an <id> which matches an identifier in pIdList,
91750** then return TRUE.  If pIdList==NULL, then it is considered a
91751** wildcard that matches anything.  Likewise if pEList==NULL then
91752** it matches anything so always return true.  Return false only
91753** if there is no match.
91754*/
91755static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
91756  int e;
91757  if( pIdList==0 || NEVER(pEList==0) ) return 1;
91758  for(e=0; e<pEList->nExpr; e++){
91759    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
91760  }
91761  return 0;
91762}
91763
91764/*
91765** Return a list of all triggers on table pTab if there exists at least
91766** one trigger that must be fired when an operation of type 'op' is
91767** performed on the table, and, if that operation is an UPDATE, if at
91768** least one of the columns in pChanges is being modified.
91769*/
91770SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
91771  Parse *pParse,          /* Parse context */
91772  Table *pTab,            /* The table the contains the triggers */
91773  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
91774  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
91775  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
91776){
91777  int mask = 0;
91778  Trigger *pList = sqlite3TriggerList(pParse, pTab);
91779  Trigger *p;
91780  assert( pList==0 || IsVirtual(pTab)==0 );
91781  for(p=pList; p; p=p->pNext){
91782    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
91783      mask |= p->tr_tm;
91784    }
91785  }
91786  if( pMask ){
91787    *pMask = mask;
91788  }
91789  return (mask ? pList : 0);
91790}
91791
91792/*
91793** Convert the pStep->target token into a SrcList and return a pointer
91794** to that SrcList.
91795**
91796** This routine adds a specific database name, if needed, to the target when
91797** forming the SrcList.  This prevents a trigger in one database from
91798** referring to a target in another database.  An exception is when the
91799** trigger is in TEMP in which case it can refer to any other database it
91800** wants.
91801*/
91802static SrcList *targetSrcList(
91803  Parse *pParse,       /* The parsing context */
91804  TriggerStep *pStep   /* The trigger containing the target token */
91805){
91806  int iDb;             /* Index of the database to use */
91807  SrcList *pSrc;       /* SrcList to be returned */
91808
91809  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
91810  if( pSrc ){
91811    assert( pSrc->nSrc>0 );
91812    assert( pSrc->a!=0 );
91813    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
91814    if( iDb==0 || iDb>=2 ){
91815      sqlite3 *db = pParse->db;
91816      assert( iDb<pParse->db->nDb );
91817      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
91818    }
91819  }
91820  return pSrc;
91821}
91822
91823/*
91824** Generate VDBE code for the statements inside the body of a single
91825** trigger.
91826*/
91827static int codeTriggerProgram(
91828  Parse *pParse,            /* The parser context */
91829  TriggerStep *pStepList,   /* List of statements inside the trigger body */
91830  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
91831){
91832  TriggerStep *pStep;
91833  Vdbe *v = pParse->pVdbe;
91834  sqlite3 *db = pParse->db;
91835
91836  assert( pParse->pTriggerTab && pParse->pToplevel );
91837  assert( pStepList );
91838  assert( v!=0 );
91839  for(pStep=pStepList; pStep; pStep=pStep->pNext){
91840    /* Figure out the ON CONFLICT policy that will be used for this step
91841    ** of the trigger program. If the statement that caused this trigger
91842    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
91843    ** the ON CONFLICT policy that was specified as part of the trigger
91844    ** step statement. Example:
91845    **
91846    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
91847    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
91848    **   END;
91849    **
91850    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
91851    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
91852    */
91853    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
91854
91855    switch( pStep->op ){
91856      case TK_UPDATE: {
91857        sqlite3Update(pParse,
91858          targetSrcList(pParse, pStep),
91859          sqlite3ExprListDup(db, pStep->pExprList, 0),
91860          sqlite3ExprDup(db, pStep->pWhere, 0),
91861          pParse->eOrconf
91862        );
91863        break;
91864      }
91865      case TK_INSERT: {
91866        sqlite3Insert(pParse,
91867          targetSrcList(pParse, pStep),
91868          sqlite3ExprListDup(db, pStep->pExprList, 0),
91869          sqlite3SelectDup(db, pStep->pSelect, 0),
91870          sqlite3IdListDup(db, pStep->pIdList),
91871          pParse->eOrconf
91872        );
91873        break;
91874      }
91875      case TK_DELETE: {
91876        sqlite3DeleteFrom(pParse,
91877          targetSrcList(pParse, pStep),
91878          sqlite3ExprDup(db, pStep->pWhere, 0)
91879        );
91880        break;
91881      }
91882      default: assert( pStep->op==TK_SELECT ); {
91883        SelectDest sDest;
91884        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
91885        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
91886        sqlite3Select(pParse, pSelect, &sDest);
91887        sqlite3SelectDelete(db, pSelect);
91888        break;
91889      }
91890    }
91891    if( pStep->op!=TK_SELECT ){
91892      sqlite3VdbeAddOp0(v, OP_ResetCount);
91893    }
91894  }
91895
91896  return 0;
91897}
91898
91899#ifdef SQLITE_DEBUG
91900/*
91901** This function is used to add VdbeComment() annotations to a VDBE
91902** program. It is not used in production code, only for debugging.
91903*/
91904static const char *onErrorText(int onError){
91905  switch( onError ){
91906    case OE_Abort:    return "abort";
91907    case OE_Rollback: return "rollback";
91908    case OE_Fail:     return "fail";
91909    case OE_Replace:  return "replace";
91910    case OE_Ignore:   return "ignore";
91911    case OE_Default:  return "default";
91912  }
91913  return "n/a";
91914}
91915#endif
91916
91917/*
91918** Parse context structure pFrom has just been used to create a sub-vdbe
91919** (trigger program). If an error has occurred, transfer error information
91920** from pFrom to pTo.
91921*/
91922static void transferParseError(Parse *pTo, Parse *pFrom){
91923  assert( pFrom->zErrMsg==0 || pFrom->nErr );
91924  assert( pTo->zErrMsg==0 || pTo->nErr );
91925  if( pTo->nErr==0 ){
91926    pTo->zErrMsg = pFrom->zErrMsg;
91927    pTo->nErr = pFrom->nErr;
91928  }else{
91929    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
91930  }
91931}
91932
91933/*
91934** Create and populate a new TriggerPrg object with a sub-program
91935** implementing trigger pTrigger with ON CONFLICT policy orconf.
91936*/
91937static TriggerPrg *codeRowTrigger(
91938  Parse *pParse,       /* Current parse context */
91939  Trigger *pTrigger,   /* Trigger to code */
91940  Table *pTab,         /* The table pTrigger is attached to */
91941  int orconf           /* ON CONFLICT policy to code trigger program with */
91942){
91943  Parse *pTop = sqlite3ParseToplevel(pParse);
91944  sqlite3 *db = pParse->db;   /* Database handle */
91945  TriggerPrg *pPrg;           /* Value to return */
91946  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
91947  Vdbe *v;                    /* Temporary VM */
91948  NameContext sNC;            /* Name context for sub-vdbe */
91949  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
91950  Parse *pSubParse;           /* Parse context for sub-vdbe */
91951  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
91952
91953  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
91954  assert( pTop->pVdbe );
91955
91956  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
91957  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
91958  ** list of the top-level Parse object sooner rather than later.  */
91959  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
91960  if( !pPrg ) return 0;
91961  pPrg->pNext = pTop->pTriggerPrg;
91962  pTop->pTriggerPrg = pPrg;
91963  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
91964  if( !pProgram ) return 0;
91965  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
91966  pPrg->pTrigger = pTrigger;
91967  pPrg->orconf = orconf;
91968  pPrg->aColmask[0] = 0xffffffff;
91969  pPrg->aColmask[1] = 0xffffffff;
91970
91971  /* Allocate and populate a new Parse context to use for coding the
91972  ** trigger sub-program.  */
91973  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
91974  if( !pSubParse ) return 0;
91975  memset(&sNC, 0, sizeof(sNC));
91976  sNC.pParse = pSubParse;
91977  pSubParse->db = db;
91978  pSubParse->pTriggerTab = pTab;
91979  pSubParse->pToplevel = pTop;
91980  pSubParse->zAuthContext = pTrigger->zName;
91981  pSubParse->eTriggerOp = pTrigger->op;
91982  pSubParse->nQueryLoop = pParse->nQueryLoop;
91983
91984  v = sqlite3GetVdbe(pSubParse);
91985  if( v ){
91986    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
91987      pTrigger->zName, onErrorText(orconf),
91988      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
91989        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
91990        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
91991        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
91992      pTab->zName
91993    ));
91994#ifndef SQLITE_OMIT_TRACE
91995    sqlite3VdbeChangeP4(v, -1,
91996      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
91997    );
91998#endif
91999
92000    /* If one was specified, code the WHEN clause. If it evaluates to false
92001    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
92002    ** OP_Halt inserted at the end of the program.  */
92003    if( pTrigger->pWhen ){
92004      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
92005      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
92006       && db->mallocFailed==0
92007      ){
92008        iEndTrigger = sqlite3VdbeMakeLabel(v);
92009        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
92010      }
92011      sqlite3ExprDelete(db, pWhen);
92012    }
92013
92014    /* Code the trigger program into the sub-vdbe. */
92015    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
92016
92017    /* Insert an OP_Halt at the end of the sub-program. */
92018    if( iEndTrigger ){
92019      sqlite3VdbeResolveLabel(v, iEndTrigger);
92020    }
92021    sqlite3VdbeAddOp0(v, OP_Halt);
92022    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
92023
92024    transferParseError(pParse, pSubParse);
92025    if( db->mallocFailed==0 ){
92026      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
92027    }
92028    pProgram->nMem = pSubParse->nMem;
92029    pProgram->nCsr = pSubParse->nTab;
92030    pProgram->token = (void *)pTrigger;
92031    pPrg->aColmask[0] = pSubParse->oldmask;
92032    pPrg->aColmask[1] = pSubParse->newmask;
92033    sqlite3VdbeDelete(v);
92034  }
92035
92036  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
92037  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
92038  sqlite3StackFree(db, pSubParse);
92039
92040  return pPrg;
92041}
92042
92043/*
92044** Return a pointer to a TriggerPrg object containing the sub-program for
92045** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
92046** TriggerPrg object exists, a new object is allocated and populated before
92047** being returned.
92048*/
92049static TriggerPrg *getRowTrigger(
92050  Parse *pParse,       /* Current parse context */
92051  Trigger *pTrigger,   /* Trigger to code */
92052  Table *pTab,         /* The table trigger pTrigger is attached to */
92053  int orconf           /* ON CONFLICT algorithm. */
92054){
92055  Parse *pRoot = sqlite3ParseToplevel(pParse);
92056  TriggerPrg *pPrg;
92057
92058  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
92059
92060  /* It may be that this trigger has already been coded (or is in the
92061  ** process of being coded). If this is the case, then an entry with
92062  ** a matching TriggerPrg.pTrigger field will be present somewhere
92063  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
92064  for(pPrg=pRoot->pTriggerPrg;
92065      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
92066      pPrg=pPrg->pNext
92067  );
92068
92069  /* If an existing TriggerPrg could not be located, create a new one. */
92070  if( !pPrg ){
92071    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
92072  }
92073
92074  return pPrg;
92075}
92076
92077/*
92078** Generate code for the trigger program associated with trigger p on
92079** table pTab. The reg, orconf and ignoreJump parameters passed to this
92080** function are the same as those described in the header function for
92081** sqlite3CodeRowTrigger()
92082*/
92083SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
92084  Parse *pParse,       /* Parse context */
92085  Trigger *p,          /* Trigger to code */
92086  Table *pTab,         /* The table to code triggers from */
92087  int reg,             /* Reg array containing OLD.* and NEW.* values */
92088  int orconf,          /* ON CONFLICT policy */
92089  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
92090){
92091  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
92092  TriggerPrg *pPrg;
92093  pPrg = getRowTrigger(pParse, p, pTab, orconf);
92094  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
92095
92096  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
92097  ** is a pointer to the sub-vdbe containing the trigger program.  */
92098  if( pPrg ){
92099    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
92100
92101    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
92102    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
92103    VdbeComment(
92104        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
92105
92106    /* Set the P5 operand of the OP_Program instruction to non-zero if
92107    ** recursive invocation of this trigger program is disallowed. Recursive
92108    ** invocation is disallowed if (a) the sub-program is really a trigger,
92109    ** not a foreign key action, and (b) the flag to enable recursive triggers
92110    ** is clear.  */
92111    sqlite3VdbeChangeP5(v, (u8)bRecursive);
92112  }
92113}
92114
92115/*
92116** This is called to code the required FOR EACH ROW triggers for an operation
92117** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
92118** is given by the op paramater. The tr_tm parameter determines whether the
92119** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
92120** parameter pChanges is passed the list of columns being modified.
92121**
92122** If there are no triggers that fire at the specified time for the specified
92123** operation on pTab, this function is a no-op.
92124**
92125** The reg argument is the address of the first in an array of registers
92126** that contain the values substituted for the new.* and old.* references
92127** in the trigger program. If N is the number of columns in table pTab
92128** (a copy of pTab->nCol), then registers are populated as follows:
92129**
92130**   Register       Contains
92131**   ------------------------------------------------------
92132**   reg+0          OLD.rowid
92133**   reg+1          OLD.* value of left-most column of pTab
92134**   ...            ...
92135**   reg+N          OLD.* value of right-most column of pTab
92136**   reg+N+1        NEW.rowid
92137**   reg+N+2        OLD.* value of left-most column of pTab
92138**   ...            ...
92139**   reg+N+N+1      NEW.* value of right-most column of pTab
92140**
92141** For ON DELETE triggers, the registers containing the NEW.* values will
92142** never be accessed by the trigger program, so they are not allocated or
92143** populated by the caller (there is no data to populate them with anyway).
92144** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
92145** are never accessed, and so are not allocated by the caller. So, for an
92146** ON INSERT trigger, the value passed to this function as parameter reg
92147** is not a readable register, although registers (reg+N) through
92148** (reg+N+N+1) are.
92149**
92150** Parameter orconf is the default conflict resolution algorithm for the
92151** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
92152** is the instruction that control should jump to if a trigger program
92153** raises an IGNORE exception.
92154*/
92155SQLITE_PRIVATE void sqlite3CodeRowTrigger(
92156  Parse *pParse,       /* Parse context */
92157  Trigger *pTrigger,   /* List of triggers on table pTab */
92158  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
92159  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
92160  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
92161  Table *pTab,         /* The table to code triggers from */
92162  int reg,             /* The first in an array of registers (see above) */
92163  int orconf,          /* ON CONFLICT policy */
92164  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
92165){
92166  Trigger *p;          /* Used to iterate through pTrigger list */
92167
92168  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
92169  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
92170  assert( (op==TK_UPDATE)==(pChanges!=0) );
92171
92172  for(p=pTrigger; p; p=p->pNext){
92173
92174    /* Sanity checking:  The schema for the trigger and for the table are
92175    ** always defined.  The trigger must be in the same schema as the table
92176    ** or else it must be a TEMP trigger. */
92177    assert( p->pSchema!=0 );
92178    assert( p->pTabSchema!=0 );
92179    assert( p->pSchema==p->pTabSchema
92180         || p->pSchema==pParse->db->aDb[1].pSchema );
92181
92182    /* Determine whether we should code this trigger */
92183    if( p->op==op
92184     && p->tr_tm==tr_tm
92185     && checkColumnOverlap(p->pColumns, pChanges)
92186    ){
92187      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
92188    }
92189  }
92190}
92191
92192/*
92193** Triggers may access values stored in the old.* or new.* pseudo-table.
92194** This function returns a 32-bit bitmask indicating which columns of the
92195** old.* or new.* tables actually are used by triggers. This information
92196** may be used by the caller, for example, to avoid having to load the entire
92197** old.* record into memory when executing an UPDATE or DELETE command.
92198**
92199** Bit 0 of the returned mask is set if the left-most column of the
92200** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
92201** the second leftmost column value is required, and so on. If there
92202** are more than 32 columns in the table, and at least one of the columns
92203** with an index greater than 32 may be accessed, 0xffffffff is returned.
92204**
92205** It is not possible to determine if the old.rowid or new.rowid column is
92206** accessed by triggers. The caller must always assume that it is.
92207**
92208** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
92209** applies to the old.* table. If 1, the new.* table.
92210**
92211** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
92212** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
92213** included in the returned mask if the TRIGGER_BEFORE bit is set in the
92214** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
92215** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
92216*/
92217SQLITE_PRIVATE u32 sqlite3TriggerColmask(
92218  Parse *pParse,       /* Parse context */
92219  Trigger *pTrigger,   /* List of triggers on table pTab */
92220  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
92221  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
92222  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
92223  Table *pTab,         /* The table to code triggers from */
92224  int orconf           /* Default ON CONFLICT policy for trigger steps */
92225){
92226  const int op = pChanges ? TK_UPDATE : TK_DELETE;
92227  u32 mask = 0;
92228  Trigger *p;
92229
92230  assert( isNew==1 || isNew==0 );
92231  for(p=pTrigger; p; p=p->pNext){
92232    if( p->op==op && (tr_tm&p->tr_tm)
92233     && checkColumnOverlap(p->pColumns,pChanges)
92234    ){
92235      TriggerPrg *pPrg;
92236      pPrg = getRowTrigger(pParse, p, pTab, orconf);
92237      if( pPrg ){
92238        mask |= pPrg->aColmask[isNew];
92239      }
92240    }
92241  }
92242
92243  return mask;
92244}
92245
92246#endif /* !defined(SQLITE_OMIT_TRIGGER) */
92247
92248/************** End of trigger.c *********************************************/
92249/************** Begin file update.c ******************************************/
92250/*
92251** 2001 September 15
92252**
92253** The author disclaims copyright to this source code.  In place of
92254** a legal notice, here is a blessing:
92255**
92256**    May you do good and not evil.
92257**    May you find forgiveness for yourself and forgive others.
92258**    May you share freely, never taking more than you give.
92259**
92260*************************************************************************
92261** This file contains C code routines that are called by the parser
92262** to handle UPDATE statements.
92263*/
92264
92265#ifndef SQLITE_OMIT_VIRTUALTABLE
92266/* Forward declaration */
92267static void updateVirtualTable(
92268  Parse *pParse,       /* The parsing context */
92269  SrcList *pSrc,       /* The virtual table to be modified */
92270  Table *pTab,         /* The virtual table */
92271  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
92272  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
92273  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
92274  Expr *pWhere         /* WHERE clause of the UPDATE statement */
92275);
92276#endif /* SQLITE_OMIT_VIRTUALTABLE */
92277
92278/*
92279** The most recently coded instruction was an OP_Column to retrieve the
92280** i-th column of table pTab. This routine sets the P4 parameter of the
92281** OP_Column to the default value, if any.
92282**
92283** The default value of a column is specified by a DEFAULT clause in the
92284** column definition. This was either supplied by the user when the table
92285** was created, or added later to the table definition by an ALTER TABLE
92286** command. If the latter, then the row-records in the table btree on disk
92287** may not contain a value for the column and the default value, taken
92288** from the P4 parameter of the OP_Column instruction, is returned instead.
92289** If the former, then all row-records are guaranteed to include a value
92290** for the column and the P4 value is not required.
92291**
92292** Column definitions created by an ALTER TABLE command may only have
92293** literal default values specified: a number, null or a string. (If a more
92294** complicated default expression value was provided, it is evaluated
92295** when the ALTER TABLE is executed and one of the literal values written
92296** into the sqlite_master table.)
92297**
92298** Therefore, the P4 parameter is only required if the default value for
92299** the column is a literal number, string or null. The sqlite3ValueFromExpr()
92300** function is capable of transforming these types of expressions into
92301** sqlite3_value objects.
92302**
92303** If parameter iReg is not negative, code an OP_RealAffinity instruction
92304** on register iReg. This is used when an equivalent integer value is
92305** stored in place of an 8-byte floating point value in order to save
92306** space.
92307*/
92308SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
92309  assert( pTab!=0 );
92310  if( !pTab->pSelect ){
92311    sqlite3_value *pValue;
92312    u8 enc = ENC(sqlite3VdbeDb(v));
92313    Column *pCol = &pTab->aCol[i];
92314    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
92315    assert( i<pTab->nCol );
92316    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
92317                         pCol->affinity, &pValue);
92318    if( pValue ){
92319      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
92320    }
92321#ifndef SQLITE_OMIT_FLOATING_POINT
92322    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
92323      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
92324    }
92325#endif
92326  }
92327}
92328
92329/*
92330** Process an UPDATE statement.
92331**
92332**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
92333**          \_______/ \________/     \______/       \________________/
92334*            onError   pTabList      pChanges             pWhere
92335*/
92336SQLITE_PRIVATE void sqlite3Update(
92337  Parse *pParse,         /* The parser context */
92338  SrcList *pTabList,     /* The table in which we should change things */
92339  ExprList *pChanges,    /* Things to be changed */
92340  Expr *pWhere,          /* The WHERE clause.  May be null */
92341  int onError            /* How to handle constraint errors */
92342){
92343  int i, j;              /* Loop counters */
92344  Table *pTab;           /* The table to be updated */
92345  int addr = 0;          /* VDBE instruction address of the start of the loop */
92346  WhereInfo *pWInfo;     /* Information about the WHERE clause */
92347  Vdbe *v;               /* The virtual database engine */
92348  Index *pIdx;           /* For looping over indices */
92349  int nIdx;              /* Number of indices that need updating */
92350  int iCur;              /* VDBE Cursor number of pTab */
92351  sqlite3 *db;           /* The database structure */
92352  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
92353  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
92354                         ** an expression for the i-th column of the table.
92355                         ** aXRef[i]==-1 if the i-th column is not changed. */
92356  int chngRowid;         /* True if the record number is being changed */
92357  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
92358  int openAll = 0;       /* True if all indices need to be opened */
92359  AuthContext sContext;  /* The authorization context */
92360  NameContext sNC;       /* The name-context to resolve expressions in */
92361  int iDb;               /* Database containing the table being updated */
92362  int okOnePass;         /* True for one-pass algorithm without the FIFO */
92363  int hasFK;             /* True if foreign key processing is required */
92364
92365#ifndef SQLITE_OMIT_TRIGGER
92366  int isView;            /* True when updating a view (INSTEAD OF trigger) */
92367  Trigger *pTrigger;     /* List of triggers on pTab, if required */
92368  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
92369#endif
92370  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
92371
92372  /* Register Allocations */
92373  int regRowCount = 0;   /* A count of rows changed */
92374  int regOldRowid;       /* The old rowid */
92375  int regNewRowid;       /* The new rowid */
92376  int regNew;
92377  int regOld = 0;
92378  int regRowSet = 0;     /* Rowset of rows to be updated */
92379  int regRec;            /* Register used for new table record to insert */
92380
92381  memset(&sContext, 0, sizeof(sContext));
92382  db = pParse->db;
92383  if( pParse->nErr || db->mallocFailed ){
92384    goto update_cleanup;
92385  }
92386  assert( pTabList->nSrc==1 );
92387
92388  /* Locate the table which we want to update.
92389  */
92390  pTab = sqlite3SrcListLookup(pParse, pTabList);
92391  if( pTab==0 ) goto update_cleanup;
92392  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92393
92394  /* Figure out if we have any triggers and if the table being
92395  ** updated is a view.
92396  */
92397#ifndef SQLITE_OMIT_TRIGGER
92398  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
92399  isView = pTab->pSelect!=0;
92400  assert( pTrigger || tmask==0 );
92401#else
92402# define pTrigger 0
92403# define isView 0
92404# define tmask 0
92405#endif
92406#ifdef SQLITE_OMIT_VIEW
92407# undef isView
92408# define isView 0
92409#endif
92410
92411  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
92412    goto update_cleanup;
92413  }
92414  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
92415    goto update_cleanup;
92416  }
92417  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
92418  if( aXRef==0 ) goto update_cleanup;
92419  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
92420
92421  /* Allocate a cursors for the main database table and for all indices.
92422  ** The index cursors might not be used, but if they are used they
92423  ** need to occur right after the database cursor.  So go ahead and
92424  ** allocate enough space, just in case.
92425  */
92426  pTabList->a[0].iCursor = iCur = pParse->nTab++;
92427  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92428    pParse->nTab++;
92429  }
92430
92431  /* Initialize the name-context */
92432  memset(&sNC, 0, sizeof(sNC));
92433  sNC.pParse = pParse;
92434  sNC.pSrcList = pTabList;
92435
92436  /* Resolve the column names in all the expressions of the
92437  ** of the UPDATE statement.  Also find the column index
92438  ** for each column to be updated in the pChanges array.  For each
92439  ** column to be updated, make sure we have authorization to change
92440  ** that column.
92441  */
92442  chngRowid = 0;
92443  for(i=0; i<pChanges->nExpr; i++){
92444    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
92445      goto update_cleanup;
92446    }
92447    for(j=0; j<pTab->nCol; j++){
92448      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
92449        if( j==pTab->iPKey ){
92450          chngRowid = 1;
92451          pRowidExpr = pChanges->a[i].pExpr;
92452        }
92453        aXRef[j] = i;
92454        break;
92455      }
92456    }
92457    if( j>=pTab->nCol ){
92458      if( sqlite3IsRowid(pChanges->a[i].zName) ){
92459        chngRowid = 1;
92460        pRowidExpr = pChanges->a[i].pExpr;
92461      }else{
92462        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
92463        pParse->checkSchema = 1;
92464        goto update_cleanup;
92465      }
92466    }
92467#ifndef SQLITE_OMIT_AUTHORIZATION
92468    {
92469      int rc;
92470      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
92471                           pTab->aCol[j].zName, db->aDb[iDb].zName);
92472      if( rc==SQLITE_DENY ){
92473        goto update_cleanup;
92474      }else if( rc==SQLITE_IGNORE ){
92475        aXRef[j] = -1;
92476      }
92477    }
92478#endif
92479  }
92480
92481  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
92482
92483  /* Allocate memory for the array aRegIdx[].  There is one entry in the
92484  ** array for each index associated with table being updated.  Fill in
92485  ** the value with a register number for indices that are to be used
92486  ** and with zero for unused indices.
92487  */
92488  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
92489  if( nIdx>0 ){
92490    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
92491    if( aRegIdx==0 ) goto update_cleanup;
92492  }
92493  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
92494    int reg;
92495    if( chngRowid ){
92496      reg = ++pParse->nMem;
92497    }else{
92498      reg = 0;
92499      for(i=0; i<pIdx->nColumn; i++){
92500        if( aXRef[pIdx->aiColumn[i]]>=0 ){
92501          reg = ++pParse->nMem;
92502          break;
92503        }
92504      }
92505    }
92506    aRegIdx[j] = reg;
92507  }
92508
92509  /* Begin generating code. */
92510  v = sqlite3GetVdbe(pParse);
92511  if( v==0 ) goto update_cleanup;
92512  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
92513  sqlite3BeginWriteOperation(pParse, 1, iDb);
92514
92515#ifndef SQLITE_OMIT_VIRTUALTABLE
92516  /* Virtual tables must be handled separately */
92517  if( IsVirtual(pTab) ){
92518    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
92519                       pWhere);
92520    pWhere = 0;
92521    pTabList = 0;
92522    goto update_cleanup;
92523  }
92524#endif
92525
92526  /* Allocate required registers. */
92527  regOldRowid = regNewRowid = ++pParse->nMem;
92528  if( pTrigger || hasFK ){
92529    regOld = pParse->nMem + 1;
92530    pParse->nMem += pTab->nCol;
92531  }
92532  if( chngRowid || pTrigger || hasFK ){
92533    regNewRowid = ++pParse->nMem;
92534  }
92535  regNew = pParse->nMem + 1;
92536  pParse->nMem += pTab->nCol;
92537  regRec = ++pParse->nMem;
92538
92539  /* Start the view context. */
92540  if( isView ){
92541    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
92542  }
92543
92544  /* If we are trying to update a view, realize that view into
92545  ** a ephemeral table.
92546  */
92547#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
92548  if( isView ){
92549    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
92550  }
92551#endif
92552
92553  /* Resolve the column names in all the expressions in the
92554  ** WHERE clause.
92555  */
92556  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
92557    goto update_cleanup;
92558  }
92559
92560  /* Begin the database scan
92561  */
92562  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
92563  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
92564  if( pWInfo==0 ) goto update_cleanup;
92565  okOnePass = pWInfo->okOnePass;
92566
92567  /* Remember the rowid of every item to be updated.
92568  */
92569  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
92570  if( !okOnePass ){
92571    regRowSet = ++pParse->nMem;
92572    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
92573  }
92574
92575  /* End the database scan loop.
92576  */
92577  sqlite3WhereEnd(pWInfo);
92578
92579  /* Initialize the count of updated rows
92580  */
92581  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
92582    regRowCount = ++pParse->nMem;
92583    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
92584  }
92585
92586  if( !isView ){
92587    /*
92588    ** Open every index that needs updating.  Note that if any
92589    ** index could potentially invoke a REPLACE conflict resolution
92590    ** action, then we need to open all indices because we might need
92591    ** to be deleting some records.
92592    */
92593    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
92594    if( onError==OE_Replace ){
92595      openAll = 1;
92596    }else{
92597      openAll = 0;
92598      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92599        if( pIdx->onError==OE_Replace ){
92600          openAll = 1;
92601          break;
92602        }
92603      }
92604    }
92605    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
92606      if( openAll || aRegIdx[i]>0 ){
92607        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
92608        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
92609                       (char*)pKey, P4_KEYINFO_HANDOFF);
92610        assert( pParse->nTab>iCur+i+1 );
92611      }
92612    }
92613  }
92614
92615  /* Top of the update loop */
92616  if( okOnePass ){
92617    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
92618    addr = sqlite3VdbeAddOp0(v, OP_Goto);
92619    sqlite3VdbeJumpHere(v, a1);
92620  }else{
92621    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
92622  }
92623
92624  /* Make cursor iCur point to the record that is being updated. If
92625  ** this record does not exist for some reason (deleted by a trigger,
92626  ** for example, then jump to the next iteration of the RowSet loop.  */
92627  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
92628
92629  /* If the record number will change, set register regNewRowid to
92630  ** contain the new value. If the record number is not being modified,
92631  ** then regNewRowid is the same register as regOldRowid, which is
92632  ** already populated.  */
92633  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
92634  if( chngRowid ){
92635    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
92636    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
92637  }
92638
92639  /* If there are triggers on this table, populate an array of registers
92640  ** with the required old.* column data.  */
92641  if( hasFK || pTrigger ){
92642    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
92643    oldmask |= sqlite3TriggerColmask(pParse,
92644        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
92645    );
92646    for(i=0; i<pTab->nCol; i++){
92647      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
92648        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
92649      }else{
92650        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
92651      }
92652    }
92653    if( chngRowid==0 ){
92654      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
92655    }
92656  }
92657
92658  /* Populate the array of registers beginning at regNew with the new
92659  ** row data. This array is used to check constaints, create the new
92660  ** table and index records, and as the values for any new.* references
92661  ** made by triggers.
92662  **
92663  ** If there are one or more BEFORE triggers, then do not populate the
92664  ** registers associated with columns that are (a) not modified by
92665  ** this UPDATE statement and (b) not accessed by new.* references. The
92666  ** values for registers not modified by the UPDATE must be reloaded from
92667  ** the database after the BEFORE triggers are fired anyway (as the trigger
92668  ** may have modified them). So not loading those that are not going to
92669  ** be used eliminates some redundant opcodes.
92670  */
92671  newmask = sqlite3TriggerColmask(
92672      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
92673  );
92674  for(i=0; i<pTab->nCol; i++){
92675    if( i==pTab->iPKey ){
92676      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
92677    }else{
92678      j = aXRef[i];
92679      if( j>=0 ){
92680        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
92681      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
92682        /* This branch loads the value of a column that will not be changed
92683        ** into a register. This is done if there are no BEFORE triggers, or
92684        ** if there are one or more BEFORE triggers that use this value via
92685        ** a new.* reference in a trigger program.
92686        */
92687        testcase( i==31 );
92688        testcase( i==32 );
92689        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
92690        sqlite3ColumnDefault(v, pTab, i, regNew+i);
92691      }
92692    }
92693  }
92694
92695  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
92696  ** verified. One could argue that this is wrong.
92697  */
92698  if( tmask&TRIGGER_BEFORE ){
92699    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
92700    sqlite3TableAffinityStr(v, pTab);
92701    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
92702        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
92703
92704    /* The row-trigger may have deleted the row being updated. In this
92705    ** case, jump to the next row. No updates or AFTER triggers are
92706    ** required. This behaviour - what happens when the row being updated
92707    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
92708    ** documentation.
92709    */
92710    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
92711
92712    /* If it did not delete it, the row-trigger may still have modified
92713    ** some of the columns of the row being updated. Load the values for
92714    ** all columns not modified by the update statement into their
92715    ** registers in case this has happened.
92716    */
92717    for(i=0; i<pTab->nCol; i++){
92718      if( aXRef[i]<0 && i!=pTab->iPKey ){
92719        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
92720        sqlite3ColumnDefault(v, pTab, i, regNew+i);
92721      }
92722    }
92723  }
92724
92725  if( !isView ){
92726    int j1;                       /* Address of jump instruction */
92727
92728    /* Do constraint checks. */
92729    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
92730        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
92731
92732    /* Do FK constraint checks. */
92733    if( hasFK ){
92734      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
92735    }
92736
92737    /* Delete the index entries associated with the current record.  */
92738    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
92739    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
92740
92741    /* If changing the record number, delete the old record.  */
92742    if( hasFK || chngRowid ){
92743      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
92744    }
92745    sqlite3VdbeJumpHere(v, j1);
92746
92747    if( hasFK ){
92748      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
92749    }
92750
92751    /* Insert the new index entries and the new record. */
92752    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
92753
92754    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
92755    ** handle rows (possibly in other tables) that refer via a foreign key
92756    ** to the row just updated. */
92757    if( hasFK ){
92758      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
92759    }
92760  }
92761
92762  /* Increment the row counter
92763  */
92764  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
92765    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
92766  }
92767
92768  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
92769      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
92770
92771  /* Repeat the above with the next record to be updated, until
92772  ** all record selected by the WHERE clause have been updated.
92773  */
92774  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
92775  sqlite3VdbeJumpHere(v, addr);
92776
92777  /* Close all tables */
92778  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
92779    if( openAll || aRegIdx[i]>0 ){
92780      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
92781    }
92782  }
92783  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
92784
92785  /* Update the sqlite_sequence table by storing the content of the
92786  ** maximum rowid counter values recorded while inserting into
92787  ** autoincrement tables.
92788  */
92789  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
92790    sqlite3AutoincrementEnd(pParse);
92791  }
92792
92793  /*
92794  ** Return the number of rows that were changed. If this routine is
92795  ** generating code because of a call to sqlite3NestedParse(), do not
92796  ** invoke the callback function.
92797  */
92798  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
92799    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
92800    sqlite3VdbeSetNumCols(v, 1);
92801    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
92802  }
92803
92804update_cleanup:
92805  sqlite3AuthContextPop(&sContext);
92806  sqlite3DbFree(db, aRegIdx);
92807  sqlite3DbFree(db, aXRef);
92808  sqlite3SrcListDelete(db, pTabList);
92809  sqlite3ExprListDelete(db, pChanges);
92810  sqlite3ExprDelete(db, pWhere);
92811  return;
92812}
92813/* Make sure "isView" and other macros defined above are undefined. Otherwise
92814** thely may interfere with compilation of other functions in this file
92815** (or in another file, if this file becomes part of the amalgamation).  */
92816#ifdef isView
92817 #undef isView
92818#endif
92819#ifdef pTrigger
92820 #undef pTrigger
92821#endif
92822
92823#ifndef SQLITE_OMIT_VIRTUALTABLE
92824/*
92825** Generate code for an UPDATE of a virtual table.
92826**
92827** The strategy is that we create an ephemerial table that contains
92828** for each row to be changed:
92829**
92830**   (A)  The original rowid of that row.
92831**   (B)  The revised rowid for the row. (note1)
92832**   (C)  The content of every column in the row.
92833**
92834** Then we loop over this ephemeral table and for each row in
92835** the ephermeral table call VUpdate.
92836**
92837** When finished, drop the ephemeral table.
92838**
92839** (note1) Actually, if we know in advance that (A) is always the same
92840** as (B) we only store (A), then duplicate (A) when pulling
92841** it out of the ephemeral table before calling VUpdate.
92842*/
92843static void updateVirtualTable(
92844  Parse *pParse,       /* The parsing context */
92845  SrcList *pSrc,       /* The virtual table to be modified */
92846  Table *pTab,         /* The virtual table */
92847  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
92848  Expr *pRowid,        /* Expression used to recompute the rowid */
92849  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
92850  Expr *pWhere         /* WHERE clause of the UPDATE statement */
92851){
92852  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
92853  ExprList *pEList = 0;     /* The result set of the SELECT statement */
92854  Select *pSelect = 0;      /* The SELECT statement */
92855  Expr *pExpr;              /* Temporary expression */
92856  int ephemTab;             /* Table holding the result of the SELECT */
92857  int i;                    /* Loop counter */
92858  int addr;                 /* Address of top of loop */
92859  int iReg;                 /* First register in set passed to OP_VUpdate */
92860  sqlite3 *db = pParse->db; /* Database connection */
92861  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
92862  SelectDest dest;
92863
92864  /* Construct the SELECT statement that will find the new values for
92865  ** all updated rows.
92866  */
92867  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
92868  if( pRowid ){
92869    pEList = sqlite3ExprListAppend(pParse, pEList,
92870                                   sqlite3ExprDup(db, pRowid, 0));
92871  }
92872  assert( pTab->iPKey<0 );
92873  for(i=0; i<pTab->nCol; i++){
92874    if( aXRef[i]>=0 ){
92875      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
92876    }else{
92877      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
92878    }
92879    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
92880  }
92881  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
92882
92883  /* Create the ephemeral table into which the update results will
92884  ** be stored.
92885  */
92886  assert( v );
92887  ephemTab = pParse->nTab++;
92888  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
92889
92890  /* fill the ephemeral table
92891  */
92892  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
92893  sqlite3Select(pParse, pSelect, &dest);
92894
92895  /* Generate code to scan the ephemeral table and call VUpdate. */
92896  iReg = ++pParse->nMem;
92897  pParse->nMem += pTab->nCol+1;
92898  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
92899  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
92900  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
92901  for(i=0; i<pTab->nCol; i++){
92902    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
92903  }
92904  sqlite3VtabMakeWritable(pParse, pTab);
92905  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
92906  sqlite3MayAbort(pParse);
92907  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
92908  sqlite3VdbeJumpHere(v, addr);
92909  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
92910
92911  /* Cleanup */
92912  sqlite3SelectDelete(db, pSelect);
92913}
92914#endif /* SQLITE_OMIT_VIRTUALTABLE */
92915
92916/************** End of update.c **********************************************/
92917/************** Begin file vacuum.c ******************************************/
92918/*
92919** 2003 April 6
92920**
92921** The author disclaims copyright to this source code.  In place of
92922** a legal notice, here is a blessing:
92923**
92924**    May you do good and not evil.
92925**    May you find forgiveness for yourself and forgive others.
92926**    May you share freely, never taking more than you give.
92927**
92928*************************************************************************
92929** This file contains code used to implement the VACUUM command.
92930**
92931** Most of the code in this file may be omitted by defining the
92932** SQLITE_OMIT_VACUUM macro.
92933*/
92934
92935#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
92936/*
92937** Finalize a prepared statement.  If there was an error, store the
92938** text of the error message in *pzErrMsg.  Return the result code.
92939*/
92940static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
92941  int rc;
92942  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
92943  if( rc ){
92944    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
92945  }
92946  return rc;
92947}
92948
92949/*
92950** Execute zSql on database db. Return an error code.
92951*/
92952static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
92953  sqlite3_stmt *pStmt;
92954  VVA_ONLY( int rc; )
92955  if( !zSql ){
92956    return SQLITE_NOMEM;
92957  }
92958  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
92959    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
92960    return sqlite3_errcode(db);
92961  }
92962  VVA_ONLY( rc = ) sqlite3_step(pStmt);
92963  assert( rc!=SQLITE_ROW );
92964  return vacuumFinalize(db, pStmt, pzErrMsg);
92965}
92966
92967/*
92968** Execute zSql on database db. The statement returns exactly
92969** one column. Execute this as SQL on the same database.
92970*/
92971static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
92972  sqlite3_stmt *pStmt;
92973  int rc;
92974
92975  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
92976  if( rc!=SQLITE_OK ) return rc;
92977
92978  while( SQLITE_ROW==sqlite3_step(pStmt) ){
92979    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
92980    if( rc!=SQLITE_OK ){
92981      vacuumFinalize(db, pStmt, pzErrMsg);
92982      return rc;
92983    }
92984  }
92985
92986  return vacuumFinalize(db, pStmt, pzErrMsg);
92987}
92988
92989/*
92990** The non-standard VACUUM command is used to clean up the database,
92991** collapse free space, etc.  It is modelled after the VACUUM command
92992** in PostgreSQL.
92993**
92994** In version 1.0.x of SQLite, the VACUUM command would call
92995** gdbm_reorganize() on all the database tables.  But beginning
92996** with 2.0.0, SQLite no longer uses GDBM so this command has
92997** become a no-op.
92998*/
92999SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
93000  Vdbe *v = sqlite3GetVdbe(pParse);
93001  if( v ){
93002    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
93003  }
93004  return;
93005}
93006
93007/*
93008** This routine implements the OP_Vacuum opcode of the VDBE.
93009*/
93010SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
93011  int rc = SQLITE_OK;     /* Return code from service routines */
93012  Btree *pMain;           /* The database being vacuumed */
93013  Btree *pTemp;           /* The temporary database we vacuum into */
93014  char *zSql = 0;         /* SQL statements */
93015  int saved_flags;        /* Saved value of the db->flags */
93016  int saved_nChange;      /* Saved value of db->nChange */
93017  int saved_nTotalChange; /* Saved value of db->nTotalChange */
93018  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
93019  Db *pDb = 0;            /* Database to detach at end of vacuum */
93020  int isMemDb;            /* True if vacuuming a :memory: database */
93021  int nRes;               /* Bytes of reserved space at the end of each page */
93022  int nDb;                /* Number of attached databases */
93023
93024  if( !db->autoCommit ){
93025    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
93026    return SQLITE_ERROR;
93027  }
93028
93029  /* Save the current value of the database flags so that it can be
93030  ** restored before returning. Then set the writable-schema flag, and
93031  ** disable CHECK and foreign key constraints.  */
93032  saved_flags = db->flags;
93033  saved_nChange = db->nChange;
93034  saved_nTotalChange = db->nTotalChange;
93035  saved_xTrace = db->xTrace;
93036  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
93037  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
93038  db->xTrace = 0;
93039
93040  pMain = db->aDb[0].pBt;
93041  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
93042
93043  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
93044  ** can be set to 'off' for this file, as it is not recovered if a crash
93045  ** occurs anyway. The integrity of the database is maintained by a
93046  ** (possibly synchronous) transaction opened on the main database before
93047  ** sqlite3BtreeCopyFile() is called.
93048  **
93049  ** An optimisation would be to use a non-journaled pager.
93050  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
93051  ** that actually made the VACUUM run slower.  Very little journalling
93052  ** actually occurs when doing a vacuum since the vacuum_db is initially
93053  ** empty.  Only the journal header is written.  Apparently it takes more
93054  ** time to parse and run the PRAGMA to turn journalling off than it does
93055  ** to write the journal header file.
93056  */
93057  nDb = db->nDb;
93058  if( sqlite3TempInMemory(db) ){
93059    zSql = "ATTACH ':memory:' AS vacuum_db;";
93060  }else{
93061    zSql = "ATTACH '' AS vacuum_db;";
93062  }
93063  rc = execSql(db, pzErrMsg, zSql);
93064  if( db->nDb>nDb ){
93065    pDb = &db->aDb[db->nDb-1];
93066    assert( strcmp(pDb->zName,"vacuum_db")==0 );
93067  }
93068  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93069  pTemp = db->aDb[db->nDb-1].pBt;
93070
93071  /* The call to execSql() to attach the temp database has left the file
93072  ** locked (as there was more than one active statement when the transaction
93073  ** to read the schema was concluded. Unlock it here so that this doesn't
93074  ** cause problems for the call to BtreeSetPageSize() below.  */
93075  sqlite3BtreeCommit(pTemp);
93076
93077  nRes = sqlite3BtreeGetReserve(pMain);
93078
93079  /* A VACUUM cannot change the pagesize of an encrypted database. */
93080#ifdef SQLITE_HAS_CODEC
93081  if( db->nextPagesize ){
93082    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
93083    int nKey;
93084    char *zKey;
93085    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
93086    if( nKey ) db->nextPagesize = 0;
93087  }
93088#endif
93089
93090  /* Do not attempt to change the page size for a WAL database */
93091  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
93092                                               ==PAGER_JOURNALMODE_WAL ){
93093    db->nextPagesize = 0;
93094  }
93095
93096  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
93097   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
93098   || NEVER(db->mallocFailed)
93099  ){
93100    rc = SQLITE_NOMEM;
93101    goto end_of_vacuum;
93102  }
93103  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
93104  if( rc!=SQLITE_OK ){
93105    goto end_of_vacuum;
93106  }
93107
93108#ifndef SQLITE_OMIT_AUTOVACUUM
93109  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
93110                                           sqlite3BtreeGetAutoVacuum(pMain));
93111#endif
93112
93113  /* Begin a transaction */
93114  rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
93115  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93116
93117  /* Query the schema of the main database. Create a mirror schema
93118  ** in the temporary database.
93119  */
93120  rc = execExecSql(db, pzErrMsg,
93121      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
93122      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
93123      "   AND rootpage>0"
93124  );
93125  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93126  rc = execExecSql(db, pzErrMsg,
93127      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
93128      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
93129  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93130  rc = execExecSql(db, pzErrMsg,
93131      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
93132      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
93133  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93134
93135  /* Loop through the tables in the main database. For each, do
93136  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
93137  ** the contents to the temporary database.
93138  */
93139  rc = execExecSql(db, pzErrMsg,
93140      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
93141      "|| ' SELECT * FROM main.' || quote(name) || ';'"
93142      "FROM main.sqlite_master "
93143      "WHERE type = 'table' AND name!='sqlite_sequence' "
93144      "  AND rootpage>0"
93145  );
93146  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93147
93148  /* Copy over the sequence table
93149  */
93150  rc = execExecSql(db, pzErrMsg,
93151      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
93152      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
93153  );
93154  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93155  rc = execExecSql(db, pzErrMsg,
93156      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
93157      "|| ' SELECT * FROM main.' || quote(name) || ';' "
93158      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
93159  );
93160  if( rc!=SQLITE_OK ) goto end_of_vacuum;
93161
93162
93163  /* Copy the triggers, views, and virtual tables from the main database
93164  ** over to the temporary database.  None of these objects has any
93165  ** associated storage, so all we have to do is copy their entries
93166  ** from the SQLITE_MASTER table.
93167  */
93168  rc = execSql(db, pzErrMsg,
93169      "INSERT INTO vacuum_db.sqlite_master "
93170      "  SELECT type, name, tbl_name, rootpage, sql"
93171      "    FROM main.sqlite_master"
93172      "   WHERE type='view' OR type='trigger'"
93173      "      OR (type='table' AND rootpage=0)"
93174  );
93175  if( rc ) goto end_of_vacuum;
93176
93177  /* At this point, unless the main db was completely empty, there is now a
93178  ** transaction open on the vacuum database, but not on the main database.
93179  ** Open a btree level transaction on the main database. This allows a
93180  ** call to sqlite3BtreeCopyFile(). The main database btree level
93181  ** transaction is then committed, so the SQL level never knows it was
93182  ** opened for writing. This way, the SQL transaction used to create the
93183  ** temporary database never needs to be committed.
93184  */
93185  {
93186    u32 meta;
93187    int i;
93188
93189    /* This array determines which meta meta values are preserved in the
93190    ** vacuum.  Even entries are the meta value number and odd entries
93191    ** are an increment to apply to the meta value after the vacuum.
93192    ** The increment is used to increase the schema cookie so that other
93193    ** connections to the same database will know to reread the schema.
93194    */
93195    static const unsigned char aCopy[] = {
93196       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
93197       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
93198       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
93199       BTREE_USER_VERSION,       0,  /* Preserve the user version */
93200    };
93201
93202    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
93203    assert( 1==sqlite3BtreeIsInTrans(pMain) );
93204
93205    /* Copy Btree meta values */
93206    for(i=0; i<ArraySize(aCopy); i+=2){
93207      /* GetMeta() and UpdateMeta() cannot fail in this context because
93208      ** we already have page 1 loaded into cache and marked dirty. */
93209      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
93210      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
93211      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
93212    }
93213
93214    rc = sqlite3BtreeCopyFile(pMain, pTemp);
93215    if( rc!=SQLITE_OK ) goto end_of_vacuum;
93216    rc = sqlite3BtreeCommit(pTemp);
93217    if( rc!=SQLITE_OK ) goto end_of_vacuum;
93218#ifndef SQLITE_OMIT_AUTOVACUUM
93219    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
93220#endif
93221  }
93222
93223  assert( rc==SQLITE_OK );
93224  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
93225
93226end_of_vacuum:
93227  /* Restore the original value of db->flags */
93228  db->flags = saved_flags;
93229  db->nChange = saved_nChange;
93230  db->nTotalChange = saved_nTotalChange;
93231  db->xTrace = saved_xTrace;
93232  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
93233
93234  /* Currently there is an SQL level transaction open on the vacuum
93235  ** database. No locks are held on any other files (since the main file
93236  ** was committed at the btree level). So it safe to end the transaction
93237  ** by manually setting the autoCommit flag to true and detaching the
93238  ** vacuum database. The vacuum_db journal file is deleted when the pager
93239  ** is closed by the DETACH.
93240  */
93241  db->autoCommit = 1;
93242
93243  if( pDb ){
93244    sqlite3BtreeClose(pDb->pBt);
93245    pDb->pBt = 0;
93246    pDb->pSchema = 0;
93247  }
93248
93249  sqlite3ResetInternalSchema(db, 0);
93250
93251  return rc;
93252}
93253#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
93254
93255/************** End of vacuum.c **********************************************/
93256/************** Begin file vtab.c ********************************************/
93257/*
93258** 2006 June 10
93259**
93260** The author disclaims copyright to this source code.  In place of
93261** a legal notice, here is a blessing:
93262**
93263**    May you do good and not evil.
93264**    May you find forgiveness for yourself and forgive others.
93265**    May you share freely, never taking more than you give.
93266**
93267*************************************************************************
93268** This file contains code used to help implement virtual tables.
93269*/
93270#ifndef SQLITE_OMIT_VIRTUALTABLE
93271
93272/*
93273** The actual function that does the work of creating a new module.
93274** This function implements the sqlite3_create_module() and
93275** sqlite3_create_module_v2() interfaces.
93276*/
93277static int createModule(
93278  sqlite3 *db,                    /* Database in which module is registered */
93279  const char *zName,              /* Name assigned to this module */
93280  const sqlite3_module *pModule,  /* The definition of the module */
93281  void *pAux,                     /* Context pointer for xCreate/xConnect */
93282  void (*xDestroy)(void *)        /* Module destructor function */
93283){
93284  int rc, nName;
93285  Module *pMod;
93286
93287  sqlite3_mutex_enter(db->mutex);
93288  nName = sqlite3Strlen30(zName);
93289  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
93290  if( pMod ){
93291    Module *pDel;
93292    char *zCopy = (char *)(&pMod[1]);
93293    memcpy(zCopy, zName, nName+1);
93294    pMod->zName = zCopy;
93295    pMod->pModule = pModule;
93296    pMod->pAux = pAux;
93297    pMod->xDestroy = xDestroy;
93298    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
93299    if( pDel && pDel->xDestroy ){
93300      pDel->xDestroy(pDel->pAux);
93301    }
93302    sqlite3DbFree(db, pDel);
93303    if( pDel==pMod ){
93304      db->mallocFailed = 1;
93305    }
93306    sqlite3ResetInternalSchema(db, 0);
93307  }else if( xDestroy ){
93308    xDestroy(pAux);
93309  }
93310  rc = sqlite3ApiExit(db, SQLITE_OK);
93311  sqlite3_mutex_leave(db->mutex);
93312  return rc;
93313}
93314
93315
93316/*
93317** External API function used to create a new virtual-table module.
93318*/
93319SQLITE_API int sqlite3_create_module(
93320  sqlite3 *db,                    /* Database in which module is registered */
93321  const char *zName,              /* Name assigned to this module */
93322  const sqlite3_module *pModule,  /* The definition of the module */
93323  void *pAux                      /* Context pointer for xCreate/xConnect */
93324){
93325  return createModule(db, zName, pModule, pAux, 0);
93326}
93327
93328/*
93329** External API function used to create a new virtual-table module.
93330*/
93331SQLITE_API int sqlite3_create_module_v2(
93332  sqlite3 *db,                    /* Database in which module is registered */
93333  const char *zName,              /* Name assigned to this module */
93334  const sqlite3_module *pModule,  /* The definition of the module */
93335  void *pAux,                     /* Context pointer for xCreate/xConnect */
93336  void (*xDestroy)(void *)        /* Module destructor function */
93337){
93338  return createModule(db, zName, pModule, pAux, xDestroy);
93339}
93340
93341/*
93342** Lock the virtual table so that it cannot be disconnected.
93343** Locks nest.  Every lock should have a corresponding unlock.
93344** If an unlock is omitted, resources leaks will occur.
93345**
93346** If a disconnect is attempted while a virtual table is locked,
93347** the disconnect is deferred until all locks have been removed.
93348*/
93349SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
93350  pVTab->nRef++;
93351}
93352
93353
93354/*
93355** pTab is a pointer to a Table structure representing a virtual-table.
93356** Return a pointer to the VTable object used by connection db to access
93357** this virtual-table, if one has been created, or NULL otherwise.
93358*/
93359SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
93360  VTable *pVtab;
93361  assert( IsVirtual(pTab) );
93362  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
93363  return pVtab;
93364}
93365
93366/*
93367** Decrement the ref-count on a virtual table object. When the ref-count
93368** reaches zero, call the xDisconnect() method to delete the object.
93369*/
93370SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
93371  sqlite3 *db = pVTab->db;
93372
93373  assert( db );
93374  assert( pVTab->nRef>0 );
93375  assert( sqlite3SafetyCheckOk(db) );
93376
93377  pVTab->nRef--;
93378  if( pVTab->nRef==0 ){
93379    sqlite3_vtab *p = pVTab->pVtab;
93380    if( p ){
93381      p->pModule->xDisconnect(p);
93382    }
93383    sqlite3DbFree(db, pVTab);
93384  }
93385}
93386
93387/*
93388** Table p is a virtual table. This function moves all elements in the
93389** p->pVTable list to the sqlite3.pDisconnect lists of their associated
93390** database connections to be disconnected at the next opportunity.
93391** Except, if argument db is not NULL, then the entry associated with
93392** connection db is left in the p->pVTable list.
93393*/
93394static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
93395  VTable *pRet = 0;
93396  VTable *pVTable = p->pVTable;
93397  p->pVTable = 0;
93398
93399  /* Assert that the mutex (if any) associated with the BtShared database
93400  ** that contains table p is held by the caller. See header comments
93401  ** above function sqlite3VtabUnlockList() for an explanation of why
93402  ** this makes it safe to access the sqlite3.pDisconnect list of any
93403  ** database connection that may have an entry in the p->pVTable list.  */
93404  assert( db==0 ||
93405    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
93406  );
93407
93408  while( pVTable ){
93409    sqlite3 *db2 = pVTable->db;
93410    VTable *pNext = pVTable->pNext;
93411    assert( db2 );
93412    if( db2==db ){
93413      pRet = pVTable;
93414      p->pVTable = pRet;
93415      pRet->pNext = 0;
93416    }else{
93417      pVTable->pNext = db2->pDisconnect;
93418      db2->pDisconnect = pVTable;
93419    }
93420    pVTable = pNext;
93421  }
93422
93423  assert( !db || pRet );
93424  return pRet;
93425}
93426
93427
93428/*
93429** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
93430**
93431** This function may only be called when the mutexes associated with all
93432** shared b-tree databases opened using connection db are held by the
93433** caller. This is done to protect the sqlite3.pDisconnect list. The
93434** sqlite3.pDisconnect list is accessed only as follows:
93435**
93436**   1) By this function. In this case, all BtShared mutexes and the mutex
93437**      associated with the database handle itself must be held.
93438**
93439**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
93440**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
93441**      associated with the database the virtual table is stored in is held
93442**      or, if the virtual table is stored in a non-sharable database, then
93443**      the database handle mutex is held.
93444**
93445** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
93446** by multiple threads. It is thread-safe.
93447*/
93448SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
93449  VTable *p = db->pDisconnect;
93450  db->pDisconnect = 0;
93451
93452  assert( sqlite3BtreeHoldsAllMutexes(db) );
93453  assert( sqlite3_mutex_held(db->mutex) );
93454
93455  if( p ){
93456    sqlite3ExpirePreparedStatements(db);
93457    do {
93458      VTable *pNext = p->pNext;
93459      sqlite3VtabUnlock(p);
93460      p = pNext;
93461    }while( p );
93462  }
93463}
93464
93465/*
93466** Clear any and all virtual-table information from the Table record.
93467** This routine is called, for example, just before deleting the Table
93468** record.
93469**
93470** Since it is a virtual-table, the Table structure contains a pointer
93471** to the head of a linked list of VTable structures. Each VTable
93472** structure is associated with a single sqlite3* user of the schema.
93473** The reference count of the VTable structure associated with database
93474** connection db is decremented immediately (which may lead to the
93475** structure being xDisconnected and free). Any other VTable structures
93476** in the list are moved to the sqlite3.pDisconnect list of the associated
93477** database connection.
93478*/
93479SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
93480  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
93481  if( p->azModuleArg ){
93482    int i;
93483    for(i=0; i<p->nModuleArg; i++){
93484      sqlite3DbFree(db, p->azModuleArg[i]);
93485    }
93486    sqlite3DbFree(db, p->azModuleArg);
93487  }
93488}
93489
93490/*
93491** Add a new module argument to pTable->azModuleArg[].
93492** The string is not copied - the pointer is stored.  The
93493** string will be freed automatically when the table is
93494** deleted.
93495*/
93496static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
93497  int i = pTable->nModuleArg++;
93498  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
93499  char **azModuleArg;
93500  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
93501  if( azModuleArg==0 ){
93502    int j;
93503    for(j=0; j<i; j++){
93504      sqlite3DbFree(db, pTable->azModuleArg[j]);
93505    }
93506    sqlite3DbFree(db, zArg);
93507    sqlite3DbFree(db, pTable->azModuleArg);
93508    pTable->nModuleArg = 0;
93509  }else{
93510    azModuleArg[i] = zArg;
93511    azModuleArg[i+1] = 0;
93512  }
93513  pTable->azModuleArg = azModuleArg;
93514}
93515
93516/*
93517** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
93518** statement.  The module name has been parsed, but the optional list
93519** of parameters that follow the module name are still pending.
93520*/
93521SQLITE_PRIVATE void sqlite3VtabBeginParse(
93522  Parse *pParse,        /* Parsing context */
93523  Token *pName1,        /* Name of new table, or database name */
93524  Token *pName2,        /* Name of new table or NULL */
93525  Token *pModuleName    /* Name of the module for the virtual table */
93526){
93527  int iDb;              /* The database the table is being created in */
93528  Table *pTable;        /* The new virtual table */
93529  sqlite3 *db;          /* Database connection */
93530
93531  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
93532  pTable = pParse->pNewTable;
93533  if( pTable==0 ) return;
93534  assert( 0==pTable->pIndex );
93535
93536  db = pParse->db;
93537  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
93538  assert( iDb>=0 );
93539
93540  pTable->tabFlags |= TF_Virtual;
93541  pTable->nModuleArg = 0;
93542  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
93543  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
93544  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
93545  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
93546
93547#ifndef SQLITE_OMIT_AUTHORIZATION
93548  /* Creating a virtual table invokes the authorization callback twice.
93549  ** The first invocation, to obtain permission to INSERT a row into the
93550  ** sqlite_master table, has already been made by sqlite3StartTable().
93551  ** The second call, to obtain permission to create the table, is made now.
93552  */
93553  if( pTable->azModuleArg ){
93554    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
93555            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
93556  }
93557#endif
93558}
93559
93560/*
93561** This routine takes the module argument that has been accumulating
93562** in pParse->zArg[] and appends it to the list of arguments on the
93563** virtual table currently under construction in pParse->pTable.
93564*/
93565static void addArgumentToVtab(Parse *pParse){
93566  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
93567    const char *z = (const char*)pParse->sArg.z;
93568    int n = pParse->sArg.n;
93569    sqlite3 *db = pParse->db;
93570    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
93571  }
93572}
93573
93574/*
93575** The parser calls this routine after the CREATE VIRTUAL TABLE statement
93576** has been completely parsed.
93577*/
93578SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
93579  Table *pTab = pParse->pNewTable;  /* The table being constructed */
93580  sqlite3 *db = pParse->db;         /* The database connection */
93581
93582  if( pTab==0 ) return;
93583  addArgumentToVtab(pParse);
93584  pParse->sArg.z = 0;
93585  if( pTab->nModuleArg<1 ) return;
93586
93587  /* If the CREATE VIRTUAL TABLE statement is being entered for the
93588  ** first time (in other words if the virtual table is actually being
93589  ** created now instead of just being read out of sqlite_master) then
93590  ** do additional initialization work and store the statement text
93591  ** in the sqlite_master table.
93592  */
93593  if( !db->init.busy ){
93594    char *zStmt;
93595    char *zWhere;
93596    int iDb;
93597    Vdbe *v;
93598
93599    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
93600    if( pEnd ){
93601      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
93602    }
93603    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
93604
93605    /* A slot for the record has already been allocated in the
93606    ** SQLITE_MASTER table.  We just need to update that slot with all
93607    ** the information we've collected.
93608    **
93609    ** The VM register number pParse->regRowid holds the rowid of an
93610    ** entry in the sqlite_master table tht was created for this vtab
93611    ** by sqlite3StartTable().
93612    */
93613    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93614    sqlite3NestedParse(pParse,
93615      "UPDATE %Q.%s "
93616         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
93617       "WHERE rowid=#%d",
93618      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
93619      pTab->zName,
93620      pTab->zName,
93621      zStmt,
93622      pParse->regRowid
93623    );
93624    sqlite3DbFree(db, zStmt);
93625    v = sqlite3GetVdbe(pParse);
93626    sqlite3ChangeCookie(pParse, iDb);
93627
93628    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93629    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
93630    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
93631    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
93632                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
93633  }
93634
93635  /* If we are rereading the sqlite_master table create the in-memory
93636  ** record of the table. The xConnect() method is not called until
93637  ** the first time the virtual table is used in an SQL statement. This
93638  ** allows a schema that contains virtual tables to be loaded before
93639  ** the required virtual table implementations are registered.  */
93640  else {
93641    Table *pOld;
93642    Schema *pSchema = pTab->pSchema;
93643    const char *zName = pTab->zName;
93644    int nName = sqlite3Strlen30(zName);
93645    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
93646    if( pOld ){
93647      db->mallocFailed = 1;
93648      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
93649      return;
93650    }
93651    pParse->pNewTable = 0;
93652  }
93653}
93654
93655/*
93656** The parser calls this routine when it sees the first token
93657** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
93658*/
93659SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
93660  addArgumentToVtab(pParse);
93661  pParse->sArg.z = 0;
93662  pParse->sArg.n = 0;
93663}
93664
93665/*
93666** The parser calls this routine for each token after the first token
93667** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
93668*/
93669SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
93670  Token *pArg = &pParse->sArg;
93671  if( pArg->z==0 ){
93672    pArg->z = p->z;
93673    pArg->n = p->n;
93674  }else{
93675    assert(pArg->z < p->z);
93676    pArg->n = (int)(&p->z[p->n] - pArg->z);
93677  }
93678}
93679
93680/*
93681** Invoke a virtual table constructor (either xCreate or xConnect). The
93682** pointer to the function to invoke is passed as the fourth parameter
93683** to this procedure.
93684*/
93685static int vtabCallConstructor(
93686  sqlite3 *db,
93687  Table *pTab,
93688  Module *pMod,
93689  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
93690  char **pzErr
93691){
93692  VTable *pVTable;
93693  int rc;
93694  const char *const*azArg = (const char *const*)pTab->azModuleArg;
93695  int nArg = pTab->nModuleArg;
93696  char *zErr = 0;
93697  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
93698
93699  if( !zModuleName ){
93700    return SQLITE_NOMEM;
93701  }
93702
93703  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
93704  if( !pVTable ){
93705    sqlite3DbFree(db, zModuleName);
93706    return SQLITE_NOMEM;
93707  }
93708  pVTable->db = db;
93709  pVTable->pMod = pMod;
93710
93711  assert( !db->pVTab );
93712  assert( xConstruct );
93713  db->pVTab = pTab;
93714
93715  /* Invoke the virtual table constructor */
93716  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
93717  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
93718
93719  if( SQLITE_OK!=rc ){
93720    if( zErr==0 ){
93721      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
93722    }else {
93723      *pzErr = sqlite3MPrintf(db, "%s", zErr);
93724      sqlite3_free(zErr);
93725    }
93726    sqlite3DbFree(db, pVTable);
93727  }else if( ALWAYS(pVTable->pVtab) ){
93728    /* Justification of ALWAYS():  A correct vtab constructor must allocate
93729    ** the sqlite3_vtab object if successful.  */
93730    pVTable->pVtab->pModule = pMod->pModule;
93731    pVTable->nRef = 1;
93732    if( db->pVTab ){
93733      const char *zFormat = "vtable constructor did not declare schema: %s";
93734      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
93735      sqlite3VtabUnlock(pVTable);
93736      rc = SQLITE_ERROR;
93737    }else{
93738      int iCol;
93739      /* If everything went according to plan, link the new VTable structure
93740      ** into the linked list headed by pTab->pVTable. Then loop through the
93741      ** columns of the table to see if any of them contain the token "hidden".
93742      ** If so, set the Column.isHidden flag and remove the token from
93743      ** the type string.  */
93744      pVTable->pNext = pTab->pVTable;
93745      pTab->pVTable = pVTable;
93746
93747      for(iCol=0; iCol<pTab->nCol; iCol++){
93748        char *zType = pTab->aCol[iCol].zType;
93749        int nType;
93750        int i = 0;
93751        if( !zType ) continue;
93752        nType = sqlite3Strlen30(zType);
93753        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
93754          for(i=0; i<nType; i++){
93755            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
93756             && (zType[i+7]=='\0' || zType[i+7]==' ')
93757            ){
93758              i++;
93759              break;
93760            }
93761          }
93762        }
93763        if( i<nType ){
93764          int j;
93765          int nDel = 6 + (zType[i+6] ? 1 : 0);
93766          for(j=i; (j+nDel)<=nType; j++){
93767            zType[j] = zType[j+nDel];
93768          }
93769          if( zType[i]=='\0' && i>0 ){
93770            assert(zType[i-1]==' ');
93771            zType[i-1] = '\0';
93772          }
93773          pTab->aCol[iCol].isHidden = 1;
93774        }
93775      }
93776    }
93777  }
93778
93779  sqlite3DbFree(db, zModuleName);
93780  db->pVTab = 0;
93781  return rc;
93782}
93783
93784/*
93785** This function is invoked by the parser to call the xConnect() method
93786** of the virtual table pTab. If an error occurs, an error code is returned
93787** and an error left in pParse.
93788**
93789** This call is a no-op if table pTab is not a virtual table.
93790*/
93791SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
93792  sqlite3 *db = pParse->db;
93793  const char *zMod;
93794  Module *pMod;
93795  int rc;
93796
93797  assert( pTab );
93798  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
93799    return SQLITE_OK;
93800  }
93801
93802  /* Locate the required virtual table module */
93803  zMod = pTab->azModuleArg[0];
93804  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
93805
93806  if( !pMod ){
93807    const char *zModule = pTab->azModuleArg[0];
93808    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
93809    rc = SQLITE_ERROR;
93810  }else{
93811    char *zErr = 0;
93812    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
93813    if( rc!=SQLITE_OK ){
93814      sqlite3ErrorMsg(pParse, "%s", zErr);
93815    }
93816    sqlite3DbFree(db, zErr);
93817  }
93818
93819  return rc;
93820}
93821
93822/*
93823** Add the virtual table pVTab to the array sqlite3.aVTrans[].
93824*/
93825static int addToVTrans(sqlite3 *db, VTable *pVTab){
93826  const int ARRAY_INCR = 5;
93827
93828  /* Grow the sqlite3.aVTrans array if required */
93829  if( (db->nVTrans%ARRAY_INCR)==0 ){
93830    VTable **aVTrans;
93831    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
93832    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
93833    if( !aVTrans ){
93834      return SQLITE_NOMEM;
93835    }
93836    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
93837    db->aVTrans = aVTrans;
93838  }
93839
93840  /* Add pVtab to the end of sqlite3.aVTrans */
93841  db->aVTrans[db->nVTrans++] = pVTab;
93842  sqlite3VtabLock(pVTab);
93843  return SQLITE_OK;
93844}
93845
93846/*
93847** This function is invoked by the vdbe to call the xCreate method
93848** of the virtual table named zTab in database iDb.
93849**
93850** If an error occurs, *pzErr is set to point an an English language
93851** description of the error and an SQLITE_XXX error code is returned.
93852** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
93853*/
93854SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
93855  int rc = SQLITE_OK;
93856  Table *pTab;
93857  Module *pMod;
93858  const char *zMod;
93859
93860  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
93861  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
93862
93863  /* Locate the required virtual table module */
93864  zMod = pTab->azModuleArg[0];
93865  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
93866
93867  /* If the module has been registered and includes a Create method,
93868  ** invoke it now. If the module has not been registered, return an
93869  ** error. Otherwise, do nothing.
93870  */
93871  if( !pMod ){
93872    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
93873    rc = SQLITE_ERROR;
93874  }else{
93875    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
93876  }
93877
93878  /* Justification of ALWAYS():  The xConstructor method is required to
93879  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
93880  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
93881      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
93882  }
93883
93884  return rc;
93885}
93886
93887/*
93888** This function is used to set the schema of a virtual table.  It is only
93889** valid to call this function from within the xCreate() or xConnect() of a
93890** virtual table module.
93891*/
93892SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
93893  Parse *pParse;
93894
93895  int rc = SQLITE_OK;
93896  Table *pTab;
93897  char *zErr = 0;
93898
93899  sqlite3_mutex_enter(db->mutex);
93900  pTab = db->pVTab;
93901  if( !pTab ){
93902    sqlite3Error(db, SQLITE_MISUSE, 0);
93903    sqlite3_mutex_leave(db->mutex);
93904    return SQLITE_MISUSE_BKPT;
93905  }
93906  assert( (pTab->tabFlags & TF_Virtual)!=0 );
93907
93908  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
93909  if( pParse==0 ){
93910    rc = SQLITE_NOMEM;
93911  }else{
93912    pParse->declareVtab = 1;
93913    pParse->db = db;
93914    pParse->nQueryLoop = 1;
93915
93916    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
93917     && pParse->pNewTable
93918     && !db->mallocFailed
93919     && !pParse->pNewTable->pSelect
93920     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
93921    ){
93922      if( !pTab->aCol ){
93923        pTab->aCol = pParse->pNewTable->aCol;
93924        pTab->nCol = pParse->pNewTable->nCol;
93925        pParse->pNewTable->nCol = 0;
93926        pParse->pNewTable->aCol = 0;
93927      }
93928      db->pVTab = 0;
93929    }else{
93930      sqlite3Error(db, SQLITE_ERROR, zErr);
93931      sqlite3DbFree(db, zErr);
93932      rc = SQLITE_ERROR;
93933    }
93934    pParse->declareVtab = 0;
93935
93936    if( pParse->pVdbe ){
93937      sqlite3VdbeFinalize(pParse->pVdbe);
93938    }
93939    sqlite3DeleteTable(db, pParse->pNewTable);
93940    sqlite3StackFree(db, pParse);
93941  }
93942
93943  assert( (rc&0xff)==rc );
93944  rc = sqlite3ApiExit(db, rc);
93945  sqlite3_mutex_leave(db->mutex);
93946  return rc;
93947}
93948
93949/*
93950** This function is invoked by the vdbe to call the xDestroy method
93951** of the virtual table named zTab in database iDb. This occurs
93952** when a DROP TABLE is mentioned.
93953**
93954** This call is a no-op if zTab is not a virtual table.
93955*/
93956SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
93957  int rc = SQLITE_OK;
93958  Table *pTab;
93959
93960  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
93961  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
93962    VTable *p = vtabDisconnectAll(db, pTab);
93963
93964    assert( rc==SQLITE_OK );
93965    rc = p->pMod->pModule->xDestroy(p->pVtab);
93966
93967    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
93968    if( rc==SQLITE_OK ){
93969      assert( pTab->pVTable==p && p->pNext==0 );
93970      p->pVtab = 0;
93971      pTab->pVTable = 0;
93972      sqlite3VtabUnlock(p);
93973    }
93974  }
93975
93976  return rc;
93977}
93978
93979/*
93980** This function invokes either the xRollback or xCommit method
93981** of each of the virtual tables in the sqlite3.aVTrans array. The method
93982** called is identified by the second argument, "offset", which is
93983** the offset of the method to call in the sqlite3_module structure.
93984**
93985** The array is cleared after invoking the callbacks.
93986*/
93987static void callFinaliser(sqlite3 *db, int offset){
93988  int i;
93989  if( db->aVTrans ){
93990    for(i=0; i<db->nVTrans; i++){
93991      VTable *pVTab = db->aVTrans[i];
93992      sqlite3_vtab *p = pVTab->pVtab;
93993      if( p ){
93994        int (*x)(sqlite3_vtab *);
93995        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
93996        if( x ) x(p);
93997      }
93998      sqlite3VtabUnlock(pVTab);
93999    }
94000    sqlite3DbFree(db, db->aVTrans);
94001    db->nVTrans = 0;
94002    db->aVTrans = 0;
94003  }
94004}
94005
94006/*
94007** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
94008** array. Return the error code for the first error that occurs, or
94009** SQLITE_OK if all xSync operations are successful.
94010**
94011** Set *pzErrmsg to point to a buffer that should be released using
94012** sqlite3DbFree() containing an error message, if one is available.
94013*/
94014SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
94015  int i;
94016  int rc = SQLITE_OK;
94017  VTable **aVTrans = db->aVTrans;
94018
94019  db->aVTrans = 0;
94020  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
94021    int (*x)(sqlite3_vtab *);
94022    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
94023    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
94024      rc = x(pVtab);
94025      sqlite3DbFree(db, *pzErrmsg);
94026      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
94027      sqlite3_free(pVtab->zErrMsg);
94028    }
94029  }
94030  db->aVTrans = aVTrans;
94031  return rc;
94032}
94033
94034/*
94035** Invoke the xRollback method of all virtual tables in the
94036** sqlite3.aVTrans array. Then clear the array itself.
94037*/
94038SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
94039  callFinaliser(db, offsetof(sqlite3_module,xRollback));
94040  return SQLITE_OK;
94041}
94042
94043/*
94044** Invoke the xCommit method of all virtual tables in the
94045** sqlite3.aVTrans array. Then clear the array itself.
94046*/
94047SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
94048  callFinaliser(db, offsetof(sqlite3_module,xCommit));
94049  return SQLITE_OK;
94050}
94051
94052/*
94053** If the virtual table pVtab supports the transaction interface
94054** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
94055** not currently open, invoke the xBegin method now.
94056**
94057** If the xBegin call is successful, place the sqlite3_vtab pointer
94058** in the sqlite3.aVTrans array.
94059*/
94060SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
94061  int rc = SQLITE_OK;
94062  const sqlite3_module *pModule;
94063
94064  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
94065  ** than zero, then this function is being called from within a
94066  ** virtual module xSync() callback. It is illegal to write to
94067  ** virtual module tables in this case, so return SQLITE_LOCKED.
94068  */
94069  if( sqlite3VtabInSync(db) ){
94070    return SQLITE_LOCKED;
94071  }
94072  if( !pVTab ){
94073    return SQLITE_OK;
94074  }
94075  pModule = pVTab->pVtab->pModule;
94076
94077  if( pModule->xBegin ){
94078    int i;
94079
94080
94081    /* If pVtab is already in the aVTrans array, return early */
94082    for(i=0; i<db->nVTrans; i++){
94083      if( db->aVTrans[i]==pVTab ){
94084        return SQLITE_OK;
94085      }
94086    }
94087
94088    /* Invoke the xBegin method */
94089    rc = pModule->xBegin(pVTab->pVtab);
94090    if( rc==SQLITE_OK ){
94091      rc = addToVTrans(db, pVTab);
94092    }
94093  }
94094  return rc;
94095}
94096
94097/*
94098** The first parameter (pDef) is a function implementation.  The
94099** second parameter (pExpr) is the first argument to this function.
94100** If pExpr is a column in a virtual table, then let the virtual
94101** table implementation have an opportunity to overload the function.
94102**
94103** This routine is used to allow virtual table implementations to
94104** overload MATCH, LIKE, GLOB, and REGEXP operators.
94105**
94106** Return either the pDef argument (indicating no change) or a
94107** new FuncDef structure that is marked as ephemeral using the
94108** SQLITE_FUNC_EPHEM flag.
94109*/
94110SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
94111  sqlite3 *db,    /* Database connection for reporting malloc problems */
94112  FuncDef *pDef,  /* Function to possibly overload */
94113  int nArg,       /* Number of arguments to the function */
94114  Expr *pExpr     /* First argument to the function */
94115){
94116  Table *pTab;
94117  sqlite3_vtab *pVtab;
94118  sqlite3_module *pMod;
94119  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
94120  void *pArg = 0;
94121  FuncDef *pNew;
94122  int rc = 0;
94123  char *zLowerName;
94124  unsigned char *z;
94125
94126
94127  /* Check to see the left operand is a column in a virtual table */
94128  if( NEVER(pExpr==0) ) return pDef;
94129  if( pExpr->op!=TK_COLUMN ) return pDef;
94130  pTab = pExpr->pTab;
94131  if( NEVER(pTab==0) ) return pDef;
94132  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
94133  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
94134  assert( pVtab!=0 );
94135  assert( pVtab->pModule!=0 );
94136  pMod = (sqlite3_module *)pVtab->pModule;
94137  if( pMod->xFindFunction==0 ) return pDef;
94138
94139  /* Call the xFindFunction method on the virtual table implementation
94140  ** to see if the implementation wants to overload this function
94141  */
94142  zLowerName = sqlite3DbStrDup(db, pDef->zName);
94143  if( zLowerName ){
94144    for(z=(unsigned char*)zLowerName; *z; z++){
94145      *z = sqlite3UpperToLower[*z];
94146    }
94147    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
94148    sqlite3DbFree(db, zLowerName);
94149  }
94150  if( rc==0 ){
94151    return pDef;
94152  }
94153
94154  /* Create a new ephemeral function definition for the overloaded
94155  ** function */
94156  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
94157                             + sqlite3Strlen30(pDef->zName) + 1);
94158  if( pNew==0 ){
94159    return pDef;
94160  }
94161  *pNew = *pDef;
94162  pNew->zName = (char *)&pNew[1];
94163  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
94164  pNew->xFunc = xFunc;
94165  pNew->pUserData = pArg;
94166  pNew->flags |= SQLITE_FUNC_EPHEM;
94167  return pNew;
94168}
94169
94170/*
94171** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
94172** array so that an OP_VBegin will get generated for it.  Add pTab to the
94173** array if it is missing.  If pTab is already in the array, this routine
94174** is a no-op.
94175*/
94176SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
94177  Parse *pToplevel = sqlite3ParseToplevel(pParse);
94178  int i, n;
94179  Table **apVtabLock;
94180
94181  assert( IsVirtual(pTab) );
94182  for(i=0; i<pToplevel->nVtabLock; i++){
94183    if( pTab==pToplevel->apVtabLock[i] ) return;
94184  }
94185  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
94186  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
94187  if( apVtabLock ){
94188    pToplevel->apVtabLock = apVtabLock;
94189    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
94190  }else{
94191    pToplevel->db->mallocFailed = 1;
94192  }
94193}
94194
94195#endif /* SQLITE_OMIT_VIRTUALTABLE */
94196
94197/************** End of vtab.c ************************************************/
94198/************** Begin file where.c *******************************************/
94199/*
94200** 2001 September 15
94201**
94202** The author disclaims copyright to this source code.  In place of
94203** a legal notice, here is a blessing:
94204**
94205**    May you do good and not evil.
94206**    May you find forgiveness for yourself and forgive others.
94207**    May you share freely, never taking more than you give.
94208**
94209*************************************************************************
94210** This module contains C code that generates VDBE code used to process
94211** the WHERE clause of SQL statements.  This module is responsible for
94212** generating the code that loops through a table looking for applicable
94213** rows.  Indices are selected and used to speed the search when doing
94214** so is applicable.  Because this module is responsible for selecting
94215** indices, you might also think of this module as the "query optimizer".
94216*/
94217
94218/*
94219** Trace output macros
94220*/
94221#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
94222SQLITE_PRIVATE int sqlite3WhereTrace = 0;
94223#endif
94224#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
94225# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
94226#else
94227# define WHERETRACE(X)
94228#endif
94229
94230/* Forward reference
94231*/
94232typedef struct WhereClause WhereClause;
94233typedef struct WhereMaskSet WhereMaskSet;
94234typedef struct WhereOrInfo WhereOrInfo;
94235typedef struct WhereAndInfo WhereAndInfo;
94236typedef struct WhereCost WhereCost;
94237
94238/*
94239** The query generator uses an array of instances of this structure to
94240** help it analyze the subexpressions of the WHERE clause.  Each WHERE
94241** clause subexpression is separated from the others by AND operators,
94242** usually, or sometimes subexpressions separated by OR.
94243**
94244** All WhereTerms are collected into a single WhereClause structure.
94245** The following identity holds:
94246**
94247**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
94248**
94249** When a term is of the form:
94250**
94251**              X <op> <expr>
94252**
94253** where X is a column name and <op> is one of certain operators,
94254** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
94255** cursor number and column number for X.  WhereTerm.eOperator records
94256** the <op> using a bitmask encoding defined by WO_xxx below.  The
94257** use of a bitmask encoding for the operator allows us to search
94258** quickly for terms that match any of several different operators.
94259**
94260** A WhereTerm might also be two or more subterms connected by OR:
94261**
94262**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
94263**
94264** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
94265** and the WhereTerm.u.pOrInfo field points to auxiliary information that
94266** is collected about the
94267**
94268** If a term in the WHERE clause does not match either of the two previous
94269** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
94270** to the original subexpression content and wtFlags is set up appropriately
94271** but no other fields in the WhereTerm object are meaningful.
94272**
94273** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
94274** but they do so indirectly.  A single WhereMaskSet structure translates
94275** cursor number into bits and the translated bit is stored in the prereq
94276** fields.  The translation is used in order to maximize the number of
94277** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
94278** spread out over the non-negative integers.  For example, the cursor
94279** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
94280** translates these sparse cursor numbers into consecutive integers
94281** beginning with 0 in order to make the best possible use of the available
94282** bits in the Bitmask.  So, in the example above, the cursor numbers
94283** would be mapped into integers 0 through 7.
94284**
94285** The number of terms in a join is limited by the number of bits
94286** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
94287** is only able to process joins with 64 or fewer tables.
94288*/
94289typedef struct WhereTerm WhereTerm;
94290struct WhereTerm {
94291  Expr *pExpr;            /* Pointer to the subexpression that is this term */
94292  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
94293  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
94294  union {
94295    int leftColumn;         /* Column number of X in "X <op> <expr>" */
94296    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
94297    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
94298  } u;
94299  u16 eOperator;          /* A WO_xx value describing <op> */
94300  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
94301  u8 nChild;              /* Number of children that must disable us */
94302  WhereClause *pWC;       /* The clause this term is part of */
94303  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
94304  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
94305};
94306
94307/*
94308** Allowed values of WhereTerm.wtFlags
94309*/
94310#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
94311#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
94312#define TERM_CODED      0x04   /* This term is already coded */
94313#define TERM_COPIED     0x08   /* Has a child */
94314#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
94315#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
94316#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
94317
94318/*
94319** An instance of the following structure holds all information about a
94320** WHERE clause.  Mostly this is a container for one or more WhereTerms.
94321*/
94322struct WhereClause {
94323  Parse *pParse;           /* The parser context */
94324  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
94325  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
94326  u8 op;                   /* Split operator.  TK_AND or TK_OR */
94327  int nTerm;               /* Number of terms */
94328  int nSlot;               /* Number of entries in a[] */
94329  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
94330#if defined(SQLITE_SMALL_STACK)
94331  WhereTerm aStatic[1];    /* Initial static space for a[] */
94332#else
94333  WhereTerm aStatic[8];    /* Initial static space for a[] */
94334#endif
94335};
94336
94337/*
94338** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
94339** a dynamically allocated instance of the following structure.
94340*/
94341struct WhereOrInfo {
94342  WhereClause wc;          /* Decomposition into subterms */
94343  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
94344};
94345
94346/*
94347** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
94348** a dynamically allocated instance of the following structure.
94349*/
94350struct WhereAndInfo {
94351  WhereClause wc;          /* The subexpression broken out */
94352};
94353
94354/*
94355** An instance of the following structure keeps track of a mapping
94356** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
94357**
94358** The VDBE cursor numbers are small integers contained in
94359** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
94360** clause, the cursor numbers might not begin with 0 and they might
94361** contain gaps in the numbering sequence.  But we want to make maximum
94362** use of the bits in our bitmasks.  This structure provides a mapping
94363** from the sparse cursor numbers into consecutive integers beginning
94364** with 0.
94365**
94366** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
94367** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
94368**
94369** For example, if the WHERE clause expression used these VDBE
94370** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
94371** would map those cursor numbers into bits 0 through 5.
94372**
94373** Note that the mapping is not necessarily ordered.  In the example
94374** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
94375** 57->5, 73->4.  Or one of 719 other combinations might be used. It
94376** does not really matter.  What is important is that sparse cursor
94377** numbers all get mapped into bit numbers that begin with 0 and contain
94378** no gaps.
94379*/
94380struct WhereMaskSet {
94381  int n;                        /* Number of assigned cursor values */
94382  int ix[BMS];                  /* Cursor assigned to each bit */
94383};
94384
94385/*
94386** A WhereCost object records a lookup strategy and the estimated
94387** cost of pursuing that strategy.
94388*/
94389struct WhereCost {
94390  WherePlan plan;    /* The lookup strategy */
94391  double rCost;      /* Overall cost of pursuing this search strategy */
94392  double nRow;       /* Estimated number of output rows */
94393  Bitmask used;      /* Bitmask of cursors used by this plan */
94394};
94395
94396/*
94397** Bitmasks for the operators that indices are able to exploit.  An
94398** OR-ed combination of these values can be used when searching for
94399** terms in the where clause.
94400*/
94401#define WO_IN     0x001
94402#define WO_EQ     0x002
94403#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
94404#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
94405#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
94406#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
94407#define WO_MATCH  0x040
94408#define WO_ISNULL 0x080
94409#define WO_OR     0x100       /* Two or more OR-connected terms */
94410#define WO_AND    0x200       /* Two or more AND-connected terms */
94411
94412#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
94413#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
94414
94415/*
94416** Value for wsFlags returned by bestIndex() and stored in
94417** WhereLevel.wsFlags.  These flags determine which search
94418** strategies are appropriate.
94419**
94420** The least significant 12 bits is reserved as a mask for WO_ values above.
94421** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
94422** But if the table is the right table of a left join, WhereLevel.wsFlags
94423** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
94424** the "op" parameter to findTerm when we are resolving equality constraints.
94425** ISNULL constraints will then not be used on the right table of a left
94426** join.  Tickets #2177 and #2189.
94427*/
94428#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
94429#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
94430#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
94431#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
94432#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
94433#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
94434#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
94435#define WHERE_NOT_FULLSCAN 0x000f3000  /* Does not do a full table scan */
94436#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
94437#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
94438#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
94439#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
94440#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
94441#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
94442#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
94443#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
94444#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
94445#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
94446
94447/*
94448** Initialize a preallocated WhereClause structure.
94449*/
94450static void whereClauseInit(
94451  WhereClause *pWC,        /* The WhereClause to be initialized */
94452  Parse *pParse,           /* The parsing context */
94453  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
94454){
94455  pWC->pParse = pParse;
94456  pWC->pMaskSet = pMaskSet;
94457  pWC->nTerm = 0;
94458  pWC->nSlot = ArraySize(pWC->aStatic);
94459  pWC->a = pWC->aStatic;
94460  pWC->vmask = 0;
94461}
94462
94463/* Forward reference */
94464static void whereClauseClear(WhereClause*);
94465
94466/*
94467** Deallocate all memory associated with a WhereOrInfo object.
94468*/
94469static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
94470  whereClauseClear(&p->wc);
94471  sqlite3DbFree(db, p);
94472}
94473
94474/*
94475** Deallocate all memory associated with a WhereAndInfo object.
94476*/
94477static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
94478  whereClauseClear(&p->wc);
94479  sqlite3DbFree(db, p);
94480}
94481
94482/*
94483** Deallocate a WhereClause structure.  The WhereClause structure
94484** itself is not freed.  This routine is the inverse of whereClauseInit().
94485*/
94486static void whereClauseClear(WhereClause *pWC){
94487  int i;
94488  WhereTerm *a;
94489  sqlite3 *db = pWC->pParse->db;
94490  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
94491    if( a->wtFlags & TERM_DYNAMIC ){
94492      sqlite3ExprDelete(db, a->pExpr);
94493    }
94494    if( a->wtFlags & TERM_ORINFO ){
94495      whereOrInfoDelete(db, a->u.pOrInfo);
94496    }else if( a->wtFlags & TERM_ANDINFO ){
94497      whereAndInfoDelete(db, a->u.pAndInfo);
94498    }
94499  }
94500  if( pWC->a!=pWC->aStatic ){
94501    sqlite3DbFree(db, pWC->a);
94502  }
94503}
94504
94505/*
94506** Add a single new WhereTerm entry to the WhereClause object pWC.
94507** The new WhereTerm object is constructed from Expr p and with wtFlags.
94508** The index in pWC->a[] of the new WhereTerm is returned on success.
94509** 0 is returned if the new WhereTerm could not be added due to a memory
94510** allocation error.  The memory allocation failure will be recorded in
94511** the db->mallocFailed flag so that higher-level functions can detect it.
94512**
94513** This routine will increase the size of the pWC->a[] array as necessary.
94514**
94515** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
94516** for freeing the expression p is assumed by the WhereClause object pWC.
94517** This is true even if this routine fails to allocate a new WhereTerm.
94518**
94519** WARNING:  This routine might reallocate the space used to store
94520** WhereTerms.  All pointers to WhereTerms should be invalidated after
94521** calling this routine.  Such pointers may be reinitialized by referencing
94522** the pWC->a[] array.
94523*/
94524static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
94525  WhereTerm *pTerm;
94526  int idx;
94527  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
94528  if( pWC->nTerm>=pWC->nSlot ){
94529    WhereTerm *pOld = pWC->a;
94530    sqlite3 *db = pWC->pParse->db;
94531    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
94532    if( pWC->a==0 ){
94533      if( wtFlags & TERM_DYNAMIC ){
94534        sqlite3ExprDelete(db, p);
94535      }
94536      pWC->a = pOld;
94537      return 0;
94538    }
94539    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
94540    if( pOld!=pWC->aStatic ){
94541      sqlite3DbFree(db, pOld);
94542    }
94543    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
94544  }
94545  pTerm = &pWC->a[idx = pWC->nTerm++];
94546  pTerm->pExpr = p;
94547  pTerm->wtFlags = wtFlags;
94548  pTerm->pWC = pWC;
94549  pTerm->iParent = -1;
94550  return idx;
94551}
94552
94553/*
94554** This routine identifies subexpressions in the WHERE clause where
94555** each subexpression is separated by the AND operator or some other
94556** operator specified in the op parameter.  The WhereClause structure
94557** is filled with pointers to subexpressions.  For example:
94558**
94559**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
94560**           \________/     \_______________/     \________________/
94561**            slot[0]            slot[1]               slot[2]
94562**
94563** The original WHERE clause in pExpr is unaltered.  All this routine
94564** does is make slot[] entries point to substructure within pExpr.
94565**
94566** In the previous sentence and in the diagram, "slot[]" refers to
94567** the WhereClause.a[] array.  The slot[] array grows as needed to contain
94568** all terms of the WHERE clause.
94569*/
94570static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
94571  pWC->op = (u8)op;
94572  if( pExpr==0 ) return;
94573  if( pExpr->op!=op ){
94574    whereClauseInsert(pWC, pExpr, 0);
94575  }else{
94576    whereSplit(pWC, pExpr->pLeft, op);
94577    whereSplit(pWC, pExpr->pRight, op);
94578  }
94579}
94580
94581/*
94582** Initialize an expression mask set (a WhereMaskSet object)
94583*/
94584#define initMaskSet(P)  memset(P, 0, sizeof(*P))
94585
94586/*
94587** Return the bitmask for the given cursor number.  Return 0 if
94588** iCursor is not in the set.
94589*/
94590static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
94591  int i;
94592  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
94593  for(i=0; i<pMaskSet->n; i++){
94594    if( pMaskSet->ix[i]==iCursor ){
94595      return ((Bitmask)1)<<i;
94596    }
94597  }
94598  return 0;
94599}
94600
94601/*
94602** Create a new mask for cursor iCursor.
94603**
94604** There is one cursor per table in the FROM clause.  The number of
94605** tables in the FROM clause is limited by a test early in the
94606** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
94607** array will never overflow.
94608*/
94609static void createMask(WhereMaskSet *pMaskSet, int iCursor){
94610  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
94611  pMaskSet->ix[pMaskSet->n++] = iCursor;
94612}
94613
94614/*
94615** This routine walks (recursively) an expression tree and generates
94616** a bitmask indicating which tables are used in that expression
94617** tree.
94618**
94619** In order for this routine to work, the calling function must have
94620** previously invoked sqlite3ResolveExprNames() on the expression.  See
94621** the header comment on that routine for additional information.
94622** The sqlite3ResolveExprNames() routines looks for column names and
94623** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
94624** the VDBE cursor number of the table.  This routine just has to
94625** translate the cursor numbers into bitmask values and OR all
94626** the bitmasks together.
94627*/
94628static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
94629static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
94630static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
94631  Bitmask mask = 0;
94632  if( p==0 ) return 0;
94633  if( p->op==TK_COLUMN ){
94634    mask = getMask(pMaskSet, p->iTable);
94635    return mask;
94636  }
94637  mask = exprTableUsage(pMaskSet, p->pRight);
94638  mask |= exprTableUsage(pMaskSet, p->pLeft);
94639  if( ExprHasProperty(p, EP_xIsSelect) ){
94640    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
94641  }else{
94642    mask |= exprListTableUsage(pMaskSet, p->x.pList);
94643  }
94644  return mask;
94645}
94646static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
94647  int i;
94648  Bitmask mask = 0;
94649  if( pList ){
94650    for(i=0; i<pList->nExpr; i++){
94651      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
94652    }
94653  }
94654  return mask;
94655}
94656static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
94657  Bitmask mask = 0;
94658  while( pS ){
94659    mask |= exprListTableUsage(pMaskSet, pS->pEList);
94660    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
94661    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
94662    mask |= exprTableUsage(pMaskSet, pS->pWhere);
94663    mask |= exprTableUsage(pMaskSet, pS->pHaving);
94664    pS = pS->pPrior;
94665  }
94666  return mask;
94667}
94668
94669/*
94670** Return TRUE if the given operator is one of the operators that is
94671** allowed for an indexable WHERE clause term.  The allowed operators are
94672** "=", "<", ">", "<=", ">=", and "IN".
94673**
94674** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
94675** of one of the following forms: column = expression column > expression
94676** column >= expression column < expression column <= expression
94677** expression = column expression > column expression >= column
94678** expression < column expression <= column column IN
94679** (expression-list) column IN (subquery) column IS NULL
94680*/
94681static int allowedOp(int op){
94682  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
94683  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
94684  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
94685  assert( TK_GE==TK_EQ+4 );
94686  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
94687}
94688
94689/*
94690** Swap two objects of type TYPE.
94691*/
94692#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
94693
94694/*
94695** Commute a comparison operator.  Expressions of the form "X op Y"
94696** are converted into "Y op X".
94697**
94698** If a collation sequence is associated with either the left or right
94699** side of the comparison, it remains associated with the same side after
94700** the commutation. So "Y collate NOCASE op X" becomes
94701** "X collate NOCASE op Y". This is because any collation sequence on
94702** the left hand side of a comparison overrides any collation sequence
94703** attached to the right. For the same reason the EP_ExpCollate flag
94704** is not commuted.
94705*/
94706static void exprCommute(Parse *pParse, Expr *pExpr){
94707  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
94708  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
94709  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
94710  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
94711  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
94712  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
94713  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
94714  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
94715  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
94716  if( pExpr->op>=TK_GT ){
94717    assert( TK_LT==TK_GT+2 );
94718    assert( TK_GE==TK_LE+2 );
94719    assert( TK_GT>TK_EQ );
94720    assert( TK_GT<TK_LE );
94721    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
94722    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
94723  }
94724}
94725
94726/*
94727** Translate from TK_xx operator to WO_xx bitmask.
94728*/
94729static u16 operatorMask(int op){
94730  u16 c;
94731  assert( allowedOp(op) );
94732  if( op==TK_IN ){
94733    c = WO_IN;
94734  }else if( op==TK_ISNULL ){
94735    c = WO_ISNULL;
94736  }else{
94737    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
94738    c = (u16)(WO_EQ<<(op-TK_EQ));
94739  }
94740  assert( op!=TK_ISNULL || c==WO_ISNULL );
94741  assert( op!=TK_IN || c==WO_IN );
94742  assert( op!=TK_EQ || c==WO_EQ );
94743  assert( op!=TK_LT || c==WO_LT );
94744  assert( op!=TK_LE || c==WO_LE );
94745  assert( op!=TK_GT || c==WO_GT );
94746  assert( op!=TK_GE || c==WO_GE );
94747  return c;
94748}
94749
94750/*
94751** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
94752** where X is a reference to the iColumn of table iCur and <op> is one of
94753** the WO_xx operator codes specified by the op parameter.
94754** Return a pointer to the term.  Return 0 if not found.
94755*/
94756static WhereTerm *findTerm(
94757  WhereClause *pWC,     /* The WHERE clause to be searched */
94758  int iCur,             /* Cursor number of LHS */
94759  int iColumn,          /* Column number of LHS */
94760  Bitmask notReady,     /* RHS must not overlap with this mask */
94761  u32 op,               /* Mask of WO_xx values describing operator */
94762  Index *pIdx           /* Must be compatible with this index, if not NULL */
94763){
94764  WhereTerm *pTerm;
94765  int k;
94766  assert( iCur>=0 );
94767  op &= WO_ALL;
94768  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
94769    if( pTerm->leftCursor==iCur
94770       && (pTerm->prereqRight & notReady)==0
94771       && pTerm->u.leftColumn==iColumn
94772       && (pTerm->eOperator & op)!=0
94773    ){
94774      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
94775        Expr *pX = pTerm->pExpr;
94776        CollSeq *pColl;
94777        char idxaff;
94778        int j;
94779        Parse *pParse = pWC->pParse;
94780
94781        idxaff = pIdx->pTable->aCol[iColumn].affinity;
94782        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
94783
94784        /* Figure out the collation sequence required from an index for
94785        ** it to be useful for optimising expression pX. Store this
94786        ** value in variable pColl.
94787        */
94788        assert(pX->pLeft);
94789        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
94790        assert(pColl || pParse->nErr);
94791
94792        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
94793          if( NEVER(j>=pIdx->nColumn) ) return 0;
94794        }
94795        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
94796      }
94797      return pTerm;
94798    }
94799  }
94800  return 0;
94801}
94802
94803/* Forward reference */
94804static void exprAnalyze(SrcList*, WhereClause*, int);
94805
94806/*
94807** Call exprAnalyze on all terms in a WHERE clause.
94808**
94809**
94810*/
94811static void exprAnalyzeAll(
94812  SrcList *pTabList,       /* the FROM clause */
94813  WhereClause *pWC         /* the WHERE clause to be analyzed */
94814){
94815  int i;
94816  for(i=pWC->nTerm-1; i>=0; i--){
94817    exprAnalyze(pTabList, pWC, i);
94818  }
94819}
94820
94821#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
94822/*
94823** Check to see if the given expression is a LIKE or GLOB operator that
94824** can be optimized using inequality constraints.  Return TRUE if it is
94825** so and false if not.
94826**
94827** In order for the operator to be optimizible, the RHS must be a string
94828** literal that does not begin with a wildcard.
94829*/
94830static int isLikeOrGlob(
94831  Parse *pParse,    /* Parsing and code generating context */
94832  Expr *pExpr,      /* Test this expression */
94833  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
94834  int *pisComplete, /* True if the only wildcard is % in the last character */
94835  int *pnoCase      /* True if uppercase is equivalent to lowercase */
94836){
94837  const char *z = 0;         /* String on RHS of LIKE operator */
94838  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
94839  ExprList *pList;           /* List of operands to the LIKE operator */
94840  int c;                     /* One character in z[] */
94841  int cnt;                   /* Number of non-wildcard prefix characters */
94842  char wc[3];                /* Wildcard characters */
94843  sqlite3 *db = pParse->db;  /* Database connection */
94844  sqlite3_value *pVal = 0;
94845  int op;                    /* Opcode of pRight */
94846
94847  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
94848    return 0;
94849  }
94850#ifdef SQLITE_EBCDIC
94851  if( *pnoCase ) return 0;
94852#endif
94853  pList = pExpr->x.pList;
94854  pLeft = pList->a[1].pExpr;
94855  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
94856    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
94857    ** be the name of an indexed column with TEXT affinity. */
94858    return 0;
94859  }
94860  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
94861
94862  pRight = pList->a[0].pExpr;
94863  op = pRight->op;
94864  if( op==TK_REGISTER ){
94865    op = pRight->op2;
94866  }
94867  if( op==TK_VARIABLE ){
94868    Vdbe *pReprepare = pParse->pReprepare;
94869    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
94870    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
94871      z = (char *)sqlite3_value_text(pVal);
94872    }
94873    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
94874    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
94875  }else if( op==TK_STRING ){
94876    z = pRight->u.zToken;
94877  }
94878  if( z ){
94879    cnt = 0;
94880    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
94881      cnt++;
94882    }
94883    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
94884      Expr *pPrefix;
94885      *pisComplete = c==wc[0] && z[cnt+1]==0;
94886      pPrefix = sqlite3Expr(db, TK_STRING, z);
94887      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
94888      *ppPrefix = pPrefix;
94889      if( op==TK_VARIABLE ){
94890        Vdbe *v = pParse->pVdbe;
94891        sqlite3VdbeSetVarmask(v, pRight->iColumn);
94892        if( *pisComplete && pRight->u.zToken[1] ){
94893          /* If the rhs of the LIKE expression is a variable, and the current
94894          ** value of the variable means there is no need to invoke the LIKE
94895          ** function, then no OP_Variable will be added to the program.
94896          ** This causes problems for the sqlite3_bind_parameter_name()
94897          ** API. To workaround them, add a dummy OP_Variable here.
94898          */
94899          int r1 = sqlite3GetTempReg(pParse);
94900          sqlite3ExprCodeTarget(pParse, pRight, r1);
94901          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
94902          sqlite3ReleaseTempReg(pParse, r1);
94903        }
94904      }
94905    }else{
94906      z = 0;
94907    }
94908  }
94909
94910  sqlite3ValueFree(pVal);
94911  return (z!=0);
94912}
94913#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
94914
94915
94916#ifndef SQLITE_OMIT_VIRTUALTABLE
94917/*
94918** Check to see if the given expression is of the form
94919**
94920**         column MATCH expr
94921**
94922** If it is then return TRUE.  If not, return FALSE.
94923*/
94924static int isMatchOfColumn(
94925  Expr *pExpr      /* Test this expression */
94926){
94927  ExprList *pList;
94928
94929  if( pExpr->op!=TK_FUNCTION ){
94930    return 0;
94931  }
94932  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
94933    return 0;
94934  }
94935  pList = pExpr->x.pList;
94936  if( pList->nExpr!=2 ){
94937    return 0;
94938  }
94939  if( pList->a[1].pExpr->op != TK_COLUMN ){
94940    return 0;
94941  }
94942  return 1;
94943}
94944#endif /* SQLITE_OMIT_VIRTUALTABLE */
94945
94946/*
94947** If the pBase expression originated in the ON or USING clause of
94948** a join, then transfer the appropriate markings over to derived.
94949*/
94950static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
94951  pDerived->flags |= pBase->flags & EP_FromJoin;
94952  pDerived->iRightJoinTable = pBase->iRightJoinTable;
94953}
94954
94955#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
94956/*
94957** Analyze a term that consists of two or more OR-connected
94958** subterms.  So in:
94959**
94960**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
94961**                          ^^^^^^^^^^^^^^^^^^^^
94962**
94963** This routine analyzes terms such as the middle term in the above example.
94964** A WhereOrTerm object is computed and attached to the term under
94965** analysis, regardless of the outcome of the analysis.  Hence:
94966**
94967**     WhereTerm.wtFlags   |=  TERM_ORINFO
94968**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
94969**
94970** The term being analyzed must have two or more of OR-connected subterms.
94971** A single subterm might be a set of AND-connected sub-subterms.
94972** Examples of terms under analysis:
94973**
94974**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
94975**     (B)     x=expr1 OR expr2=x OR x=expr3
94976**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
94977**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
94978**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
94979**
94980** CASE 1:
94981**
94982** If all subterms are of the form T.C=expr for some single column of C
94983** a single table T (as shown in example B above) then create a new virtual
94984** term that is an equivalent IN expression.  In other words, if the term
94985** being analyzed is:
94986**
94987**      x = expr1  OR  expr2 = x  OR  x = expr3
94988**
94989** then create a new virtual term like this:
94990**
94991**      x IN (expr1,expr2,expr3)
94992**
94993** CASE 2:
94994**
94995** If all subterms are indexable by a single table T, then set
94996**
94997**     WhereTerm.eOperator              =  WO_OR
94998**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
94999**
95000** A subterm is "indexable" if it is of the form
95001** "T.C <op> <expr>" where C is any column of table T and
95002** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
95003** A subterm is also indexable if it is an AND of two or more
95004** subsubterms at least one of which is indexable.  Indexable AND
95005** subterms have their eOperator set to WO_AND and they have
95006** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
95007**
95008** From another point of view, "indexable" means that the subterm could
95009** potentially be used with an index if an appropriate index exists.
95010** This analysis does not consider whether or not the index exists; that
95011** is something the bestIndex() routine will determine.  This analysis
95012** only looks at whether subterms appropriate for indexing exist.
95013**
95014** All examples A through E above all satisfy case 2.  But if a term
95015** also statisfies case 1 (such as B) we know that the optimizer will
95016** always prefer case 1, so in that case we pretend that case 2 is not
95017** satisfied.
95018**
95019** It might be the case that multiple tables are indexable.  For example,
95020** (E) above is indexable on tables P, Q, and R.
95021**
95022** Terms that satisfy case 2 are candidates for lookup by using
95023** separate indices to find rowids for each subterm and composing
95024** the union of all rowids using a RowSet object.  This is similar
95025** to "bitmap indices" in other database engines.
95026**
95027** OTHERWISE:
95028**
95029** If neither case 1 nor case 2 apply, then leave the eOperator set to
95030** zero.  This term is not useful for search.
95031*/
95032static void exprAnalyzeOrTerm(
95033  SrcList *pSrc,            /* the FROM clause */
95034  WhereClause *pWC,         /* the complete WHERE clause */
95035  int idxTerm               /* Index of the OR-term to be analyzed */
95036){
95037  Parse *pParse = pWC->pParse;            /* Parser context */
95038  sqlite3 *db = pParse->db;               /* Database connection */
95039  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
95040  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
95041  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
95042  int i;                                  /* Loop counters */
95043  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
95044  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
95045  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
95046  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
95047  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
95048
95049  /*
95050  ** Break the OR clause into its separate subterms.  The subterms are
95051  ** stored in a WhereClause structure containing within the WhereOrInfo
95052  ** object that is attached to the original OR clause term.
95053  */
95054  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
95055  assert( pExpr->op==TK_OR );
95056  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
95057  if( pOrInfo==0 ) return;
95058  pTerm->wtFlags |= TERM_ORINFO;
95059  pOrWc = &pOrInfo->wc;
95060  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
95061  whereSplit(pOrWc, pExpr, TK_OR);
95062  exprAnalyzeAll(pSrc, pOrWc);
95063  if( db->mallocFailed ) return;
95064  assert( pOrWc->nTerm>=2 );
95065
95066  /*
95067  ** Compute the set of tables that might satisfy cases 1 or 2.
95068  */
95069  indexable = ~(Bitmask)0;
95070  chngToIN = ~(pWC->vmask);
95071  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
95072    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
95073      WhereAndInfo *pAndInfo;
95074      assert( pOrTerm->eOperator==0 );
95075      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
95076      chngToIN = 0;
95077      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
95078      if( pAndInfo ){
95079        WhereClause *pAndWC;
95080        WhereTerm *pAndTerm;
95081        int j;
95082        Bitmask b = 0;
95083        pOrTerm->u.pAndInfo = pAndInfo;
95084        pOrTerm->wtFlags |= TERM_ANDINFO;
95085        pOrTerm->eOperator = WO_AND;
95086        pAndWC = &pAndInfo->wc;
95087        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
95088        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
95089        exprAnalyzeAll(pSrc, pAndWC);
95090        testcase( db->mallocFailed );
95091        if( !db->mallocFailed ){
95092          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
95093            assert( pAndTerm->pExpr );
95094            if( allowedOp(pAndTerm->pExpr->op) ){
95095              b |= getMask(pMaskSet, pAndTerm->leftCursor);
95096            }
95097          }
95098        }
95099        indexable &= b;
95100      }
95101    }else if( pOrTerm->wtFlags & TERM_COPIED ){
95102      /* Skip this term for now.  We revisit it when we process the
95103      ** corresponding TERM_VIRTUAL term */
95104    }else{
95105      Bitmask b;
95106      b = getMask(pMaskSet, pOrTerm->leftCursor);
95107      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
95108        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
95109        b |= getMask(pMaskSet, pOther->leftCursor);
95110      }
95111      indexable &= b;
95112      if( pOrTerm->eOperator!=WO_EQ ){
95113        chngToIN = 0;
95114      }else{
95115        chngToIN &= b;
95116      }
95117    }
95118  }
95119
95120  /*
95121  ** Record the set of tables that satisfy case 2.  The set might be
95122  ** empty.
95123  */
95124  pOrInfo->indexable = indexable;
95125  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
95126
95127  /*
95128  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
95129  ** we have to do some additional checking to see if case 1 really
95130  ** is satisfied.
95131  **
95132  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
95133  ** that there is no possibility of transforming the OR clause into an
95134  ** IN operator because one or more terms in the OR clause contain
95135  ** something other than == on a column in the single table.  The 1-bit
95136  ** case means that every term of the OR clause is of the form
95137  ** "table.column=expr" for some single table.  The one bit that is set
95138  ** will correspond to the common table.  We still need to check to make
95139  ** sure the same column is used on all terms.  The 2-bit case is when
95140  ** the all terms are of the form "table1.column=table2.column".  It
95141  ** might be possible to form an IN operator with either table1.column
95142  ** or table2.column as the LHS if either is common to every term of
95143  ** the OR clause.
95144  **
95145  ** Note that terms of the form "table.column1=table.column2" (the
95146  ** same table on both sizes of the ==) cannot be optimized.
95147  */
95148  if( chngToIN ){
95149    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
95150    int iColumn = -1;         /* Column index on lhs of IN operator */
95151    int iCursor = -1;         /* Table cursor common to all terms */
95152    int j = 0;                /* Loop counter */
95153
95154    /* Search for a table and column that appears on one side or the
95155    ** other of the == operator in every subterm.  That table and column
95156    ** will be recorded in iCursor and iColumn.  There might not be any
95157    ** such table and column.  Set okToChngToIN if an appropriate table
95158    ** and column is found but leave okToChngToIN false if not found.
95159    */
95160    for(j=0; j<2 && !okToChngToIN; j++){
95161      pOrTerm = pOrWc->a;
95162      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
95163        assert( pOrTerm->eOperator==WO_EQ );
95164        pOrTerm->wtFlags &= ~TERM_OR_OK;
95165        if( pOrTerm->leftCursor==iCursor ){
95166          /* This is the 2-bit case and we are on the second iteration and
95167          ** current term is from the first iteration.  So skip this term. */
95168          assert( j==1 );
95169          continue;
95170        }
95171        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
95172          /* This term must be of the form t1.a==t2.b where t2 is in the
95173          ** chngToIN set but t1 is not.  This term will be either preceeded
95174          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
95175          ** and use its inversion. */
95176          testcase( pOrTerm->wtFlags & TERM_COPIED );
95177          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
95178          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
95179          continue;
95180        }
95181        iColumn = pOrTerm->u.leftColumn;
95182        iCursor = pOrTerm->leftCursor;
95183        break;
95184      }
95185      if( i<0 ){
95186        /* No candidate table+column was found.  This can only occur
95187        ** on the second iteration */
95188        assert( j==1 );
95189        assert( (chngToIN&(chngToIN-1))==0 );
95190        assert( chngToIN==getMask(pMaskSet, iCursor) );
95191        break;
95192      }
95193      testcase( j==1 );
95194
95195      /* We have found a candidate table and column.  Check to see if that
95196      ** table and column is common to every term in the OR clause */
95197      okToChngToIN = 1;
95198      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
95199        assert( pOrTerm->eOperator==WO_EQ );
95200        if( pOrTerm->leftCursor!=iCursor ){
95201          pOrTerm->wtFlags &= ~TERM_OR_OK;
95202        }else if( pOrTerm->u.leftColumn!=iColumn ){
95203          okToChngToIN = 0;
95204        }else{
95205          int affLeft, affRight;
95206          /* If the right-hand side is also a column, then the affinities
95207          ** of both right and left sides must be such that no type
95208          ** conversions are required on the right.  (Ticket #2249)
95209          */
95210          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
95211          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
95212          if( affRight!=0 && affRight!=affLeft ){
95213            okToChngToIN = 0;
95214          }else{
95215            pOrTerm->wtFlags |= TERM_OR_OK;
95216          }
95217        }
95218      }
95219    }
95220
95221    /* At this point, okToChngToIN is true if original pTerm satisfies
95222    ** case 1.  In that case, construct a new virtual term that is
95223    ** pTerm converted into an IN operator.
95224    **
95225    ** EV: R-00211-15100
95226    */
95227    if( okToChngToIN ){
95228      Expr *pDup;            /* A transient duplicate expression */
95229      ExprList *pList = 0;   /* The RHS of the IN operator */
95230      Expr *pLeft = 0;       /* The LHS of the IN operator */
95231      Expr *pNew;            /* The complete IN operator */
95232
95233      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
95234        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
95235        assert( pOrTerm->eOperator==WO_EQ );
95236        assert( pOrTerm->leftCursor==iCursor );
95237        assert( pOrTerm->u.leftColumn==iColumn );
95238        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
95239        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
95240        pLeft = pOrTerm->pExpr->pLeft;
95241      }
95242      assert( pLeft!=0 );
95243      pDup = sqlite3ExprDup(db, pLeft, 0);
95244      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
95245      if( pNew ){
95246        int idxNew;
95247        transferJoinMarkings(pNew, pExpr);
95248        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
95249        pNew->x.pList = pList;
95250        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
95251        testcase( idxNew==0 );
95252        exprAnalyze(pSrc, pWC, idxNew);
95253        pTerm = &pWC->a[idxTerm];
95254        pWC->a[idxNew].iParent = idxTerm;
95255        pTerm->nChild = 1;
95256      }else{
95257        sqlite3ExprListDelete(db, pList);
95258      }
95259      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
95260    }
95261  }
95262}
95263#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
95264
95265
95266/*
95267** The input to this routine is an WhereTerm structure with only the
95268** "pExpr" field filled in.  The job of this routine is to analyze the
95269** subexpression and populate all the other fields of the WhereTerm
95270** structure.
95271**
95272** If the expression is of the form "<expr> <op> X" it gets commuted
95273** to the standard form of "X <op> <expr>".
95274**
95275** If the expression is of the form "X <op> Y" where both X and Y are
95276** columns, then the original expression is unchanged and a new virtual
95277** term of the form "Y <op> X" is added to the WHERE clause and
95278** analyzed separately.  The original term is marked with TERM_COPIED
95279** and the new term is marked with TERM_DYNAMIC (because it's pExpr
95280** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
95281** is a commuted copy of a prior term.)  The original term has nChild=1
95282** and the copy has idxParent set to the index of the original term.
95283*/
95284static void exprAnalyze(
95285  SrcList *pSrc,            /* the FROM clause */
95286  WhereClause *pWC,         /* the WHERE clause */
95287  int idxTerm               /* Index of the term to be analyzed */
95288){
95289  WhereTerm *pTerm;                /* The term to be analyzed */
95290  WhereMaskSet *pMaskSet;          /* Set of table index masks */
95291  Expr *pExpr;                     /* The expression to be analyzed */
95292  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
95293  Bitmask prereqAll;               /* Prerequesites of pExpr */
95294  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
95295  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
95296  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
95297  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
95298  int op;                          /* Top-level operator.  pExpr->op */
95299  Parse *pParse = pWC->pParse;     /* Parsing context */
95300  sqlite3 *db = pParse->db;        /* Database connection */
95301
95302  if( db->mallocFailed ){
95303    return;
95304  }
95305  pTerm = &pWC->a[idxTerm];
95306  pMaskSet = pWC->pMaskSet;
95307  pExpr = pTerm->pExpr;
95308  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
95309  op = pExpr->op;
95310  if( op==TK_IN ){
95311    assert( pExpr->pRight==0 );
95312    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
95313      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
95314    }else{
95315      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
95316    }
95317  }else if( op==TK_ISNULL ){
95318    pTerm->prereqRight = 0;
95319  }else{
95320    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
95321  }
95322  prereqAll = exprTableUsage(pMaskSet, pExpr);
95323  if( ExprHasProperty(pExpr, EP_FromJoin) ){
95324    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
95325    prereqAll |= x;
95326    extraRight = x-1;  /* ON clause terms may not be used with an index
95327                       ** on left table of a LEFT JOIN.  Ticket #3015 */
95328  }
95329  pTerm->prereqAll = prereqAll;
95330  pTerm->leftCursor = -1;
95331  pTerm->iParent = -1;
95332  pTerm->eOperator = 0;
95333  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
95334    Expr *pLeft = pExpr->pLeft;
95335    Expr *pRight = pExpr->pRight;
95336    if( pLeft->op==TK_COLUMN ){
95337      pTerm->leftCursor = pLeft->iTable;
95338      pTerm->u.leftColumn = pLeft->iColumn;
95339      pTerm->eOperator = operatorMask(op);
95340    }
95341    if( pRight && pRight->op==TK_COLUMN ){
95342      WhereTerm *pNew;
95343      Expr *pDup;
95344      if( pTerm->leftCursor>=0 ){
95345        int idxNew;
95346        pDup = sqlite3ExprDup(db, pExpr, 0);
95347        if( db->mallocFailed ){
95348          sqlite3ExprDelete(db, pDup);
95349          return;
95350        }
95351        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
95352        if( idxNew==0 ) return;
95353        pNew = &pWC->a[idxNew];
95354        pNew->iParent = idxTerm;
95355        pTerm = &pWC->a[idxTerm];
95356        pTerm->nChild = 1;
95357        pTerm->wtFlags |= TERM_COPIED;
95358      }else{
95359        pDup = pExpr;
95360        pNew = pTerm;
95361      }
95362      exprCommute(pParse, pDup);
95363      pLeft = pDup->pLeft;
95364      pNew->leftCursor = pLeft->iTable;
95365      pNew->u.leftColumn = pLeft->iColumn;
95366      testcase( (prereqLeft | extraRight) != prereqLeft );
95367      pNew->prereqRight = prereqLeft | extraRight;
95368      pNew->prereqAll = prereqAll;
95369      pNew->eOperator = operatorMask(pDup->op);
95370    }
95371  }
95372
95373#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
95374  /* If a term is the BETWEEN operator, create two new virtual terms
95375  ** that define the range that the BETWEEN implements.  For example:
95376  **
95377  **      a BETWEEN b AND c
95378  **
95379  ** is converted into:
95380  **
95381  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
95382  **
95383  ** The two new terms are added onto the end of the WhereClause object.
95384  ** The new terms are "dynamic" and are children of the original BETWEEN
95385  ** term.  That means that if the BETWEEN term is coded, the children are
95386  ** skipped.  Or, if the children are satisfied by an index, the original
95387  ** BETWEEN term is skipped.
95388  */
95389  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
95390    ExprList *pList = pExpr->x.pList;
95391    int i;
95392    static const u8 ops[] = {TK_GE, TK_LE};
95393    assert( pList!=0 );
95394    assert( pList->nExpr==2 );
95395    for(i=0; i<2; i++){
95396      Expr *pNewExpr;
95397      int idxNew;
95398      pNewExpr = sqlite3PExpr(pParse, ops[i],
95399                             sqlite3ExprDup(db, pExpr->pLeft, 0),
95400                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
95401      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
95402      testcase( idxNew==0 );
95403      exprAnalyze(pSrc, pWC, idxNew);
95404      pTerm = &pWC->a[idxTerm];
95405      pWC->a[idxNew].iParent = idxTerm;
95406    }
95407    pTerm->nChild = 2;
95408  }
95409#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
95410
95411#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
95412  /* Analyze a term that is composed of two or more subterms connected by
95413  ** an OR operator.
95414  */
95415  else if( pExpr->op==TK_OR ){
95416    assert( pWC->op==TK_AND );
95417    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
95418    pTerm = &pWC->a[idxTerm];
95419  }
95420#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
95421
95422#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
95423  /* Add constraints to reduce the search space on a LIKE or GLOB
95424  ** operator.
95425  **
95426  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
95427  **
95428  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
95429  **
95430  ** The last character of the prefix "abc" is incremented to form the
95431  ** termination condition "abd".
95432  */
95433  if( pWC->op==TK_AND
95434   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
95435  ){
95436    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
95437    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
95438    Expr *pNewExpr1;
95439    Expr *pNewExpr2;
95440    int idxNew1;
95441    int idxNew2;
95442    CollSeq *pColl;    /* Collating sequence to use */
95443
95444    pLeft = pExpr->x.pList->a[1].pExpr;
95445    pStr2 = sqlite3ExprDup(db, pStr1, 0);
95446    if( !db->mallocFailed ){
95447      u8 c, *pC;       /* Last character before the first wildcard */
95448      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
95449      c = *pC;
95450      if( noCase ){
95451        /* The point is to increment the last character before the first
95452        ** wildcard.  But if we increment '@', that will push it into the
95453        ** alphabetic range where case conversions will mess up the
95454        ** inequality.  To avoid this, make sure to also run the full
95455        ** LIKE on all candidate expressions by clearing the isComplete flag
95456        */
95457        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
95458
95459
95460        c = sqlite3UpperToLower[c];
95461      }
95462      *pC = c + 1;
95463    }
95464    pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
95465    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
95466                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
95467                     pStr1, 0);
95468    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
95469    testcase( idxNew1==0 );
95470    exprAnalyze(pSrc, pWC, idxNew1);
95471    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
95472                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
95473                     pStr2, 0);
95474    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
95475    testcase( idxNew2==0 );
95476    exprAnalyze(pSrc, pWC, idxNew2);
95477    pTerm = &pWC->a[idxTerm];
95478    if( isComplete ){
95479      pWC->a[idxNew1].iParent = idxTerm;
95480      pWC->a[idxNew2].iParent = idxTerm;
95481      pTerm->nChild = 2;
95482    }
95483  }
95484#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
95485
95486#ifndef SQLITE_OMIT_VIRTUALTABLE
95487  /* Add a WO_MATCH auxiliary term to the constraint set if the
95488  ** current expression is of the form:  column MATCH expr.
95489  ** This information is used by the xBestIndex methods of
95490  ** virtual tables.  The native query optimizer does not attempt
95491  ** to do anything with MATCH functions.
95492  */
95493  if( isMatchOfColumn(pExpr) ){
95494    int idxNew;
95495    Expr *pRight, *pLeft;
95496    WhereTerm *pNewTerm;
95497    Bitmask prereqColumn, prereqExpr;
95498
95499    pRight = pExpr->x.pList->a[0].pExpr;
95500    pLeft = pExpr->x.pList->a[1].pExpr;
95501    prereqExpr = exprTableUsage(pMaskSet, pRight);
95502    prereqColumn = exprTableUsage(pMaskSet, pLeft);
95503    if( (prereqExpr & prereqColumn)==0 ){
95504      Expr *pNewExpr;
95505      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
95506                              0, sqlite3ExprDup(db, pRight, 0), 0);
95507      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
95508      testcase( idxNew==0 );
95509      pNewTerm = &pWC->a[idxNew];
95510      pNewTerm->prereqRight = prereqExpr;
95511      pNewTerm->leftCursor = pLeft->iTable;
95512      pNewTerm->u.leftColumn = pLeft->iColumn;
95513      pNewTerm->eOperator = WO_MATCH;
95514      pNewTerm->iParent = idxTerm;
95515      pTerm = &pWC->a[idxTerm];
95516      pTerm->nChild = 1;
95517      pTerm->wtFlags |= TERM_COPIED;
95518      pNewTerm->prereqAll = pTerm->prereqAll;
95519    }
95520  }
95521#endif /* SQLITE_OMIT_VIRTUALTABLE */
95522
95523  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
95524  ** an index for tables to the left of the join.
95525  */
95526  pTerm->prereqRight |= extraRight;
95527}
95528
95529/*
95530** Return TRUE if any of the expressions in pList->a[iFirst...] contain
95531** a reference to any table other than the iBase table.
95532*/
95533static int referencesOtherTables(
95534  ExprList *pList,          /* Search expressions in ths list */
95535  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
95536  int iFirst,               /* Be searching with the iFirst-th expression */
95537  int iBase                 /* Ignore references to this table */
95538){
95539  Bitmask allowed = ~getMask(pMaskSet, iBase);
95540  while( iFirst<pList->nExpr ){
95541    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
95542      return 1;
95543    }
95544  }
95545  return 0;
95546}
95547
95548
95549/*
95550** This routine decides if pIdx can be used to satisfy the ORDER BY
95551** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
95552** ORDER BY clause, this routine returns 0.
95553**
95554** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
95555** left-most table in the FROM clause of that same SELECT statement and
95556** the table has a cursor number of "base".  pIdx is an index on pTab.
95557**
95558** nEqCol is the number of columns of pIdx that are used as equality
95559** constraints.  Any of these columns may be missing from the ORDER BY
95560** clause and the match can still be a success.
95561**
95562** All terms of the ORDER BY that match against the index must be either
95563** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
95564** index do not need to satisfy this constraint.)  The *pbRev value is
95565** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
95566** the ORDER BY clause is all ASC.
95567*/
95568static int isSortingIndex(
95569  Parse *pParse,          /* Parsing context */
95570  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
95571  Index *pIdx,            /* The index we are testing */
95572  int base,               /* Cursor number for the table to be sorted */
95573  ExprList *pOrderBy,     /* The ORDER BY clause */
95574  int nEqCol,             /* Number of index columns with == constraints */
95575  int *pbRev              /* Set to 1 if ORDER BY is DESC */
95576){
95577  int i, j;                       /* Loop counters */
95578  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
95579  int nTerm;                      /* Number of ORDER BY terms */
95580  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
95581  sqlite3 *db = pParse->db;
95582
95583  assert( pOrderBy!=0 );
95584  nTerm = pOrderBy->nExpr;
95585  assert( nTerm>0 );
95586
95587  /* Argument pIdx must either point to a 'real' named index structure,
95588  ** or an index structure allocated on the stack by bestBtreeIndex() to
95589  ** represent the rowid index that is part of every table.  */
95590  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
95591
95592  /* Match terms of the ORDER BY clause against columns of
95593  ** the index.
95594  **
95595  ** Note that indices have pIdx->nColumn regular columns plus
95596  ** one additional column containing the rowid.  The rowid column
95597  ** of the index is also allowed to match against the ORDER BY
95598  ** clause.
95599  */
95600  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
95601    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
95602    CollSeq *pColl;    /* The collating sequence of pExpr */
95603    int termSortOrder; /* Sort order for this term */
95604    int iColumn;       /* The i-th column of the index.  -1 for rowid */
95605    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
95606    const char *zColl; /* Name of the collating sequence for i-th index term */
95607
95608    pExpr = pTerm->pExpr;
95609    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
95610      /* Can not use an index sort on anything that is not a column in the
95611      ** left-most table of the FROM clause */
95612      break;
95613    }
95614    pColl = sqlite3ExprCollSeq(pParse, pExpr);
95615    if( !pColl ){
95616      pColl = db->pDfltColl;
95617    }
95618    if( pIdx->zName && i<pIdx->nColumn ){
95619      iColumn = pIdx->aiColumn[i];
95620      if( iColumn==pIdx->pTable->iPKey ){
95621        iColumn = -1;
95622      }
95623      iSortOrder = pIdx->aSortOrder[i];
95624      zColl = pIdx->azColl[i];
95625    }else{
95626      iColumn = -1;
95627      iSortOrder = 0;
95628      zColl = pColl->zName;
95629    }
95630    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
95631      /* Term j of the ORDER BY clause does not match column i of the index */
95632      if( i<nEqCol ){
95633        /* If an index column that is constrained by == fails to match an
95634        ** ORDER BY term, that is OK.  Just ignore that column of the index
95635        */
95636        continue;
95637      }else if( i==pIdx->nColumn ){
95638        /* Index column i is the rowid.  All other terms match. */
95639        break;
95640      }else{
95641        /* If an index column fails to match and is not constrained by ==
95642        ** then the index cannot satisfy the ORDER BY constraint.
95643        */
95644        return 0;
95645      }
95646    }
95647    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
95648    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
95649    assert( iSortOrder==0 || iSortOrder==1 );
95650    termSortOrder = iSortOrder ^ pTerm->sortOrder;
95651    if( i>nEqCol ){
95652      if( termSortOrder!=sortOrder ){
95653        /* Indices can only be used if all ORDER BY terms past the
95654        ** equality constraints are all either DESC or ASC. */
95655        return 0;
95656      }
95657    }else{
95658      sortOrder = termSortOrder;
95659    }
95660    j++;
95661    pTerm++;
95662    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
95663      /* If the indexed column is the primary key and everything matches
95664      ** so far and none of the ORDER BY terms to the right reference other
95665      ** tables in the join, then we are assured that the index can be used
95666      ** to sort because the primary key is unique and so none of the other
95667      ** columns will make any difference
95668      */
95669      j = nTerm;
95670    }
95671  }
95672
95673  *pbRev = sortOrder!=0;
95674  if( j>=nTerm ){
95675    /* All terms of the ORDER BY clause are covered by this index so
95676    ** this index can be used for sorting. */
95677    return 1;
95678  }
95679  if( pIdx->onError!=OE_None && i==pIdx->nColumn
95680      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
95681    /* All terms of this index match some prefix of the ORDER BY clause
95682    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
95683    ** clause reference other tables in a join.  If this is all true then
95684    ** the order by clause is superfluous. */
95685    return 1;
95686  }
95687  return 0;
95688}
95689
95690/*
95691** Prepare a crude estimate of the logarithm of the input value.
95692** The results need not be exact.  This is only used for estimating
95693** the total cost of performing operations with O(logN) or O(NlogN)
95694** complexity.  Because N is just a guess, it is no great tragedy if
95695** logN is a little off.
95696*/
95697static double estLog(double N){
95698  double logN = 1;
95699  double x = 10;
95700  while( N>x ){
95701    logN += 1;
95702    x *= 10;
95703  }
95704  return logN;
95705}
95706
95707/*
95708** Two routines for printing the content of an sqlite3_index_info
95709** structure.  Used for testing and debugging only.  If neither
95710** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
95711** are no-ops.
95712*/
95713#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
95714static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
95715  int i;
95716  if( !sqlite3WhereTrace ) return;
95717  for(i=0; i<p->nConstraint; i++){
95718    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
95719       i,
95720       p->aConstraint[i].iColumn,
95721       p->aConstraint[i].iTermOffset,
95722       p->aConstraint[i].op,
95723       p->aConstraint[i].usable);
95724  }
95725  for(i=0; i<p->nOrderBy; i++){
95726    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
95727       i,
95728       p->aOrderBy[i].iColumn,
95729       p->aOrderBy[i].desc);
95730  }
95731}
95732static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
95733  int i;
95734  if( !sqlite3WhereTrace ) return;
95735  for(i=0; i<p->nConstraint; i++){
95736    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
95737       i,
95738       p->aConstraintUsage[i].argvIndex,
95739       p->aConstraintUsage[i].omit);
95740  }
95741  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
95742  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
95743  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
95744  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
95745}
95746#else
95747#define TRACE_IDX_INPUTS(A)
95748#define TRACE_IDX_OUTPUTS(A)
95749#endif
95750
95751/*
95752** Required because bestIndex() is called by bestOrClauseIndex()
95753*/
95754static void bestIndex(
95755    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
95756
95757/*
95758** This routine attempts to find an scanning strategy that can be used
95759** to optimize an 'OR' expression that is part of a WHERE clause.
95760**
95761** The table associated with FROM clause term pSrc may be either a
95762** regular B-Tree table or a virtual table.
95763*/
95764static void bestOrClauseIndex(
95765  Parse *pParse,              /* The parsing context */
95766  WhereClause *pWC,           /* The WHERE clause */
95767  struct SrcList_item *pSrc,  /* The FROM clause term to search */
95768  Bitmask notReady,           /* Mask of cursors that are not available */
95769  ExprList *pOrderBy,         /* The ORDER BY clause */
95770  WhereCost *pCost            /* Lowest cost query plan */
95771){
95772#ifndef SQLITE_OMIT_OR_OPTIMIZATION
95773  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
95774  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
95775  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
95776  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
95777
95778  /* No OR-clause optimization allowed if the NOT INDEXED clause is used */
95779  if( pSrc->notIndexed ){
95780    return;
95781  }
95782
95783  /* Search the WHERE clause terms for a usable WO_OR term. */
95784  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95785    if( pTerm->eOperator==WO_OR
95786     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
95787     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
95788    ){
95789      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
95790      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
95791      WhereTerm *pOrTerm;
95792      int flags = WHERE_MULTI_OR;
95793      double rTotal = 0;
95794      double nRow = 0;
95795      Bitmask used = 0;
95796
95797      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
95798        WhereCost sTermCost;
95799        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
95800          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
95801        ));
95802        if( pOrTerm->eOperator==WO_AND ){
95803          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
95804          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
95805        }else if( pOrTerm->leftCursor==iCur ){
95806          WhereClause tempWC;
95807          tempWC.pParse = pWC->pParse;
95808          tempWC.pMaskSet = pWC->pMaskSet;
95809          tempWC.op = TK_AND;
95810          tempWC.a = pOrTerm;
95811          tempWC.nTerm = 1;
95812          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
95813        }else{
95814          continue;
95815        }
95816        rTotal += sTermCost.rCost;
95817        nRow += sTermCost.nRow;
95818        used |= sTermCost.used;
95819        if( rTotal>=pCost->rCost ) break;
95820      }
95821
95822      /* If there is an ORDER BY clause, increase the scan cost to account
95823      ** for the cost of the sort. */
95824      if( pOrderBy!=0 ){
95825        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
95826                    rTotal, rTotal+nRow*estLog(nRow)));
95827        rTotal += nRow*estLog(nRow);
95828      }
95829
95830      /* If the cost of scanning using this OR term for optimization is
95831      ** less than the current cost stored in pCost, replace the contents
95832      ** of pCost. */
95833      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
95834      if( rTotal<pCost->rCost ){
95835        pCost->rCost = rTotal;
95836        pCost->nRow = nRow;
95837        pCost->used = used;
95838        pCost->plan.wsFlags = flags;
95839        pCost->plan.u.pTerm = pTerm;
95840      }
95841    }
95842  }
95843#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
95844}
95845
95846#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95847/*
95848** Return TRUE if the WHERE clause term pTerm is of a form where it
95849** could be used with an index to access pSrc, assuming an appropriate
95850** index existed.
95851*/
95852static int termCanDriveIndex(
95853  WhereTerm *pTerm,              /* WHERE clause term to check */
95854  struct SrcList_item *pSrc,     /* Table we are trying to access */
95855  Bitmask notReady               /* Tables in outer loops of the join */
95856){
95857  char aff;
95858  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
95859  if( pTerm->eOperator!=WO_EQ ) return 0;
95860  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
95861  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
95862  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
95863  return 1;
95864}
95865#endif
95866
95867#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95868/*
95869** If the query plan for pSrc specified in pCost is a full table scan
95870** and indexing is allows (if there is no NOT INDEXED clause) and it
95871** possible to construct a transient index that would perform better
95872** than a full table scan even when the cost of constructing the index
95873** is taken into account, then alter the query plan to use the
95874** transient index.
95875*/
95876static void bestAutomaticIndex(
95877  Parse *pParse,              /* The parsing context */
95878  WhereClause *pWC,           /* The WHERE clause */
95879  struct SrcList_item *pSrc,  /* The FROM clause term to search */
95880  Bitmask notReady,           /* Mask of cursors that are not available */
95881  WhereCost *pCost            /* Lowest cost query plan */
95882){
95883  double nTableRow;           /* Rows in the input table */
95884  double logN;                /* log(nTableRow) */
95885  double costTempIdx;         /* per-query cost of the transient index */
95886  WhereTerm *pTerm;           /* A single term of the WHERE clause */
95887  WhereTerm *pWCEnd;          /* End of pWC->a[] */
95888  Table *pTable;              /* Table tht might be indexed */
95889
95890  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
95891    /* Automatic indices are disabled at run-time */
95892    return;
95893  }
95894  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
95895    /* We already have some kind of index in use for this query. */
95896    return;
95897  }
95898  if( pSrc->notIndexed ){
95899    /* The NOT INDEXED clause appears in the SQL. */
95900    return;
95901  }
95902
95903  assert( pParse->nQueryLoop >= (double)1 );
95904  pTable = pSrc->pTab;
95905  nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
95906  logN = estLog(nTableRow);
95907  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
95908  if( costTempIdx>=pCost->rCost ){
95909    /* The cost of creating the transient table would be greater than
95910    ** doing the full table scan */
95911    return;
95912  }
95913
95914  /* Search for any equality comparison term */
95915  pWCEnd = &pWC->a[pWC->nTerm];
95916  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95917    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95918      WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
95919                    pCost->rCost, costTempIdx));
95920      pCost->rCost = costTempIdx;
95921      pCost->nRow = logN + 1;
95922      pCost->plan.wsFlags = WHERE_TEMP_INDEX;
95923      pCost->used = pTerm->prereqRight;
95924      break;
95925    }
95926  }
95927}
95928#else
95929# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
95930#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
95931
95932
95933#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
95934/*
95935** Generate code to construct the Index object for an automatic index
95936** and to set up the WhereLevel object pLevel so that the code generator
95937** makes use of the automatic index.
95938*/
95939static void constructAutomaticIndex(
95940  Parse *pParse,              /* The parsing context */
95941  WhereClause *pWC,           /* The WHERE clause */
95942  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
95943  Bitmask notReady,           /* Mask of cursors that are not available */
95944  WhereLevel *pLevel          /* Write new index here */
95945){
95946  int nColumn;                /* Number of columns in the constructed index */
95947  WhereTerm *pTerm;           /* A single term of the WHERE clause */
95948  WhereTerm *pWCEnd;          /* End of pWC->a[] */
95949  int nByte;                  /* Byte of memory needed for pIdx */
95950  Index *pIdx;                /* Object describing the transient index */
95951  Vdbe *v;                    /* Prepared statement under construction */
95952  int regIsInit;              /* Register set by initialization */
95953  int addrInit;               /* Address of the initialization bypass jump */
95954  Table *pTable;              /* The table being indexed */
95955  KeyInfo *pKeyinfo;          /* Key information for the index */
95956  int addrTop;                /* Top of the index fill loop */
95957  int regRecord;              /* Register holding an index record */
95958  int n;                      /* Column counter */
95959  int i;                      /* Loop counter */
95960  int mxBitCol;               /* Maximum column in pSrc->colUsed */
95961  CollSeq *pColl;             /* Collating sequence to on a column */
95962  Bitmask idxCols;            /* Bitmap of columns used for indexing */
95963  Bitmask extraCols;          /* Bitmap of additional columns */
95964
95965  /* Generate code to skip over the creation and initialization of the
95966  ** transient index on 2nd and subsequent iterations of the loop. */
95967  v = pParse->pVdbe;
95968  assert( v!=0 );
95969  regIsInit = ++pParse->nMem;
95970  addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
95971  sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
95972
95973  /* Count the number of columns that will be added to the index
95974  ** and used to match WHERE clause constraints */
95975  nColumn = 0;
95976  pTable = pSrc->pTab;
95977  pWCEnd = &pWC->a[pWC->nTerm];
95978  idxCols = 0;
95979  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
95980    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
95981      int iCol = pTerm->u.leftColumn;
95982      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
95983      testcase( iCol==BMS );
95984      testcase( iCol==BMS-1 );
95985      if( (idxCols & cMask)==0 ){
95986        nColumn++;
95987        idxCols |= cMask;
95988      }
95989    }
95990  }
95991  assert( nColumn>0 );
95992  pLevel->plan.nEq = nColumn;
95993
95994  /* Count the number of additional columns needed to create a
95995  ** covering index.  A "covering index" is an index that contains all
95996  ** columns that are needed by the query.  With a covering index, the
95997  ** original table never needs to be accessed.  Automatic indices must
95998  ** be a covering index because the index will not be updated if the
95999  ** original table changes and the index and table cannot both be used
96000  ** if they go out of sync.
96001  */
96002  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
96003  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
96004  testcase( pTable->nCol==BMS-1 );
96005  testcase( pTable->nCol==BMS-2 );
96006  for(i=0; i<mxBitCol; i++){
96007    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
96008  }
96009  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
96010    nColumn += pTable->nCol - BMS + 1;
96011  }
96012  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
96013
96014  /* Construct the Index object to describe this index */
96015  nByte = sizeof(Index);
96016  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
96017  nByte += nColumn*sizeof(char*);   /* Index.azColl */
96018  nByte += nColumn;                 /* Index.aSortOrder */
96019  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
96020  if( pIdx==0 ) return;
96021  pLevel->plan.u.pIdx = pIdx;
96022  pIdx->azColl = (char**)&pIdx[1];
96023  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
96024  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
96025  pIdx->zName = "auto-index";
96026  pIdx->nColumn = nColumn;
96027  pIdx->pTable = pTable;
96028  n = 0;
96029  idxCols = 0;
96030  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
96031    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
96032      int iCol = pTerm->u.leftColumn;
96033      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
96034      if( (idxCols & cMask)==0 ){
96035        Expr *pX = pTerm->pExpr;
96036        idxCols |= cMask;
96037        pIdx->aiColumn[n] = pTerm->u.leftColumn;
96038        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
96039        pIdx->azColl[n] = pColl->zName;
96040        n++;
96041      }
96042    }
96043  }
96044  assert( (u32)n==pLevel->plan.nEq );
96045
96046  /* Add additional columns needed to make the automatic index into
96047  ** a covering index */
96048  for(i=0; i<mxBitCol; i++){
96049    if( extraCols & (((Bitmask)1)<<i) ){
96050      pIdx->aiColumn[n] = i;
96051      pIdx->azColl[n] = "BINARY";
96052      n++;
96053    }
96054  }
96055  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
96056    for(i=BMS-1; i<pTable->nCol; i++){
96057      pIdx->aiColumn[n] = i;
96058      pIdx->azColl[n] = "BINARY";
96059      n++;
96060    }
96061  }
96062  assert( n==nColumn );
96063
96064  /* Create the automatic index */
96065  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
96066  assert( pLevel->iIdxCur>=0 );
96067  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
96068                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
96069  VdbeComment((v, "for %s", pTable->zName));
96070
96071  /* Fill the automatic index with content */
96072  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
96073  regRecord = sqlite3GetTempReg(pParse);
96074  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
96075  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
96076  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
96077  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
96078  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
96079  sqlite3VdbeJumpHere(v, addrTop);
96080  sqlite3ReleaseTempReg(pParse, regRecord);
96081
96082  /* Jump here when skipping the initialization */
96083  sqlite3VdbeJumpHere(v, addrInit);
96084}
96085#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
96086
96087#ifndef SQLITE_OMIT_VIRTUALTABLE
96088/*
96089** Allocate and populate an sqlite3_index_info structure. It is the
96090** responsibility of the caller to eventually release the structure
96091** by passing the pointer returned by this function to sqlite3_free().
96092*/
96093static sqlite3_index_info *allocateIndexInfo(
96094  Parse *pParse,
96095  WhereClause *pWC,
96096  struct SrcList_item *pSrc,
96097  ExprList *pOrderBy
96098){
96099  int i, j;
96100  int nTerm;
96101  struct sqlite3_index_constraint *pIdxCons;
96102  struct sqlite3_index_orderby *pIdxOrderBy;
96103  struct sqlite3_index_constraint_usage *pUsage;
96104  WhereTerm *pTerm;
96105  int nOrderBy;
96106  sqlite3_index_info *pIdxInfo;
96107
96108  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
96109
96110  /* Count the number of possible WHERE clause constraints referring
96111  ** to this virtual table */
96112  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
96113    if( pTerm->leftCursor != pSrc->iCursor ) continue;
96114    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
96115    testcase( pTerm->eOperator==WO_IN );
96116    testcase( pTerm->eOperator==WO_ISNULL );
96117    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
96118    nTerm++;
96119  }
96120
96121  /* If the ORDER BY clause contains only columns in the current
96122  ** virtual table then allocate space for the aOrderBy part of
96123  ** the sqlite3_index_info structure.
96124  */
96125  nOrderBy = 0;
96126  if( pOrderBy ){
96127    for(i=0; i<pOrderBy->nExpr; i++){
96128      Expr *pExpr = pOrderBy->a[i].pExpr;
96129      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
96130    }
96131    if( i==pOrderBy->nExpr ){
96132      nOrderBy = pOrderBy->nExpr;
96133    }
96134  }
96135
96136  /* Allocate the sqlite3_index_info structure
96137  */
96138  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
96139                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
96140                           + sizeof(*pIdxOrderBy)*nOrderBy );
96141  if( pIdxInfo==0 ){
96142    sqlite3ErrorMsg(pParse, "out of memory");
96143    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
96144    return 0;
96145  }
96146
96147  /* Initialize the structure.  The sqlite3_index_info structure contains
96148  ** many fields that are declared "const" to prevent xBestIndex from
96149  ** changing them.  We have to do some funky casting in order to
96150  ** initialize those fields.
96151  */
96152  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
96153  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
96154  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
96155  *(int*)&pIdxInfo->nConstraint = nTerm;
96156  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
96157  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
96158  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
96159  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
96160                                                                   pUsage;
96161
96162  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
96163    if( pTerm->leftCursor != pSrc->iCursor ) continue;
96164    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
96165    testcase( pTerm->eOperator==WO_IN );
96166    testcase( pTerm->eOperator==WO_ISNULL );
96167    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
96168    pIdxCons[j].iColumn = pTerm->u.leftColumn;
96169    pIdxCons[j].iTermOffset = i;
96170    pIdxCons[j].op = (u8)pTerm->eOperator;
96171    /* The direct assignment in the previous line is possible only because
96172    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
96173    ** following asserts verify this fact. */
96174    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
96175    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
96176    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
96177    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
96178    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
96179    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
96180    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
96181    j++;
96182  }
96183  for(i=0; i<nOrderBy; i++){
96184    Expr *pExpr = pOrderBy->a[i].pExpr;
96185    pIdxOrderBy[i].iColumn = pExpr->iColumn;
96186    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
96187  }
96188
96189  return pIdxInfo;
96190}
96191
96192/*
96193** The table object reference passed as the second argument to this function
96194** must represent a virtual table. This function invokes the xBestIndex()
96195** method of the virtual table with the sqlite3_index_info pointer passed
96196** as the argument.
96197**
96198** If an error occurs, pParse is populated with an error message and a
96199** non-zero value is returned. Otherwise, 0 is returned and the output
96200** part of the sqlite3_index_info structure is left populated.
96201**
96202** Whether or not an error is returned, it is the responsibility of the
96203** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
96204** that this is required.
96205*/
96206static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
96207  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
96208  int i;
96209  int rc;
96210
96211  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
96212  TRACE_IDX_INPUTS(p);
96213  rc = pVtab->pModule->xBestIndex(pVtab, p);
96214  TRACE_IDX_OUTPUTS(p);
96215
96216  if( rc!=SQLITE_OK ){
96217    if( rc==SQLITE_NOMEM ){
96218      pParse->db->mallocFailed = 1;
96219    }else if( !pVtab->zErrMsg ){
96220      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
96221    }else{
96222      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
96223    }
96224  }
96225  sqlite3_free(pVtab->zErrMsg);
96226  pVtab->zErrMsg = 0;
96227
96228  for(i=0; i<p->nConstraint; i++){
96229    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
96230      sqlite3ErrorMsg(pParse,
96231          "table %s: xBestIndex returned an invalid plan", pTab->zName);
96232    }
96233  }
96234
96235  return pParse->nErr;
96236}
96237
96238
96239/*
96240** Compute the best index for a virtual table.
96241**
96242** The best index is computed by the xBestIndex method of the virtual
96243** table module.  This routine is really just a wrapper that sets up
96244** the sqlite3_index_info structure that is used to communicate with
96245** xBestIndex.
96246**
96247** In a join, this routine might be called multiple times for the
96248** same virtual table.  The sqlite3_index_info structure is created
96249** and initialized on the first invocation and reused on all subsequent
96250** invocations.  The sqlite3_index_info structure is also used when
96251** code is generated to access the virtual table.  The whereInfoDelete()
96252** routine takes care of freeing the sqlite3_index_info structure after
96253** everybody has finished with it.
96254*/
96255static void bestVirtualIndex(
96256  Parse *pParse,                  /* The parsing context */
96257  WhereClause *pWC,               /* The WHERE clause */
96258  struct SrcList_item *pSrc,      /* The FROM clause term to search */
96259  Bitmask notReady,               /* Mask of cursors that are not available */
96260  ExprList *pOrderBy,             /* The order by clause */
96261  WhereCost *pCost,               /* Lowest cost query plan */
96262  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
96263){
96264  Table *pTab = pSrc->pTab;
96265  sqlite3_index_info *pIdxInfo;
96266  struct sqlite3_index_constraint *pIdxCons;
96267  struct sqlite3_index_constraint_usage *pUsage;
96268  WhereTerm *pTerm;
96269  int i, j;
96270  int nOrderBy;
96271  double rCost;
96272
96273  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
96274  ** malloc in allocateIndexInfo() fails and this function returns leaving
96275  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
96276  */
96277  memset(pCost, 0, sizeof(*pCost));
96278  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
96279
96280  /* If the sqlite3_index_info structure has not been previously
96281  ** allocated and initialized, then allocate and initialize it now.
96282  */
96283  pIdxInfo = *ppIdxInfo;
96284  if( pIdxInfo==0 ){
96285    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
96286  }
96287  if( pIdxInfo==0 ){
96288    return;
96289  }
96290
96291  /* At this point, the sqlite3_index_info structure that pIdxInfo points
96292  ** to will have been initialized, either during the current invocation or
96293  ** during some prior invocation.  Now we just have to customize the
96294  ** details of pIdxInfo for the current invocation and pass it to
96295  ** xBestIndex.
96296  */
96297
96298  /* The module name must be defined. Also, by this point there must
96299  ** be a pointer to an sqlite3_vtab structure. Otherwise
96300  ** sqlite3ViewGetColumnNames() would have picked up the error.
96301  */
96302  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
96303  assert( sqlite3GetVTable(pParse->db, pTab) );
96304
96305  /* Set the aConstraint[].usable fields and initialize all
96306  ** output variables to zero.
96307  **
96308  ** aConstraint[].usable is true for constraints where the right-hand
96309  ** side contains only references to tables to the left of the current
96310  ** table.  In other words, if the constraint is of the form:
96311  **
96312  **           column = expr
96313  **
96314  ** and we are evaluating a join, then the constraint on column is
96315  ** only valid if all tables referenced in expr occur to the left
96316  ** of the table containing column.
96317  **
96318  ** The aConstraints[] array contains entries for all constraints
96319  ** on the current table.  That way we only have to compute it once
96320  ** even though we might try to pick the best index multiple times.
96321  ** For each attempt at picking an index, the order of tables in the
96322  ** join might be different so we have to recompute the usable flag
96323  ** each time.
96324  */
96325  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
96326  pUsage = pIdxInfo->aConstraintUsage;
96327  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
96328    j = pIdxCons->iTermOffset;
96329    pTerm = &pWC->a[j];
96330    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
96331  }
96332  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
96333  if( pIdxInfo->needToFreeIdxStr ){
96334    sqlite3_free(pIdxInfo->idxStr);
96335  }
96336  pIdxInfo->idxStr = 0;
96337  pIdxInfo->idxNum = 0;
96338  pIdxInfo->needToFreeIdxStr = 0;
96339  pIdxInfo->orderByConsumed = 0;
96340  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
96341  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
96342  nOrderBy = pIdxInfo->nOrderBy;
96343  if( !pOrderBy ){
96344    pIdxInfo->nOrderBy = 0;
96345  }
96346
96347  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
96348    return;
96349  }
96350
96351  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
96352  for(i=0; i<pIdxInfo->nConstraint; i++){
96353    if( pUsage[i].argvIndex>0 ){
96354      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
96355    }
96356  }
96357
96358  /* If there is an ORDER BY clause, and the selected virtual table index
96359  ** does not satisfy it, increase the cost of the scan accordingly. This
96360  ** matches the processing for non-virtual tables in bestBtreeIndex().
96361  */
96362  rCost = pIdxInfo->estimatedCost;
96363  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
96364    rCost += estLog(rCost)*rCost;
96365  }
96366
96367  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
96368  ** inital value of lowestCost in this loop. If it is, then the
96369  ** (cost<lowestCost) test below will never be true.
96370  **
96371  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
96372  ** is defined.
96373  */
96374  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
96375    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
96376  }else{
96377    pCost->rCost = rCost;
96378  }
96379  pCost->plan.u.pVtabIdx = pIdxInfo;
96380  if( pIdxInfo->orderByConsumed ){
96381    pCost->plan.wsFlags |= WHERE_ORDERBY;
96382  }
96383  pCost->plan.nEq = 0;
96384  pIdxInfo->nOrderBy = nOrderBy;
96385
96386  /* Try to find a more efficient access pattern by using multiple indexes
96387  ** to optimize an OR expression within the WHERE clause.
96388  */
96389  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
96390}
96391#endif /* SQLITE_OMIT_VIRTUALTABLE */
96392
96393/*
96394** Argument pIdx is a pointer to an index structure that has an array of
96395** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
96396** stored in Index.aSample. The domain of values stored in said column
96397** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
96398** Region 0 contains all values smaller than the first sample value. Region
96399** 1 contains values larger than or equal to the value of the first sample,
96400** but smaller than the value of the second. And so on.
96401**
96402** If successful, this function determines which of the regions value
96403** pVal lies in, sets *piRegion to the region index (a value between 0
96404** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
96405** Or, if an OOM occurs while converting text values between encodings,
96406** SQLITE_NOMEM is returned and *piRegion is undefined.
96407*/
96408#ifdef SQLITE_ENABLE_STAT2
96409static int whereRangeRegion(
96410  Parse *pParse,              /* Database connection */
96411  Index *pIdx,                /* Index to consider domain of */
96412  sqlite3_value *pVal,        /* Value to consider */
96413  int *piRegion               /* OUT: Region of domain in which value lies */
96414){
96415  if( ALWAYS(pVal) ){
96416    IndexSample *aSample = pIdx->aSample;
96417    int i = 0;
96418    int eType = sqlite3_value_type(pVal);
96419
96420    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
96421      double r = sqlite3_value_double(pVal);
96422      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
96423        if( aSample[i].eType==SQLITE_NULL ) continue;
96424        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
96425      }
96426    }else{
96427      sqlite3 *db = pParse->db;
96428      CollSeq *pColl;
96429      const u8 *z;
96430      int n;
96431
96432      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
96433      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
96434
96435      if( eType==SQLITE_BLOB ){
96436        z = (const u8 *)sqlite3_value_blob(pVal);
96437        pColl = db->pDfltColl;
96438        assert( pColl->enc==SQLITE_UTF8 );
96439      }else{
96440        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
96441        if( pColl==0 ){
96442          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
96443                          *pIdx->azColl);
96444          return SQLITE_ERROR;
96445        }
96446        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
96447        if( !z ){
96448          return SQLITE_NOMEM;
96449        }
96450        assert( z && pColl && pColl->xCmp );
96451      }
96452      n = sqlite3ValueBytes(pVal, pColl->enc);
96453
96454      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
96455        int r;
96456        int eSampletype = aSample[i].eType;
96457        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
96458        if( (eSampletype!=eType) ) break;
96459#ifndef SQLITE_OMIT_UTF16
96460        if( pColl->enc!=SQLITE_UTF8 ){
96461          int nSample;
96462          char *zSample = sqlite3Utf8to16(
96463              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
96464          );
96465          if( !zSample ){
96466            assert( db->mallocFailed );
96467            return SQLITE_NOMEM;
96468          }
96469          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
96470          sqlite3DbFree(db, zSample);
96471        }else
96472#endif
96473        {
96474          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
96475        }
96476        if( r>0 ) break;
96477      }
96478    }
96479
96480    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
96481    *piRegion = i;
96482  }
96483  return SQLITE_OK;
96484}
96485#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
96486
96487/*
96488** If expression pExpr represents a literal value, set *pp to point to
96489** an sqlite3_value structure containing the same value, with affinity
96490** aff applied to it, before returning. It is the responsibility of the
96491** caller to eventually release this structure by passing it to
96492** sqlite3ValueFree().
96493**
96494** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
96495** is an SQL variable that currently has a non-NULL value bound to it,
96496** create an sqlite3_value structure containing this value, again with
96497** affinity aff applied to it, instead.
96498**
96499** If neither of the above apply, set *pp to NULL.
96500**
96501** If an error occurs, return an error code. Otherwise, SQLITE_OK.
96502*/
96503#ifdef SQLITE_ENABLE_STAT2
96504static int valueFromExpr(
96505  Parse *pParse,
96506  Expr *pExpr,
96507  u8 aff,
96508  sqlite3_value **pp
96509){
96510  /* The evalConstExpr() function will have already converted any TK_VARIABLE
96511  ** expression involved in an comparison into a TK_REGISTER. */
96512  assert( pExpr->op!=TK_VARIABLE );
96513  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
96514    int iVar = pExpr->iColumn;
96515    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
96516    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
96517    return SQLITE_OK;
96518  }
96519  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
96520}
96521#endif
96522
96523/*
96524** This function is used to estimate the number of rows that will be visited
96525** by scanning an index for a range of values. The range may have an upper
96526** bound, a lower bound, or both. The WHERE clause terms that set the upper
96527** and lower bounds are represented by pLower and pUpper respectively. For
96528** example, assuming that index p is on t1(a):
96529**
96530**   ... FROM t1 WHERE a > ? AND a < ? ...
96531**                    |_____|   |_____|
96532**                       |         |
96533**                     pLower    pUpper
96534**
96535** If either of the upper or lower bound is not present, then NULL is passed in
96536** place of the corresponding WhereTerm.
96537**
96538** The nEq parameter is passed the index of the index column subject to the
96539** range constraint. Or, equivalently, the number of equality constraints
96540** optimized by the proposed index scan. For example, assuming index p is
96541** on t1(a, b), and the SQL query is:
96542**
96543**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
96544**
96545** then nEq should be passed the value 1 (as the range restricted column,
96546** b, is the second left-most column of the index). Or, if the query is:
96547**
96548**   ... FROM t1 WHERE a > ? AND a < ? ...
96549**
96550** then nEq should be passed 0.
96551**
96552** The returned value is an integer between 1 and 100, inclusive. A return
96553** value of 1 indicates that the proposed range scan is expected to visit
96554** approximately 1/100th (1%) of the rows selected by the nEq equality
96555** constraints (if any). A return value of 100 indicates that it is expected
96556** that the range scan will visit every row (100%) selected by the equality
96557** constraints.
96558**
96559** In the absence of sqlite_stat2 ANALYZE data, each range inequality
96560** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
96561** results in a return of 33 and a range constraint (x>? AND x<?) results
96562** in a return of 11.
96563*/
96564static int whereRangeScanEst(
96565  Parse *pParse,       /* Parsing & code generating context */
96566  Index *p,            /* The index containing the range-compared column; "x" */
96567  int nEq,             /* index into p->aCol[] of the range-compared column */
96568  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
96569  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
96570  int *piEst           /* OUT: Return value */
96571){
96572  int rc = SQLITE_OK;
96573
96574#ifdef SQLITE_ENABLE_STAT2
96575
96576  if( nEq==0 && p->aSample ){
96577    sqlite3_value *pLowerVal = 0;
96578    sqlite3_value *pUpperVal = 0;
96579    int iEst;
96580    int iLower = 0;
96581    int iUpper = SQLITE_INDEX_SAMPLES;
96582    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
96583
96584    if( pLower ){
96585      Expr *pExpr = pLower->pExpr->pRight;
96586      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
96587    }
96588    if( rc==SQLITE_OK && pUpper ){
96589      Expr *pExpr = pUpper->pExpr->pRight;
96590      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
96591    }
96592
96593    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
96594      sqlite3ValueFree(pLowerVal);
96595      sqlite3ValueFree(pUpperVal);
96596      goto range_est_fallback;
96597    }else if( pLowerVal==0 ){
96598      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
96599      if( pLower ) iLower = iUpper/2;
96600    }else if( pUpperVal==0 ){
96601      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
96602      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
96603    }else{
96604      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
96605      if( rc==SQLITE_OK ){
96606        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
96607      }
96608    }
96609
96610    iEst = iUpper - iLower;
96611    testcase( iEst==SQLITE_INDEX_SAMPLES );
96612    assert( iEst<=SQLITE_INDEX_SAMPLES );
96613    if( iEst<1 ){
96614      iEst = 1;
96615    }
96616
96617    sqlite3ValueFree(pLowerVal);
96618    sqlite3ValueFree(pUpperVal);
96619    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
96620    return rc;
96621  }
96622range_est_fallback:
96623#else
96624  UNUSED_PARAMETER(pParse);
96625  UNUSED_PARAMETER(p);
96626  UNUSED_PARAMETER(nEq);
96627#endif
96628  assert( pLower || pUpper );
96629  if( pLower && pUpper ){
96630    *piEst = 11;
96631  }else{
96632    *piEst = 33;
96633  }
96634  return rc;
96635}
96636
96637
96638/*
96639** Find the query plan for accessing a particular table.  Write the
96640** best query plan and its cost into the WhereCost object supplied as the
96641** last parameter.
96642**
96643** The lowest cost plan wins.  The cost is an estimate of the amount of
96644** CPU and disk I/O need to process the request using the selected plan.
96645** Factors that influence cost include:
96646**
96647**    *  The estimated number of rows that will be retrieved.  (The
96648**       fewer the better.)
96649**
96650**    *  Whether or not sorting must occur.
96651**
96652**    *  Whether or not there must be separate lookups in the
96653**       index and in the main table.
96654**
96655** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
96656** the SQL statement, then this function only considers plans using the
96657** named index. If no such plan is found, then the returned cost is
96658** SQLITE_BIG_DBL. If a plan is found that uses the named index,
96659** then the cost is calculated in the usual way.
96660**
96661** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
96662** in the SELECT statement, then no indexes are considered. However, the
96663** selected plan may still take advantage of the tables built-in rowid
96664** index.
96665*/
96666static void bestBtreeIndex(
96667  Parse *pParse,              /* The parsing context */
96668  WhereClause *pWC,           /* The WHERE clause */
96669  struct SrcList_item *pSrc,  /* The FROM clause term to search */
96670  Bitmask notReady,           /* Mask of cursors that are not available */
96671  ExprList *pOrderBy,         /* The ORDER BY clause */
96672  WhereCost *pCost            /* Lowest cost query plan */
96673){
96674  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
96675  Index *pProbe;              /* An index we are evaluating */
96676  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
96677  int eqTermMask;             /* Current mask of valid equality operators */
96678  int idxEqTermMask;          /* Index mask of valid equality operators */
96679  Index sPk;                  /* A fake index object for the primary key */
96680  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
96681  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
96682  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
96683
96684  /* Initialize the cost to a worst-case value */
96685  memset(pCost, 0, sizeof(*pCost));
96686  pCost->rCost = SQLITE_BIG_DBL;
96687
96688  /* If the pSrc table is the right table of a LEFT JOIN then we may not
96689  ** use an index to satisfy IS NULL constraints on that table.  This is
96690  ** because columns might end up being NULL if the table does not match -
96691  ** a circumstance which the index cannot help us discover.  Ticket #2177.
96692  */
96693  if( pSrc->jointype & JT_LEFT ){
96694    idxEqTermMask = WO_EQ|WO_IN;
96695  }else{
96696    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
96697  }
96698
96699  if( pSrc->pIndex ){
96700    /* An INDEXED BY clause specifies a particular index to use */
96701    pIdx = pProbe = pSrc->pIndex;
96702    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
96703    eqTermMask = idxEqTermMask;
96704  }else{
96705    /* There is no INDEXED BY clause.  Create a fake Index object to
96706    ** represent the primary key */
96707    Index *pFirst;                /* Any other index on the table */
96708    memset(&sPk, 0, sizeof(Index));
96709    sPk.nColumn = 1;
96710    sPk.aiColumn = &aiColumnPk;
96711    sPk.aiRowEst = aiRowEstPk;
96712    aiRowEstPk[1] = 1;
96713    sPk.onError = OE_Replace;
96714    sPk.pTable = pSrc->pTab;
96715    pFirst = pSrc->pTab->pIndex;
96716    if( pSrc->notIndexed==0 ){
96717      sPk.pNext = pFirst;
96718    }
96719    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
96720    ** table.  Get this information from the ANALYZE information if it is
96721    ** available.  If not available, assume the table 1 million rows in size.
96722    */
96723    if( pFirst ){
96724      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
96725      aiRowEstPk[0] = pFirst->aiRowEst[0];
96726    }else{
96727      aiRowEstPk[0] = 1000000;
96728    }
96729    pProbe = &sPk;
96730    wsFlagMask = ~(
96731        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
96732    );
96733    eqTermMask = WO_EQ|WO_IN;
96734    pIdx = 0;
96735  }
96736
96737  /* Loop over all indices looking for the best one to use
96738  */
96739  for(; pProbe; pIdx=pProbe=pProbe->pNext){
96740    const unsigned int * const aiRowEst = pProbe->aiRowEst;
96741    double cost;                /* Cost of using pProbe */
96742    double nRow;                /* Estimated number of rows in result set */
96743    int rev;                    /* True to scan in reverse order */
96744    int wsFlags = 0;
96745    Bitmask used = 0;
96746
96747    /* The following variables are populated based on the properties of
96748    ** scan being evaluated. They are then used to determine the expected
96749    ** cost and number of rows returned.
96750    **
96751    **  nEq:
96752    **    Number of equality terms that can be implemented using the index.
96753    **
96754    **  nInMul:
96755    **    The "in-multiplier". This is an estimate of how many seek operations
96756    **    SQLite must perform on the index in question. For example, if the
96757    **    WHERE clause is:
96758    **
96759    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
96760    **
96761    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
96762    **    set to 9. Given the same schema and either of the following WHERE
96763    **    clauses:
96764    **
96765    **      WHERE a =  1
96766    **      WHERE a >= 2
96767    **
96768    **    nInMul is set to 1.
96769    **
96770    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
96771    **    the sub-select is assumed to return 25 rows for the purposes of
96772    **    determining nInMul.
96773    **
96774    **  bInEst:
96775    **    Set to true if there was at least one "x IN (SELECT ...)" term used
96776    **    in determining the value of nInMul.
96777    **
96778    **  estBound:
96779    **    An estimate on the amount of the table that must be searched.  A
96780    **    value of 100 means the entire table is searched.  Range constraints
96781    **    might reduce this to a value less than 100 to indicate that only
96782    **    a fraction of the table needs searching.  In the absence of
96783    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
96784    **    space to 1/3rd its original size.  So an x>? constraint reduces
96785    **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
96786    **
96787    **  bSort:
96788    **    Boolean. True if there is an ORDER BY clause that will require an
96789    **    external sort (i.e. scanning the index being evaluated will not
96790    **    correctly order records).
96791    **
96792    **  bLookup:
96793    **    Boolean. True if for each index entry visited a lookup on the
96794    **    corresponding table b-tree is required. This is always false
96795    **    for the rowid index. For other indexes, it is true unless all the
96796    **    columns of the table used by the SELECT statement are present in
96797    **    the index (such an index is sometimes described as a covering index).
96798    **    For example, given the index on (a, b), the second of the following
96799    **    two queries requires table b-tree lookups, but the first does not.
96800    **
96801    **             SELECT a, b    FROM tbl WHERE a = 1;
96802    **             SELECT a, b, c FROM tbl WHERE a = 1;
96803    */
96804    int nEq;
96805    int bInEst = 0;
96806    int nInMul = 1;
96807    int estBound = 100;
96808    int nBound = 0;             /* Number of range constraints seen */
96809    int bSort = 0;
96810    int bLookup = 0;
96811    WhereTerm *pTerm;           /* A single term of the WHERE clause */
96812
96813    /* Determine the values of nEq and nInMul */
96814    for(nEq=0; nEq<pProbe->nColumn; nEq++){
96815      int j = pProbe->aiColumn[nEq];
96816      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
96817      if( pTerm==0 ) break;
96818      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
96819      if( pTerm->eOperator & WO_IN ){
96820        Expr *pExpr = pTerm->pExpr;
96821        wsFlags |= WHERE_COLUMN_IN;
96822        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96823          nInMul *= 25;
96824          bInEst = 1;
96825        }else if( ALWAYS(pExpr->x.pList) ){
96826          nInMul *= pExpr->x.pList->nExpr + 1;
96827        }
96828      }else if( pTerm->eOperator & WO_ISNULL ){
96829        wsFlags |= WHERE_COLUMN_NULL;
96830      }
96831      used |= pTerm->prereqRight;
96832    }
96833
96834    /* Determine the value of estBound. */
96835    if( nEq<pProbe->nColumn ){
96836      int j = pProbe->aiColumn[nEq];
96837      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
96838        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
96839        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
96840        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
96841        if( pTop ){
96842          nBound = 1;
96843          wsFlags |= WHERE_TOP_LIMIT;
96844          used |= pTop->prereqRight;
96845        }
96846        if( pBtm ){
96847          nBound++;
96848          wsFlags |= WHERE_BTM_LIMIT;
96849          used |= pBtm->prereqRight;
96850        }
96851        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
96852      }
96853    }else if( pProbe->onError!=OE_None ){
96854      testcase( wsFlags & WHERE_COLUMN_IN );
96855      testcase( wsFlags & WHERE_COLUMN_NULL );
96856      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
96857        wsFlags |= WHERE_UNIQUE;
96858      }
96859    }
96860
96861    /* If there is an ORDER BY clause and the index being considered will
96862    ** naturally scan rows in the required order, set the appropriate flags
96863    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
96864    ** will scan rows in a different order, set the bSort variable.  */
96865    if( pOrderBy ){
96866      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
96867        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
96868      ){
96869        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
96870        wsFlags |= (rev ? WHERE_REVERSE : 0);
96871      }else{
96872        bSort = 1;
96873      }
96874    }
96875
96876    /* If currently calculating the cost of using an index (not the IPK
96877    ** index), determine if all required column data may be obtained without
96878    ** using the main table (i.e. if the index is a covering
96879    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
96880    ** wsFlags. Otherwise, set the bLookup variable to true.  */
96881    if( pIdx && wsFlags ){
96882      Bitmask m = pSrc->colUsed;
96883      int j;
96884      for(j=0; j<pIdx->nColumn; j++){
96885        int x = pIdx->aiColumn[j];
96886        if( x<BMS-1 ){
96887          m &= ~(((Bitmask)1)<<x);
96888        }
96889      }
96890      if( m==0 ){
96891        wsFlags |= WHERE_IDX_ONLY;
96892      }else{
96893        bLookup = 1;
96894      }
96895    }
96896
96897    /*
96898    ** Estimate the number of rows of output.  For an IN operator,
96899    ** do not let the estimate exceed half the rows in the table.
96900    */
96901    nRow = (double)(aiRowEst[nEq] * nInMul);
96902    if( bInEst && nRow*2>aiRowEst[0] ){
96903      nRow = aiRowEst[0]/2;
96904      nInMul = (int)(nRow / aiRowEst[nEq]);
96905    }
96906
96907    /* Assume constant cost to access a row and logarithmic cost to
96908    ** do a binary search.  Hence, the initial cost is the number of output
96909    ** rows plus log2(table-size) times the number of binary searches.
96910    */
96911    cost = nRow + nInMul*estLog(aiRowEst[0]);
96912
96913    /* Adjust the number of rows and the cost downward to reflect rows
96914    ** that are excluded by range constraints.
96915    */
96916    nRow = (nRow * (double)estBound) / (double)100;
96917    cost = (cost * (double)estBound) / (double)100;
96918
96919    /* Add in the estimated cost of sorting the result
96920    */
96921    if( bSort ){
96922      cost += cost*estLog(cost);
96923    }
96924
96925    /* If all information can be taken directly from the index, we avoid
96926    ** doing table lookups.  This reduces the cost by half.  (Not really -
96927    ** this needs to be fixed.)
96928    */
96929    if( pIdx && bLookup==0 ){
96930      cost /= (double)2;
96931    }
96932    /**** Cost of using this index has now been computed ****/
96933
96934    /* If there are additional constraints on this table that cannot
96935    ** be used with the current index, but which might lower the number
96936    ** of output rows, adjust the nRow value accordingly.  This only
96937    ** matters if the current index is the least costly, so do not bother
96938    ** with this step if we already know this index will not be chosen.
96939    ** Also, never reduce the output row count below 2 using this step.
96940    **
96941    ** Do not reduce the output row count if pSrc is the only table that
96942    ** is notReady; if notReady is a power of two.  This will be the case
96943    ** when the main sqlite3WhereBegin() loop is scanning for a table with
96944    ** and "optimal" index, and on such a scan the output row count
96945    ** reduction is not valid because it does not update the "pCost->used"
96946    ** bitmap.  The notReady bitmap will also be a power of two when we
96947    ** are scanning for the last table in a 64-way join.  We are willing
96948    ** to bypass this optimization in that corner case.
96949    */
96950    if( nRow>2 && cost<=pCost->rCost && (notReady & (notReady-1))!=0 ){
96951      int k;                       /* Loop counter */
96952      int nSkipEq = nEq;           /* Number of == constraints to skip */
96953      int nSkipRange = nBound;     /* Number of < constraints to skip */
96954      Bitmask thisTab;             /* Bitmap for pSrc */
96955
96956      thisTab = getMask(pWC->pMaskSet, iCur);
96957      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
96958        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
96959        if( (pTerm->prereqAll & notReady)!=thisTab ) continue;
96960        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
96961          if( nSkipEq ){
96962            /* Ignore the first nEq equality matches since the index
96963            ** has already accounted for these */
96964            nSkipEq--;
96965          }else{
96966            /* Assume each additional equality match reduces the result
96967            ** set size by a factor of 10 */
96968            nRow /= 10;
96969          }
96970        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
96971          if( nSkipRange ){
96972            /* Ignore the first nBound range constraints since the index
96973            ** has already accounted for these */
96974            nSkipRange--;
96975          }else{
96976            /* Assume each additional range constraint reduces the result
96977            ** set size by a factor of 3 */
96978            nRow /= 3;
96979          }
96980        }else{
96981          /* Any other expression lowers the output row count by half */
96982          nRow /= 2;
96983        }
96984      }
96985      if( nRow<2 ) nRow = 2;
96986    }
96987
96988
96989    WHERETRACE((
96990      "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
96991      "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
96992      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
96993      nEq, nInMul, estBound, bSort, bLookup, wsFlags,
96994      notReady, nRow, cost, used
96995    ));
96996
96997    /* If this index is the best we have seen so far, then record this
96998    ** index and its cost in the pCost structure.
96999    */
97000    if( (!pIdx || wsFlags)
97001     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->nRow))
97002    ){
97003      pCost->rCost = cost;
97004      pCost->nRow = nRow;
97005      pCost->used = used;
97006      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
97007      pCost->plan.nEq = nEq;
97008      pCost->plan.u.pIdx = pIdx;
97009    }
97010
97011    /* If there was an INDEXED BY clause, then only that one index is
97012    ** considered. */
97013    if( pSrc->pIndex ) break;
97014
97015    /* Reset masks for the next index in the loop */
97016    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
97017    eqTermMask = idxEqTermMask;
97018  }
97019
97020  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
97021  ** is set, then reverse the order that the index will be scanned
97022  ** in. This is used for application testing, to help find cases
97023  ** where application behaviour depends on the (undefined) order that
97024  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
97025  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
97026    pCost->plan.wsFlags |= WHERE_REVERSE;
97027  }
97028
97029  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
97030  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
97031  assert( pSrc->pIndex==0
97032       || pCost->plan.u.pIdx==0
97033       || pCost->plan.u.pIdx==pSrc->pIndex
97034  );
97035
97036  WHERETRACE(("best index is: %s\n",
97037    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
97038         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
97039  ));
97040
97041  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
97042  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
97043  pCost->plan.wsFlags |= eqTermMask;
97044}
97045
97046/*
97047** Find the query plan for accessing table pSrc->pTab. Write the
97048** best query plan and its cost into the WhereCost object supplied
97049** as the last parameter. This function may calculate the cost of
97050** both real and virtual table scans.
97051*/
97052static void bestIndex(
97053  Parse *pParse,              /* The parsing context */
97054  WhereClause *pWC,           /* The WHERE clause */
97055  struct SrcList_item *pSrc,  /* The FROM clause term to search */
97056  Bitmask notReady,           /* Mask of cursors that are not available */
97057  ExprList *pOrderBy,         /* The ORDER BY clause */
97058  WhereCost *pCost            /* Lowest cost query plan */
97059){
97060#ifndef SQLITE_OMIT_VIRTUALTABLE
97061  if( IsVirtual(pSrc->pTab) ){
97062    sqlite3_index_info *p = 0;
97063    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
97064    if( p->needToFreeIdxStr ){
97065      sqlite3_free(p->idxStr);
97066    }
97067    sqlite3DbFree(pParse->db, p);
97068  }else
97069#endif
97070  {
97071    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
97072  }
97073}
97074
97075/*
97076** Disable a term in the WHERE clause.  Except, do not disable the term
97077** if it controls a LEFT OUTER JOIN and it did not originate in the ON
97078** or USING clause of that join.
97079**
97080** Consider the term t2.z='ok' in the following queries:
97081**
97082**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
97083**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
97084**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
97085**
97086** The t2.z='ok' is disabled in the in (2) because it originates
97087** in the ON clause.  The term is disabled in (3) because it is not part
97088** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
97089**
97090** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
97091** completely satisfied by indices.
97092**
97093** Disabling a term causes that term to not be tested in the inner loop
97094** of the join.  Disabling is an optimization.  When terms are satisfied
97095** by indices, we disable them to prevent redundant tests in the inner
97096** loop.  We would get the correct results if nothing were ever disabled,
97097** but joins might run a little slower.  The trick is to disable as much
97098** as we can without disabling too much.  If we disabled in (1), we'd get
97099** the wrong answer.  See ticket #813.
97100*/
97101static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
97102  if( pTerm
97103      && (pTerm->wtFlags & TERM_CODED)==0
97104      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
97105  ){
97106    pTerm->wtFlags |= TERM_CODED;
97107    if( pTerm->iParent>=0 ){
97108      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
97109      if( (--pOther->nChild)==0 ){
97110        disableTerm(pLevel, pOther);
97111      }
97112    }
97113  }
97114}
97115
97116/*
97117** Code an OP_Affinity opcode to apply the column affinity string zAff
97118** to the n registers starting at base.
97119**
97120** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
97121** beginning and end of zAff are ignored.  If all entries in zAff are
97122** SQLITE_AFF_NONE, then no code gets generated.
97123**
97124** This routine makes its own copy of zAff so that the caller is free
97125** to modify zAff after this routine returns.
97126*/
97127static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
97128  Vdbe *v = pParse->pVdbe;
97129  if( zAff==0 ){
97130    assert( pParse->db->mallocFailed );
97131    return;
97132  }
97133  assert( v!=0 );
97134
97135  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
97136  ** and end of the affinity string.
97137  */
97138  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
97139    n--;
97140    base++;
97141    zAff++;
97142  }
97143  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
97144    n--;
97145  }
97146
97147  /* Code the OP_Affinity opcode if there is anything left to do. */
97148  if( n>0 ){
97149    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
97150    sqlite3VdbeChangeP4(v, -1, zAff, n);
97151    sqlite3ExprCacheAffinityChange(pParse, base, n);
97152  }
97153}
97154
97155
97156/*
97157** Generate code for a single equality term of the WHERE clause.  An equality
97158** term can be either X=expr or X IN (...).   pTerm is the term to be
97159** coded.
97160**
97161** The current value for the constraint is left in register iReg.
97162**
97163** For a constraint of the form X=expr, the expression is evaluated and its
97164** result is left on the stack.  For constraints of the form X IN (...)
97165** this routine sets up a loop that will iterate over all values of X.
97166*/
97167static int codeEqualityTerm(
97168  Parse *pParse,      /* The parsing context */
97169  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
97170  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
97171  int iTarget         /* Attempt to leave results in this register */
97172){
97173  Expr *pX = pTerm->pExpr;
97174  Vdbe *v = pParse->pVdbe;
97175  int iReg;                  /* Register holding results */
97176
97177  assert( iTarget>0 );
97178  if( pX->op==TK_EQ ){
97179    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
97180  }else if( pX->op==TK_ISNULL ){
97181    iReg = iTarget;
97182    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
97183#ifndef SQLITE_OMIT_SUBQUERY
97184  }else{
97185    int eType;
97186    int iTab;
97187    struct InLoop *pIn;
97188
97189    assert( pX->op==TK_IN );
97190    iReg = iTarget;
97191    eType = sqlite3FindInIndex(pParse, pX, 0);
97192    iTab = pX->iTable;
97193    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
97194    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
97195    if( pLevel->u.in.nIn==0 ){
97196      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
97197    }
97198    pLevel->u.in.nIn++;
97199    pLevel->u.in.aInLoop =
97200       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
97201                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
97202    pIn = pLevel->u.in.aInLoop;
97203    if( pIn ){
97204      pIn += pLevel->u.in.nIn - 1;
97205      pIn->iCur = iTab;
97206      if( eType==IN_INDEX_ROWID ){
97207        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
97208      }else{
97209        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
97210      }
97211      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
97212    }else{
97213      pLevel->u.in.nIn = 0;
97214    }
97215#endif
97216  }
97217  disableTerm(pLevel, pTerm);
97218  return iReg;
97219}
97220
97221/*
97222** Generate code that will evaluate all == and IN constraints for an
97223** index.
97224**
97225** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
97226** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
97227** The index has as many as three equality constraints, but in this
97228** example, the third "c" value is an inequality.  So only two
97229** constraints are coded.  This routine will generate code to evaluate
97230** a==5 and b IN (1,2,3).  The current values for a and b will be stored
97231** in consecutive registers and the index of the first register is returned.
97232**
97233** In the example above nEq==2.  But this subroutine works for any value
97234** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
97235** The only thing it does is allocate the pLevel->iMem memory cell and
97236** compute the affinity string.
97237**
97238** This routine always allocates at least one memory cell and returns
97239** the index of that memory cell. The code that
97240** calls this routine will use that memory cell to store the termination
97241** key value of the loop.  If one or more IN operators appear, then
97242** this routine allocates an additional nEq memory cells for internal
97243** use.
97244**
97245** Before returning, *pzAff is set to point to a buffer containing a
97246** copy of the column affinity string of the index allocated using
97247** sqlite3DbMalloc(). Except, entries in the copy of the string associated
97248** with equality constraints that use NONE affinity are set to
97249** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
97250**
97251**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
97252**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
97253**
97254** In the example above, the index on t1(a) has TEXT affinity. But since
97255** the right hand side of the equality constraint (t2.b) has NONE affinity,
97256** no conversion should be attempted before using a t2.b value as part of
97257** a key to search the index. Hence the first byte in the returned affinity
97258** string in this example would be set to SQLITE_AFF_NONE.
97259*/
97260static int codeAllEqualityTerms(
97261  Parse *pParse,        /* Parsing context */
97262  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
97263  WhereClause *pWC,     /* The WHERE clause */
97264  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
97265  int nExtraReg,        /* Number of extra registers to allocate */
97266  char **pzAff          /* OUT: Set to point to affinity string */
97267){
97268  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
97269  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
97270  Index *pIdx;                  /* The index being used for this loop */
97271  int iCur = pLevel->iTabCur;   /* The cursor of the table */
97272  WhereTerm *pTerm;             /* A single constraint term */
97273  int j;                        /* Loop counter */
97274  int regBase;                  /* Base register */
97275  int nReg;                     /* Number of registers to allocate */
97276  char *zAff;                   /* Affinity string to return */
97277
97278  /* This module is only called on query plans that use an index. */
97279  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
97280  pIdx = pLevel->plan.u.pIdx;
97281
97282  /* Figure out how many memory cells we will need then allocate them.
97283  */
97284  regBase = pParse->nMem + 1;
97285  nReg = pLevel->plan.nEq + nExtraReg;
97286  pParse->nMem += nReg;
97287
97288  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
97289  if( !zAff ){
97290    pParse->db->mallocFailed = 1;
97291  }
97292
97293  /* Evaluate the equality constraints
97294  */
97295  assert( pIdx->nColumn>=nEq );
97296  for(j=0; j<nEq; j++){
97297    int r1;
97298    int k = pIdx->aiColumn[j];
97299    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
97300    if( NEVER(pTerm==0) ) break;
97301    /* The following true for indices with redundant columns.
97302    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
97303    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
97304    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97305    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
97306    if( r1!=regBase+j ){
97307      if( nReg==1 ){
97308        sqlite3ReleaseTempReg(pParse, regBase);
97309        regBase = r1;
97310      }else{
97311        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
97312      }
97313    }
97314    testcase( pTerm->eOperator & WO_ISNULL );
97315    testcase( pTerm->eOperator & WO_IN );
97316    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
97317      Expr *pRight = pTerm->pExpr->pRight;
97318      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
97319      if( zAff ){
97320        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
97321          zAff[j] = SQLITE_AFF_NONE;
97322        }
97323        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
97324          zAff[j] = SQLITE_AFF_NONE;
97325        }
97326      }
97327    }
97328  }
97329  *pzAff = zAff;
97330  return regBase;
97331}
97332
97333/*
97334** Generate code for the start of the iLevel-th loop in the WHERE clause
97335** implementation described by pWInfo.
97336*/
97337static Bitmask codeOneLoopStart(
97338  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
97339  int iLevel,          /* Which level of pWInfo->a[] should be coded */
97340  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
97341  Bitmask notReady     /* Which tables are currently available */
97342){
97343  int j, k;            /* Loop counters */
97344  int iCur;            /* The VDBE cursor for the table */
97345  int addrNxt;         /* Where to jump to continue with the next IN case */
97346  int omitTable;       /* True if we use the index only */
97347  int bRev;            /* True if we need to scan in reverse order */
97348  WhereLevel *pLevel;  /* The where level to be coded */
97349  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
97350  WhereTerm *pTerm;               /* A WHERE clause term */
97351  Parse *pParse;                  /* Parsing context */
97352  Vdbe *v;                        /* The prepared stmt under constructions */
97353  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
97354  int addrBrk;                    /* Jump here to break out of the loop */
97355  int addrCont;                   /* Jump here to continue with next cycle */
97356  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
97357  int iReleaseReg = 0;      /* Temp register to free before returning */
97358
97359  pParse = pWInfo->pParse;
97360  v = pParse->pVdbe;
97361  pWC = pWInfo->pWC;
97362  pLevel = &pWInfo->a[iLevel];
97363  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
97364  iCur = pTabItem->iCursor;
97365  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
97366  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
97367           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
97368
97369  /* Create labels for the "break" and "continue" instructions
97370  ** for the current loop.  Jump to addrBrk to break out of a loop.
97371  ** Jump to cont to go immediately to the next iteration of the
97372  ** loop.
97373  **
97374  ** When there is an IN operator, we also have a "addrNxt" label that
97375  ** means to continue with the next IN value combination.  When
97376  ** there are no IN operators in the constraints, the "addrNxt" label
97377  ** is the same as "addrBrk".
97378  */
97379  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
97380  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
97381
97382  /* If this is the right table of a LEFT OUTER JOIN, allocate and
97383  ** initialize a memory cell that records if this table matches any
97384  ** row of the left table of the join.
97385  */
97386  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
97387    pLevel->iLeftJoin = ++pParse->nMem;
97388    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
97389    VdbeComment((v, "init LEFT JOIN no-match flag"));
97390  }
97391
97392#ifndef SQLITE_OMIT_VIRTUALTABLE
97393  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
97394    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
97395    **          to access the data.
97396    */
97397    int iReg;   /* P3 Value for OP_VFilter */
97398    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
97399    int nConstraint = pVtabIdx->nConstraint;
97400    struct sqlite3_index_constraint_usage *aUsage =
97401                                                pVtabIdx->aConstraintUsage;
97402    const struct sqlite3_index_constraint *aConstraint =
97403                                                pVtabIdx->aConstraint;
97404
97405    sqlite3ExprCachePush(pParse);
97406    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
97407    for(j=1; j<=nConstraint; j++){
97408      for(k=0; k<nConstraint; k++){
97409        if( aUsage[k].argvIndex==j ){
97410          int iTerm = aConstraint[k].iTermOffset;
97411          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
97412          break;
97413        }
97414      }
97415      if( k==nConstraint ) break;
97416    }
97417    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
97418    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
97419    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
97420                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
97421    pVtabIdx->needToFreeIdxStr = 0;
97422    for(j=0; j<nConstraint; j++){
97423      if( aUsage[j].omit ){
97424        int iTerm = aConstraint[j].iTermOffset;
97425        disableTerm(pLevel, &pWC->a[iTerm]);
97426      }
97427    }
97428    pLevel->op = OP_VNext;
97429    pLevel->p1 = iCur;
97430    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
97431    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
97432    sqlite3ExprCachePop(pParse, 1);
97433  }else
97434#endif /* SQLITE_OMIT_VIRTUALTABLE */
97435
97436  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
97437    /* Case 1:  We can directly reference a single row using an
97438    **          equality comparison against the ROWID field.  Or
97439    **          we reference multiple rows using a "rowid IN (...)"
97440    **          construct.
97441    */
97442    iReleaseReg = sqlite3GetTempReg(pParse);
97443    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
97444    assert( pTerm!=0 );
97445    assert( pTerm->pExpr!=0 );
97446    assert( pTerm->leftCursor==iCur );
97447    assert( omitTable==0 );
97448    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97449    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
97450    addrNxt = pLevel->addrNxt;
97451    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
97452    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
97453    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
97454    VdbeComment((v, "pk"));
97455    pLevel->op = OP_Noop;
97456  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
97457    /* Case 2:  We have an inequality comparison against the ROWID field.
97458    */
97459    int testOp = OP_Noop;
97460    int start;
97461    int memEndValue = 0;
97462    WhereTerm *pStart, *pEnd;
97463
97464    assert( omitTable==0 );
97465    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
97466    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
97467    if( bRev ){
97468      pTerm = pStart;
97469      pStart = pEnd;
97470      pEnd = pTerm;
97471    }
97472    if( pStart ){
97473      Expr *pX;             /* The expression that defines the start bound */
97474      int r1, rTemp;        /* Registers for holding the start boundary */
97475
97476      /* The following constant maps TK_xx codes into corresponding
97477      ** seek opcodes.  It depends on a particular ordering of TK_xx
97478      */
97479      const u8 aMoveOp[] = {
97480           /* TK_GT */  OP_SeekGt,
97481           /* TK_LE */  OP_SeekLe,
97482           /* TK_LT */  OP_SeekLt,
97483           /* TK_GE */  OP_SeekGe
97484      };
97485      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
97486      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
97487      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
97488
97489      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97490      pX = pStart->pExpr;
97491      assert( pX!=0 );
97492      assert( pStart->leftCursor==iCur );
97493      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
97494      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
97495      VdbeComment((v, "pk"));
97496      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
97497      sqlite3ReleaseTempReg(pParse, rTemp);
97498      disableTerm(pLevel, pStart);
97499    }else{
97500      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
97501    }
97502    if( pEnd ){
97503      Expr *pX;
97504      pX = pEnd->pExpr;
97505      assert( pX!=0 );
97506      assert( pEnd->leftCursor==iCur );
97507      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97508      memEndValue = ++pParse->nMem;
97509      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
97510      if( pX->op==TK_LT || pX->op==TK_GT ){
97511        testOp = bRev ? OP_Le : OP_Ge;
97512      }else{
97513        testOp = bRev ? OP_Lt : OP_Gt;
97514      }
97515      disableTerm(pLevel, pEnd);
97516    }
97517    start = sqlite3VdbeCurrentAddr(v);
97518    pLevel->op = bRev ? OP_Prev : OP_Next;
97519    pLevel->p1 = iCur;
97520    pLevel->p2 = start;
97521    if( pStart==0 && pEnd==0 ){
97522      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
97523    }else{
97524      assert( pLevel->p5==0 );
97525    }
97526    if( testOp!=OP_Noop ){
97527      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
97528      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
97529      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
97530      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
97531      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
97532    }
97533  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
97534    /* Case 3: A scan using an index.
97535    **
97536    **         The WHERE clause may contain zero or more equality
97537    **         terms ("==" or "IN" operators) that refer to the N
97538    **         left-most columns of the index. It may also contain
97539    **         inequality constraints (>, <, >= or <=) on the indexed
97540    **         column that immediately follows the N equalities. Only
97541    **         the right-most column can be an inequality - the rest must
97542    **         use the "==" and "IN" operators. For example, if the
97543    **         index is on (x,y,z), then the following clauses are all
97544    **         optimized:
97545    **
97546    **            x=5
97547    **            x=5 AND y=10
97548    **            x=5 AND y<10
97549    **            x=5 AND y>5 AND y<10
97550    **            x=5 AND y=5 AND z<=10
97551    **
97552    **         The z<10 term of the following cannot be used, only
97553    **         the x=5 term:
97554    **
97555    **            x=5 AND z<10
97556    **
97557    **         N may be zero if there are inequality constraints.
97558    **         If there are no inequality constraints, then N is at
97559    **         least one.
97560    **
97561    **         This case is also used when there are no WHERE clause
97562    **         constraints but an index is selected anyway, in order
97563    **         to force the output order to conform to an ORDER BY.
97564    */
97565    static const u8 aStartOp[] = {
97566      0,
97567      0,
97568      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
97569      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
97570      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
97571      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
97572      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
97573      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
97574    };
97575    static const u8 aEndOp[] = {
97576      OP_Noop,             /* 0: (!end_constraints) */
97577      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
97578      OP_IdxLT             /* 2: (end_constraints && bRev) */
97579    };
97580    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
97581    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
97582    int regBase;                 /* Base register holding constraint values */
97583    int r1;                      /* Temp register */
97584    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
97585    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
97586    int startEq;                 /* True if range start uses ==, >= or <= */
97587    int endEq;                   /* True if range end uses ==, >= or <= */
97588    int start_constraints;       /* Start of range is constrained */
97589    int nConstraint;             /* Number of constraint terms */
97590    Index *pIdx;                 /* The index we will be using */
97591    int iIdxCur;                 /* The VDBE cursor for the index */
97592    int nExtraReg = 0;           /* Number of extra registers needed */
97593    int op;                      /* Instruction opcode */
97594    char *zStartAff;             /* Affinity for start of range constraint */
97595    char *zEndAff;               /* Affinity for end of range constraint */
97596
97597    pIdx = pLevel->plan.u.pIdx;
97598    iIdxCur = pLevel->iIdxCur;
97599    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
97600
97601    /* If this loop satisfies a sort order (pOrderBy) request that
97602    ** was passed to this function to implement a "SELECT min(x) ..."
97603    ** query, then the caller will only allow the loop to run for
97604    ** a single iteration. This means that the first row returned
97605    ** should not have a NULL value stored in 'x'. If column 'x' is
97606    ** the first one after the nEq equality constraints in the index,
97607    ** this requires some special handling.
97608    */
97609    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
97610     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
97611     && (pIdx->nColumn>nEq)
97612    ){
97613      /* assert( pOrderBy->nExpr==1 ); */
97614      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
97615      isMinQuery = 1;
97616      nExtraReg = 1;
97617    }
97618
97619    /* Find any inequality constraint terms for the start and end
97620    ** of the range.
97621    */
97622    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
97623      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
97624      nExtraReg = 1;
97625    }
97626    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
97627      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
97628      nExtraReg = 1;
97629    }
97630
97631    /* Generate code to evaluate all constraint terms using == or IN
97632    ** and store the values of those terms in an array of registers
97633    ** starting at regBase.
97634    */
97635    regBase = codeAllEqualityTerms(
97636        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
97637    );
97638    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
97639    addrNxt = pLevel->addrNxt;
97640
97641    /* If we are doing a reverse order scan on an ascending index, or
97642    ** a forward order scan on a descending index, interchange the
97643    ** start and end terms (pRangeStart and pRangeEnd).
97644    */
97645    if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
97646      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
97647    }
97648
97649    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
97650    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
97651    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
97652    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
97653    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
97654    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
97655    start_constraints = pRangeStart || nEq>0;
97656
97657    /* Seek the index cursor to the start of the range. */
97658    nConstraint = nEq;
97659    if( pRangeStart ){
97660      Expr *pRight = pRangeStart->pExpr->pRight;
97661      sqlite3ExprCode(pParse, pRight, regBase+nEq);
97662      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
97663      if( zStartAff ){
97664        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
97665          /* Since the comparison is to be performed with no conversions
97666          ** applied to the operands, set the affinity to apply to pRight to
97667          ** SQLITE_AFF_NONE.  */
97668          zStartAff[nEq] = SQLITE_AFF_NONE;
97669        }
97670        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
97671          zStartAff[nEq] = SQLITE_AFF_NONE;
97672        }
97673      }
97674      nConstraint++;
97675      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97676    }else if( isMinQuery ){
97677      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
97678      nConstraint++;
97679      startEq = 0;
97680      start_constraints = 1;
97681    }
97682    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
97683    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
97684    assert( op!=0 );
97685    testcase( op==OP_Rewind );
97686    testcase( op==OP_Last );
97687    testcase( op==OP_SeekGt );
97688    testcase( op==OP_SeekGe );
97689    testcase( op==OP_SeekLe );
97690    testcase( op==OP_SeekLt );
97691    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
97692
97693    /* Load the value for the inequality constraint at the end of the
97694    ** range (if any).
97695    */
97696    nConstraint = nEq;
97697    if( pRangeEnd ){
97698      Expr *pRight = pRangeEnd->pExpr->pRight;
97699      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
97700      sqlite3ExprCode(pParse, pRight, regBase+nEq);
97701      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
97702      if( zEndAff ){
97703        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
97704          /* Since the comparison is to be performed with no conversions
97705          ** applied to the operands, set the affinity to apply to pRight to
97706          ** SQLITE_AFF_NONE.  */
97707          zEndAff[nEq] = SQLITE_AFF_NONE;
97708        }
97709        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
97710          zEndAff[nEq] = SQLITE_AFF_NONE;
97711        }
97712      }
97713      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
97714      nConstraint++;
97715      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
97716    }
97717    sqlite3DbFree(pParse->db, zStartAff);
97718    sqlite3DbFree(pParse->db, zEndAff);
97719
97720    /* Top of the loop body */
97721    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
97722
97723    /* Check if the index cursor is past the end of the range. */
97724    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
97725    testcase( op==OP_Noop );
97726    testcase( op==OP_IdxGE );
97727    testcase( op==OP_IdxLT );
97728    if( op!=OP_Noop ){
97729      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
97730      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
97731    }
97732
97733    /* If there are inequality constraints, check that the value
97734    ** of the table column that the inequality contrains is not NULL.
97735    ** If it is, jump to the next iteration of the loop.
97736    */
97737    r1 = sqlite3GetTempReg(pParse);
97738    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
97739    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
97740    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
97741      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
97742      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
97743    }
97744    sqlite3ReleaseTempReg(pParse, r1);
97745
97746    /* Seek the table cursor, if required */
97747    disableTerm(pLevel, pRangeStart);
97748    disableTerm(pLevel, pRangeEnd);
97749    if( !omitTable ){
97750      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
97751      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
97752      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
97753      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
97754    }
97755
97756    /* Record the instruction used to terminate the loop. Disable
97757    ** WHERE clause terms made redundant by the index range scan.
97758    */
97759    pLevel->op = bRev ? OP_Prev : OP_Next;
97760    pLevel->p1 = iIdxCur;
97761  }else
97762
97763#ifndef SQLITE_OMIT_OR_OPTIMIZATION
97764  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
97765    /* Case 4:  Two or more separately indexed terms connected by OR
97766    **
97767    ** Example:
97768    **
97769    **   CREATE TABLE t1(a,b,c,d);
97770    **   CREATE INDEX i1 ON t1(a);
97771    **   CREATE INDEX i2 ON t1(b);
97772    **   CREATE INDEX i3 ON t1(c);
97773    **
97774    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
97775    **
97776    ** In the example, there are three indexed terms connected by OR.
97777    ** The top of the loop looks like this:
97778    **
97779    **          Null       1                # Zero the rowset in reg 1
97780    **
97781    ** Then, for each indexed term, the following. The arguments to
97782    ** RowSetTest are such that the rowid of the current row is inserted
97783    ** into the RowSet. If it is already present, control skips the
97784    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
97785    **
97786    **        sqlite3WhereBegin(<term>)
97787    **          RowSetTest                  # Insert rowid into rowset
97788    **          Gosub      2 A
97789    **        sqlite3WhereEnd()
97790    **
97791    ** Following the above, code to terminate the loop. Label A, the target
97792    ** of the Gosub above, jumps to the instruction right after the Goto.
97793    **
97794    **          Null       1                # Zero the rowset in reg 1
97795    **          Goto       B                # The loop is finished.
97796    **
97797    **       A: <loop body>                 # Return data, whatever.
97798    **
97799    **          Return     2                # Jump back to the Gosub
97800    **
97801    **       B: <after the loop>
97802    **
97803    */
97804    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
97805    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
97806    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
97807
97808    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
97809    int regRowset = 0;                        /* Register for RowSet object */
97810    int regRowid = 0;                         /* Register holding rowid */
97811    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
97812    int iRetInit;                             /* Address of regReturn init */
97813    int untestedTerms = 0;             /* Some terms not completely tested */
97814    int ii;
97815
97816    pTerm = pLevel->plan.u.pTerm;
97817    assert( pTerm!=0 );
97818    assert( pTerm->eOperator==WO_OR );
97819    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
97820    pOrWc = &pTerm->u.pOrInfo->wc;
97821    pFinal = &pOrWc->a[pOrWc->nTerm-1];
97822    pLevel->op = OP_Return;
97823    pLevel->p1 = regReturn;
97824
97825    /* Set up a new SrcList ni pOrTab containing the table being scanned
97826    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
97827    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
97828    */
97829    if( pWInfo->nLevel>1 ){
97830      int nNotReady;                 /* The number of notReady tables */
97831      struct SrcList_item *origSrc;     /* Original list of tables */
97832      nNotReady = pWInfo->nLevel - iLevel - 1;
97833      pOrTab = sqlite3StackAllocRaw(pParse->db,
97834                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
97835      if( pOrTab==0 ) return notReady;
97836      pOrTab->nAlloc = (i16)(nNotReady + 1);
97837      pOrTab->nSrc = pOrTab->nAlloc;
97838      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
97839      origSrc = pWInfo->pTabList->a;
97840      for(k=1; k<=nNotReady; k++){
97841        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
97842      }
97843    }else{
97844      pOrTab = pWInfo->pTabList;
97845    }
97846
97847    /* Initialize the rowset register to contain NULL. An SQL NULL is
97848    ** equivalent to an empty rowset.
97849    **
97850    ** Also initialize regReturn to contain the address of the instruction
97851    ** immediately following the OP_Return at the bottom of the loop. This
97852    ** is required in a few obscure LEFT JOIN cases where control jumps
97853    ** over the top of the loop into the body of it. In this case the
97854    ** correct response for the end-of-loop code (the OP_Return) is to
97855    ** fall through to the next instruction, just as an OP_Next does if
97856    ** called on an uninitialized cursor.
97857    */
97858    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
97859      regRowset = ++pParse->nMem;
97860      regRowid = ++pParse->nMem;
97861      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
97862    }
97863    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
97864
97865    for(ii=0; ii<pOrWc->nTerm; ii++){
97866      WhereTerm *pOrTerm = &pOrWc->a[ii];
97867      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
97868        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
97869        /* Loop through table entries that match term pOrTerm. */
97870        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
97871                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
97872                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
97873        if( pSubWInfo ){
97874          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
97875            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
97876            int r;
97877            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
97878                                         regRowid);
97879            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
97880                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
97881          }
97882          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
97883
97884          /* The pSubWInfo->untestedTerms flag means that this OR term
97885          ** contained one or more AND term from a notReady table.  The
97886          ** terms from the notReady table could not be tested and will
97887          ** need to be tested later.
97888          */
97889          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
97890
97891          /* Finish the loop through table entries that match term pOrTerm. */
97892          sqlite3WhereEnd(pSubWInfo);
97893        }
97894      }
97895    }
97896    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
97897    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
97898    sqlite3VdbeResolveLabel(v, iLoopBody);
97899
97900    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
97901    if( !untestedTerms ) disableTerm(pLevel, pTerm);
97902  }else
97903#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
97904
97905  {
97906    /* Case 5:  There is no usable index.  We must do a complete
97907    **          scan of the entire table.
97908    */
97909    static const u8 aStep[] = { OP_Next, OP_Prev };
97910    static const u8 aStart[] = { OP_Rewind, OP_Last };
97911    assert( bRev==0 || bRev==1 );
97912    assert( omitTable==0 );
97913    pLevel->op = aStep[bRev];
97914    pLevel->p1 = iCur;
97915    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
97916    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
97917  }
97918  notReady &= ~getMask(pWC->pMaskSet, iCur);
97919
97920  /* Insert code to test every subexpression that can be completely
97921  ** computed using the current set of tables.
97922  **
97923  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
97924  ** the use of indices become tests that are evaluated against each row of
97925  ** the relevant input tables.
97926  */
97927  k = 0;
97928  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
97929    Expr *pE;
97930    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
97931    testcase( pTerm->wtFlags & TERM_CODED );
97932    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97933    if( (pTerm->prereqAll & notReady)!=0 ){
97934      testcase( pWInfo->untestedTerms==0
97935               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
97936      pWInfo->untestedTerms = 1;
97937      continue;
97938    }
97939    pE = pTerm->pExpr;
97940    assert( pE!=0 );
97941    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
97942      continue;
97943    }
97944    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
97945    k = 1;
97946    pTerm->wtFlags |= TERM_CODED;
97947  }
97948
97949  /* For a LEFT OUTER JOIN, generate code that will record the fact that
97950  ** at least one row of the right table has matched the left table.
97951  */
97952  if( pLevel->iLeftJoin ){
97953    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
97954    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
97955    VdbeComment((v, "record LEFT JOIN hit"));
97956    sqlite3ExprCacheClear(pParse);
97957    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
97958      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
97959      testcase( pTerm->wtFlags & TERM_CODED );
97960      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
97961      if( (pTerm->prereqAll & notReady)!=0 ){
97962        assert( pWInfo->untestedTerms );
97963        continue;
97964      }
97965      assert( pTerm->pExpr );
97966      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
97967      pTerm->wtFlags |= TERM_CODED;
97968    }
97969  }
97970  sqlite3ReleaseTempReg(pParse, iReleaseReg);
97971
97972  return notReady;
97973}
97974
97975#if defined(SQLITE_TEST)
97976/*
97977** The following variable holds a text description of query plan generated
97978** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
97979** overwrites the previous.  This information is used for testing and
97980** analysis only.
97981*/
97982SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
97983static int nQPlan = 0;              /* Next free slow in _query_plan[] */
97984
97985#endif /* SQLITE_TEST */
97986
97987
97988/*
97989** Free a WhereInfo structure
97990*/
97991static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
97992  if( ALWAYS(pWInfo) ){
97993    int i;
97994    for(i=0; i<pWInfo->nLevel; i++){
97995      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
97996      if( pInfo ){
97997        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
97998        if( pInfo->needToFreeIdxStr ){
97999          sqlite3_free(pInfo->idxStr);
98000        }
98001        sqlite3DbFree(db, pInfo);
98002      }
98003      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
98004        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
98005        if( pIdx ){
98006          sqlite3DbFree(db, pIdx->zColAff);
98007          sqlite3DbFree(db, pIdx);
98008        }
98009      }
98010    }
98011    whereClauseClear(pWInfo->pWC);
98012    sqlite3DbFree(db, pWInfo);
98013  }
98014}
98015
98016
98017/*
98018** Generate the beginning of the loop used for WHERE clause processing.
98019** The return value is a pointer to an opaque structure that contains
98020** information needed to terminate the loop.  Later, the calling routine
98021** should invoke sqlite3WhereEnd() with the return value of this function
98022** in order to complete the WHERE clause processing.
98023**
98024** If an error occurs, this routine returns NULL.
98025**
98026** The basic idea is to do a nested loop, one loop for each table in
98027** the FROM clause of a select.  (INSERT and UPDATE statements are the
98028** same as a SELECT with only a single table in the FROM clause.)  For
98029** example, if the SQL is this:
98030**
98031**       SELECT * FROM t1, t2, t3 WHERE ...;
98032**
98033** Then the code generated is conceptually like the following:
98034**
98035**      foreach row1 in t1 do       \    Code generated
98036**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
98037**          foreach row3 in t3 do   /
98038**            ...
98039**          end                     \    Code generated
98040**        end                        |-- by sqlite3WhereEnd()
98041**      end                         /
98042**
98043** Note that the loops might not be nested in the order in which they
98044** appear in the FROM clause if a different order is better able to make
98045** use of indices.  Note also that when the IN operator appears in
98046** the WHERE clause, it might result in additional nested loops for
98047** scanning through all values on the right-hand side of the IN.
98048**
98049** There are Btree cursors associated with each table.  t1 uses cursor
98050** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
98051** And so forth.  This routine generates code to open those VDBE cursors
98052** and sqlite3WhereEnd() generates the code to close them.
98053**
98054** The code that sqlite3WhereBegin() generates leaves the cursors named
98055** in pTabList pointing at their appropriate entries.  The [...] code
98056** can use OP_Column and OP_Rowid opcodes on these cursors to extract
98057** data from the various tables of the loop.
98058**
98059** If the WHERE clause is empty, the foreach loops must each scan their
98060** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
98061** the tables have indices and there are terms in the WHERE clause that
98062** refer to those indices, a complete table scan can be avoided and the
98063** code will run much faster.  Most of the work of this routine is checking
98064** to see if there are indices that can be used to speed up the loop.
98065**
98066** Terms of the WHERE clause are also used to limit which rows actually
98067** make it to the "..." in the middle of the loop.  After each "foreach",
98068** terms of the WHERE clause that use only terms in that loop and outer
98069** loops are evaluated and if false a jump is made around all subsequent
98070** inner loops (or around the "..." if the test occurs within the inner-
98071** most loop)
98072**
98073** OUTER JOINS
98074**
98075** An outer join of tables t1 and t2 is conceptally coded as follows:
98076**
98077**    foreach row1 in t1 do
98078**      flag = 0
98079**      foreach row2 in t2 do
98080**        start:
98081**          ...
98082**          flag = 1
98083**      end
98084**      if flag==0 then
98085**        move the row2 cursor to a null row
98086**        goto start
98087**      fi
98088**    end
98089**
98090** ORDER BY CLAUSE PROCESSING
98091**
98092** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
98093** if there is one.  If there is no ORDER BY clause or if this routine
98094** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
98095**
98096** If an index can be used so that the natural output order of the table
98097** scan is correct for the ORDER BY clause, then that index is used and
98098** *ppOrderBy is set to NULL.  This is an optimization that prevents an
98099** unnecessary sort of the result set if an index appropriate for the
98100** ORDER BY clause already exists.
98101**
98102** If the where clause loops cannot be arranged to provide the correct
98103** output order, then the *ppOrderBy is unchanged.
98104*/
98105SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
98106  Parse *pParse,        /* The parser context */
98107  SrcList *pTabList,    /* A list of all tables to be scanned */
98108  Expr *pWhere,         /* The WHERE clause */
98109  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
98110  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
98111){
98112  int i;                     /* Loop counter */
98113  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
98114  int nTabList;              /* Number of elements in pTabList */
98115  WhereInfo *pWInfo;         /* Will become the return value of this function */
98116  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
98117  Bitmask notReady;          /* Cursors that are not yet positioned */
98118  WhereMaskSet *pMaskSet;    /* The expression mask set */
98119  WhereClause *pWC;               /* Decomposition of the WHERE clause */
98120  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
98121  WhereLevel *pLevel;             /* A single level in the pWInfo list */
98122  int iFrom;                      /* First unused FROM clause element */
98123  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
98124  sqlite3 *db;               /* Database connection */
98125
98126  /* The number of tables in the FROM clause is limited by the number of
98127  ** bits in a Bitmask
98128  */
98129  testcase( pTabList->nSrc==BMS );
98130  if( pTabList->nSrc>BMS ){
98131    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
98132    return 0;
98133  }
98134
98135  /* This function normally generates a nested loop for all tables in
98136  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
98137  ** only generate code for the first table in pTabList and assume that
98138  ** any cursors associated with subsequent tables are uninitialized.
98139  */
98140  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
98141
98142  /* Allocate and initialize the WhereInfo structure that will become the
98143  ** return value. A single allocation is used to store the WhereInfo
98144  ** struct, the contents of WhereInfo.a[], the WhereClause structure
98145  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
98146  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
98147  ** some architectures. Hence the ROUND8() below.
98148  */
98149  db = pParse->db;
98150  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
98151  pWInfo = sqlite3DbMallocZero(db,
98152      nByteWInfo +
98153      sizeof(WhereClause) +
98154      sizeof(WhereMaskSet)
98155  );
98156  if( db->mallocFailed ){
98157    sqlite3DbFree(db, pWInfo);
98158    pWInfo = 0;
98159    goto whereBeginError;
98160  }
98161  pWInfo->nLevel = nTabList;
98162  pWInfo->pParse = pParse;
98163  pWInfo->pTabList = pTabList;
98164  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
98165  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
98166  pWInfo->wctrlFlags = wctrlFlags;
98167  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
98168  pMaskSet = (WhereMaskSet*)&pWC[1];
98169
98170  /* Split the WHERE clause into separate subexpressions where each
98171  ** subexpression is separated by an AND operator.
98172  */
98173  initMaskSet(pMaskSet);
98174  whereClauseInit(pWC, pParse, pMaskSet);
98175  sqlite3ExprCodeConstants(pParse, pWhere);
98176  whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
98177
98178  /* Special case: a WHERE clause that is constant.  Evaluate the
98179  ** expression and either jump over all of the code or fall thru.
98180  */
98181  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
98182    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
98183    pWhere = 0;
98184  }
98185
98186  /* Assign a bit from the bitmask to every term in the FROM clause.
98187  **
98188  ** When assigning bitmask values to FROM clause cursors, it must be
98189  ** the case that if X is the bitmask for the N-th FROM clause term then
98190  ** the bitmask for all FROM clause terms to the left of the N-th term
98191  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
98192  ** its Expr.iRightJoinTable value to find the bitmask of the right table
98193  ** of the join.  Subtracting one from the right table bitmask gives a
98194  ** bitmask for all tables to the left of the join.  Knowing the bitmask
98195  ** for all tables to the left of a left join is important.  Ticket #3015.
98196  **
98197  ** Configure the WhereClause.vmask variable so that bits that correspond
98198  ** to virtual table cursors are set. This is used to selectively disable
98199  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
98200  ** with virtual tables.
98201  **
98202  ** Note that bitmasks are created for all pTabList->nSrc tables in
98203  ** pTabList, not just the first nTabList tables.  nTabList is normally
98204  ** equal to pTabList->nSrc but might be shortened to 1 if the
98205  ** WHERE_ONETABLE_ONLY flag is set.
98206  */
98207  assert( pWC->vmask==0 && pMaskSet->n==0 );
98208  for(i=0; i<pTabList->nSrc; i++){
98209    createMask(pMaskSet, pTabList->a[i].iCursor);
98210#ifndef SQLITE_OMIT_VIRTUALTABLE
98211    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
98212      pWC->vmask |= ((Bitmask)1 << i);
98213    }
98214#endif
98215  }
98216#ifndef NDEBUG
98217  {
98218    Bitmask toTheLeft = 0;
98219    for(i=0; i<pTabList->nSrc; i++){
98220      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
98221      assert( (m-1)==toTheLeft );
98222      toTheLeft |= m;
98223    }
98224  }
98225#endif
98226
98227  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
98228  ** add new virtual terms onto the end of the WHERE clause.  We do not
98229  ** want to analyze these virtual terms, so start analyzing at the end
98230  ** and work forward so that the added virtual terms are never processed.
98231  */
98232  exprAnalyzeAll(pTabList, pWC);
98233  if( db->mallocFailed ){
98234    goto whereBeginError;
98235  }
98236
98237  /* Chose the best index to use for each table in the FROM clause.
98238  **
98239  ** This loop fills in the following fields:
98240  **
98241  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
98242  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
98243  **   pWInfo->a[].nEq       The number of == and IN constraints
98244  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
98245  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
98246  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
98247  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
98248  **
98249  ** This loop also figures out the nesting order of tables in the FROM
98250  ** clause.
98251  */
98252  notReady = ~(Bitmask)0;
98253  pTabItem = pTabList->a;
98254  pLevel = pWInfo->a;
98255  andFlags = ~0;
98256  WHERETRACE(("*** Optimizer Start ***\n"));
98257  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
98258    WhereCost bestPlan;         /* Most efficient plan seen so far */
98259    Index *pIdx;                /* Index for FROM table at pTabItem */
98260    int j;                      /* For looping over FROM tables */
98261    int bestJ = -1;             /* The value of j */
98262    Bitmask m;                  /* Bitmask value for j or bestJ */
98263    int isOptimal;              /* Iterator for optimal/non-optimal search */
98264    int nUnconstrained;         /* Number tables without INDEXED BY */
98265    Bitmask notIndexed;         /* Mask of tables that cannot use an index */
98266
98267    memset(&bestPlan, 0, sizeof(bestPlan));
98268    bestPlan.rCost = SQLITE_BIG_DBL;
98269
98270    /* Loop through the remaining entries in the FROM clause to find the
98271    ** next nested loop. The loop tests all FROM clause entries
98272    ** either once or twice.
98273    **
98274    ** The first test is always performed if there are two or more entries
98275    ** remaining and never performed if there is only one FROM clause entry
98276    ** to choose from.  The first test looks for an "optimal" scan.  In
98277    ** this context an optimal scan is one that uses the same strategy
98278    ** for the given FROM clause entry as would be selected if the entry
98279    ** were used as the innermost nested loop.  In other words, a table
98280    ** is chosen such that the cost of running that table cannot be reduced
98281    ** by waiting for other tables to run first.  This "optimal" test works
98282    ** by first assuming that the FROM clause is on the inner loop and finding
98283    ** its query plan, then checking to see if that query plan uses any
98284    ** other FROM clause terms that are notReady.  If no notReady terms are
98285    ** used then the "optimal" query plan works.
98286    **
98287    ** The second loop iteration is only performed if no optimal scan
98288    ** strategies were found by the first loop. This 2nd iteration is used to
98289    ** search for the lowest cost scan overall.
98290    **
98291    ** Previous versions of SQLite performed only the second iteration -
98292    ** the next outermost loop was always that with the lowest overall
98293    ** cost. However, this meant that SQLite could select the wrong plan
98294    ** for scripts such as the following:
98295    **
98296    **   CREATE TABLE t1(a, b);
98297    **   CREATE TABLE t2(c, d);
98298    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
98299    **
98300    ** The best strategy is to iterate through table t1 first. However it
98301    ** is not possible to determine this with a simple greedy algorithm.
98302    ** However, since the cost of a linear scan through table t2 is the same
98303    ** as the cost of a linear scan through table t1, a simple greedy
98304    ** algorithm may choose to use t2 for the outer loop, which is a much
98305    ** costlier approach.
98306    */
98307    nUnconstrained = 0;
98308    notIndexed = 0;
98309    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0; isOptimal--){
98310      Bitmask mask;             /* Mask of tables not yet ready */
98311      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
98312        int doNotReorder;    /* True if this table should not be reordered */
98313        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
98314        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
98315
98316        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
98317        if( j!=iFrom && doNotReorder ) break;
98318        m = getMask(pMaskSet, pTabItem->iCursor);
98319        if( (m & notReady)==0 ){
98320          if( j==iFrom ) iFrom++;
98321          continue;
98322        }
98323        mask = (isOptimal ? m : notReady);
98324        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
98325        if( pTabItem->pIndex==0 ) nUnconstrained++;
98326
98327        assert( pTabItem->pTab );
98328#ifndef SQLITE_OMIT_VIRTUALTABLE
98329        if( IsVirtual(pTabItem->pTab) ){
98330          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
98331          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
98332        }else
98333#endif
98334        {
98335          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
98336        }
98337        assert( isOptimal || (sCost.used&notReady)==0 );
98338
98339        /* If an INDEXED BY clause is present, then the plan must use that
98340        ** index if it uses any index at all */
98341        assert( pTabItem->pIndex==0
98342                  || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
98343                  || sCost.plan.u.pIdx==pTabItem->pIndex );
98344
98345        if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
98346          notIndexed |= m;
98347        }
98348
98349        /* Conditions under which this table becomes the best so far:
98350        **
98351        **   (1) The table must not depend on other tables that have not
98352        **       yet run.
98353        **
98354        **   (2) A full-table-scan plan cannot supercede another plan unless
98355        **       it is an "optimal" plan as defined above.
98356        **
98357        **   (3) All tables have an INDEXED BY clause or this table lacks an
98358        **       INDEXED BY clause or this table uses the specific
98359        **       index specified by its INDEXED BY clause.  This rule ensures
98360        **       that a best-so-far is always selected even if an impossible
98361        **       combination of INDEXED BY clauses are given.  The error
98362        **       will be detected and relayed back to the application later.
98363        **       The NEVER() comes about because rule (2) above prevents
98364        **       An indexable full-table-scan from reaching rule (3).
98365        **
98366        **   (4) The plan cost must be lower than prior plans or else the
98367        **       cost must be the same and the number of rows must be lower.
98368        */
98369        if( (sCost.used&notReady)==0                       /* (1) */
98370            && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
98371                || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
98372            && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
98373                || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
98374            && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
98375                || (sCost.rCost<=bestPlan.rCost && sCost.nRow<bestPlan.nRow))
98376        ){
98377          WHERETRACE(("... best so far with cost=%g and nRow=%g\n",
98378                      sCost.rCost, sCost.nRow));
98379          bestPlan = sCost;
98380          bestJ = j;
98381        }
98382        if( doNotReorder ) break;
98383      }
98384    }
98385    assert( bestJ>=0 );
98386    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
98387    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
98388           pLevel-pWInfo->a));
98389    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
98390      *ppOrderBy = 0;
98391    }
98392    andFlags &= bestPlan.plan.wsFlags;
98393    pLevel->plan = bestPlan.plan;
98394    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
98395    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
98396    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
98397      pLevel->iIdxCur = pParse->nTab++;
98398    }else{
98399      pLevel->iIdxCur = -1;
98400    }
98401    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
98402    pLevel->iFrom = (u8)bestJ;
98403    if( bestPlan.nRow>=(double)1 ) pParse->nQueryLoop *= bestPlan.nRow;
98404
98405    /* Check that if the table scanned by this loop iteration had an
98406    ** INDEXED BY clause attached to it, that the named index is being
98407    ** used for the scan. If not, then query compilation has failed.
98408    ** Return an error.
98409    */
98410    pIdx = pTabList->a[bestJ].pIndex;
98411    if( pIdx ){
98412      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
98413        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
98414        goto whereBeginError;
98415      }else{
98416        /* If an INDEXED BY clause is used, the bestIndex() function is
98417        ** guaranteed to find the index specified in the INDEXED BY clause
98418        ** if it find an index at all. */
98419        assert( bestPlan.plan.u.pIdx==pIdx );
98420      }
98421    }
98422  }
98423  WHERETRACE(("*** Optimizer Finished ***\n"));
98424  if( pParse->nErr || db->mallocFailed ){
98425    goto whereBeginError;
98426  }
98427
98428  /* If the total query only selects a single row, then the ORDER BY
98429  ** clause is irrelevant.
98430  */
98431  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
98432    *ppOrderBy = 0;
98433  }
98434
98435  /* If the caller is an UPDATE or DELETE statement that is requesting
98436  ** to use a one-pass algorithm, determine if this is appropriate.
98437  ** The one-pass algorithm only works if the WHERE clause constraints
98438  ** the statement to update a single row.
98439  */
98440  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
98441  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
98442    pWInfo->okOnePass = 1;
98443    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
98444  }
98445
98446  /* Open all tables in the pTabList and any indices selected for
98447  ** searching those tables.
98448  */
98449  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
98450  notReady = ~(Bitmask)0;
98451  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
98452    Table *pTab;     /* Table to open */
98453    int iDb;         /* Index of database containing table/index */
98454
98455#ifndef SQLITE_OMIT_EXPLAIN
98456    if( pParse->explain==2 ){
98457      char *zMsg;
98458      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
98459      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
98460      if( pItem->zAlias ){
98461        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
98462      }
98463      if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
98464        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH AUTOMATIC INDEX", zMsg);
98465      }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
98466        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
98467           zMsg, pLevel->plan.u.pIdx->zName);
98468      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
98469        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
98470      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
98471        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
98472      }
98473#ifndef SQLITE_OMIT_VIRTUALTABLE
98474      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
98475        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
98476        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
98477                    pVtabIdx->idxNum, pVtabIdx->idxStr);
98478      }
98479#endif
98480      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
98481        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
98482      }
98483      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
98484    }
98485#endif /* SQLITE_OMIT_EXPLAIN */
98486    pTabItem = &pTabList->a[pLevel->iFrom];
98487    pTab = pTabItem->pTab;
98488    pLevel->iTabCur = pTabItem->iCursor;
98489    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98490    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
98491      /* Do nothing */
98492    }else
98493#ifndef SQLITE_OMIT_VIRTUALTABLE
98494    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
98495      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
98496      int iCur = pTabItem->iCursor;
98497      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
98498    }else
98499#endif
98500    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
98501         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
98502      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
98503      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
98504      testcase( pTab->nCol==BMS-1 );
98505      testcase( pTab->nCol==BMS );
98506      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
98507        Bitmask b = pTabItem->colUsed;
98508        int n = 0;
98509        for(; b; b=b>>1, n++){}
98510        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
98511                            SQLITE_INT_TO_PTR(n), P4_INT32);
98512        assert( n<=pTab->nCol );
98513      }
98514    }else{
98515      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98516    }
98517#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
98518    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
98519      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
98520    }else
98521#endif
98522    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
98523      Index *pIx = pLevel->plan.u.pIdx;
98524      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
98525      int iIdxCur = pLevel->iIdxCur;
98526      assert( pIx->pSchema==pTab->pSchema );
98527      assert( iIdxCur>=0 );
98528      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
98529                        (char*)pKey, P4_KEYINFO_HANDOFF);
98530      VdbeComment((v, "%s", pIx->zName));
98531    }
98532    sqlite3CodeVerifySchema(pParse, iDb);
98533    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
98534  }
98535  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
98536  if( db->mallocFailed ) goto whereBeginError;
98537
98538  /* Generate the code to do the search.  Each iteration of the for
98539  ** loop below generates code for a single nested loop of the VM
98540  ** program.
98541  */
98542  notReady = ~(Bitmask)0;
98543  for(i=0; i<nTabList; i++){
98544    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
98545    pWInfo->iContinue = pWInfo->a[i].addrCont;
98546  }
98547
98548#ifdef SQLITE_TEST  /* For testing and debugging use only */
98549  /* Record in the query plan information about the current table
98550  ** and the index used to access it (if any).  If the table itself
98551  ** is not used, its name is just '{}'.  If no index is used
98552  ** the index is listed as "{}".  If the primary key is used the
98553  ** index name is '*'.
98554  */
98555  for(i=0; i<nTabList; i++){
98556    char *z;
98557    int n;
98558    pLevel = &pWInfo->a[i];
98559    pTabItem = &pTabList->a[pLevel->iFrom];
98560    z = pTabItem->zAlias;
98561    if( z==0 ) z = pTabItem->pTab->zName;
98562    n = sqlite3Strlen30(z);
98563    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
98564      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
98565        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
98566        nQPlan += 2;
98567      }else{
98568        memcpy(&sqlite3_query_plan[nQPlan], z, n);
98569        nQPlan += n;
98570      }
98571      sqlite3_query_plan[nQPlan++] = ' ';
98572    }
98573    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
98574    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
98575    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
98576      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
98577      nQPlan += 2;
98578    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
98579      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
98580      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
98581        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
98582        nQPlan += n;
98583        sqlite3_query_plan[nQPlan++] = ' ';
98584      }
98585    }else{
98586      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
98587      nQPlan += 3;
98588    }
98589  }
98590  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
98591    sqlite3_query_plan[--nQPlan] = 0;
98592  }
98593  sqlite3_query_plan[nQPlan] = 0;
98594  nQPlan = 0;
98595#endif /* SQLITE_TEST // Testing and debugging use only */
98596
98597  /* Record the continuation address in the WhereInfo structure.  Then
98598  ** clean up and return.
98599  */
98600  return pWInfo;
98601
98602  /* Jump here if malloc fails */
98603whereBeginError:
98604  if( pWInfo ){
98605    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
98606    whereInfoFree(db, pWInfo);
98607  }
98608  return 0;
98609}
98610
98611/*
98612** Generate the end of the WHERE loop.  See comments on
98613** sqlite3WhereBegin() for additional information.
98614*/
98615SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
98616  Parse *pParse = pWInfo->pParse;
98617  Vdbe *v = pParse->pVdbe;
98618  int i;
98619  WhereLevel *pLevel;
98620  SrcList *pTabList = pWInfo->pTabList;
98621  sqlite3 *db = pParse->db;
98622
98623  /* Generate loop termination code.
98624  */
98625  sqlite3ExprCacheClear(pParse);
98626  for(i=pWInfo->nLevel-1; i>=0; i--){
98627    pLevel = &pWInfo->a[i];
98628    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
98629    if( pLevel->op!=OP_Noop ){
98630      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
98631      sqlite3VdbeChangeP5(v, pLevel->p5);
98632    }
98633    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
98634      struct InLoop *pIn;
98635      int j;
98636      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
98637      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
98638        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
98639        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
98640        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
98641      }
98642      sqlite3DbFree(db, pLevel->u.in.aInLoop);
98643    }
98644    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
98645    if( pLevel->iLeftJoin ){
98646      int addr;
98647      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
98648      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
98649           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
98650      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
98651        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
98652      }
98653      if( pLevel->iIdxCur>=0 ){
98654        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
98655      }
98656      if( pLevel->op==OP_Return ){
98657        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
98658      }else{
98659        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
98660      }
98661      sqlite3VdbeJumpHere(v, addr);
98662    }
98663  }
98664
98665  /* The "break" point is here, just past the end of the outer loop.
98666  ** Set it.
98667  */
98668  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
98669
98670  /* Close all of the cursors that were opened by sqlite3WhereBegin.
98671  */
98672  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
98673  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
98674    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
98675    Table *pTab = pTabItem->pTab;
98676    assert( pTab!=0 );
98677    if( (pTab->tabFlags & TF_Ephemeral)==0
98678     && pTab->pSelect==0
98679     && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
98680    ){
98681      int ws = pLevel->plan.wsFlags;
98682      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
98683        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
98684      }
98685      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
98686        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
98687      }
98688    }
98689
98690    /* If this scan uses an index, make code substitutions to read data
98691    ** from the index in preference to the table. Sometimes, this means
98692    ** the table need never be read from. This is a performance boost,
98693    ** as the vdbe level waits until the table is read before actually
98694    ** seeking the table cursor to the record corresponding to the current
98695    ** position in the index.
98696    **
98697    ** Calls to the code generator in between sqlite3WhereBegin and
98698    ** sqlite3WhereEnd will have created code that references the table
98699    ** directly.  This loop scans all that code looking for opcodes
98700    ** that reference the table and converts them into opcodes that
98701    ** reference the index.
98702    */
98703    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
98704      int k, j, last;
98705      VdbeOp *pOp;
98706      Index *pIdx = pLevel->plan.u.pIdx;
98707
98708      assert( pIdx!=0 );
98709      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
98710      last = sqlite3VdbeCurrentAddr(v);
98711      for(k=pWInfo->iTop; k<last; k++, pOp++){
98712        if( pOp->p1!=pLevel->iTabCur ) continue;
98713        if( pOp->opcode==OP_Column ){
98714          for(j=0; j<pIdx->nColumn; j++){
98715            if( pOp->p2==pIdx->aiColumn[j] ){
98716              pOp->p2 = j;
98717              pOp->p1 = pLevel->iIdxCur;
98718              break;
98719            }
98720          }
98721          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
98722               || j<pIdx->nColumn );
98723        }else if( pOp->opcode==OP_Rowid ){
98724          pOp->p1 = pLevel->iIdxCur;
98725          pOp->opcode = OP_IdxRowid;
98726        }
98727      }
98728    }
98729  }
98730
98731  /* Final cleanup
98732  */
98733  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
98734  whereInfoFree(db, pWInfo);
98735  return;
98736}
98737
98738/************** End of where.c ***********************************************/
98739/************** Begin file parse.c *******************************************/
98740/* Driver template for the LEMON parser generator.
98741** The author disclaims copyright to this source code.
98742**
98743** This version of "lempar.c" is modified, slightly, for use by SQLite.
98744** The only modifications are the addition of a couple of NEVER()
98745** macros to disable tests that are needed in the case of a general
98746** LALR(1) grammar but which are always false in the
98747** specific grammar used by SQLite.
98748*/
98749/* First off, code is included that follows the "include" declaration
98750** in the input grammar file. */
98751
98752
98753/*
98754** Disable all error recovery processing in the parser push-down
98755** automaton.
98756*/
98757#define YYNOERRORRECOVERY 1
98758
98759/*
98760** Make yytestcase() the same as testcase()
98761*/
98762#define yytestcase(X) testcase(X)
98763
98764/*
98765** An instance of this structure holds information about the
98766** LIMIT clause of a SELECT statement.
98767*/
98768struct LimitVal {
98769  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
98770  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
98771};
98772
98773/*
98774** An instance of this structure is used to store the LIKE,
98775** GLOB, NOT LIKE, and NOT GLOB operators.
98776*/
98777struct LikeOp {
98778  Token eOperator;  /* "like" or "glob" or "regexp" */
98779  int not;         /* True if the NOT keyword is present */
98780};
98781
98782/*
98783** An instance of the following structure describes the event of a
98784** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
98785** TK_DELETE, or TK_INSTEAD.  If the event is of the form
98786**
98787**      UPDATE ON (a,b,c)
98788**
98789** Then the "b" IdList records the list "a,b,c".
98790*/
98791struct TrigEvent { int a; IdList * b; };
98792
98793/*
98794** An instance of this structure holds the ATTACH key and the key type.
98795*/
98796struct AttachKey { int type;  Token key; };
98797
98798
98799  /* This is a utility routine used to set the ExprSpan.zStart and
98800  ** ExprSpan.zEnd values of pOut so that the span covers the complete
98801  ** range of text beginning with pStart and going to the end of pEnd.
98802  */
98803  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
98804    pOut->zStart = pStart->z;
98805    pOut->zEnd = &pEnd->z[pEnd->n];
98806  }
98807
98808  /* Construct a new Expr object from a single identifier.  Use the
98809  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
98810  ** that created the expression.
98811  */
98812  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
98813    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
98814    pOut->zStart = pValue->z;
98815    pOut->zEnd = &pValue->z[pValue->n];
98816  }
98817
98818  /* This routine constructs a binary expression node out of two ExprSpan
98819  ** objects and uses the result to populate a new ExprSpan object.
98820  */
98821  static void spanBinaryExpr(
98822    ExprSpan *pOut,     /* Write the result here */
98823    Parse *pParse,      /* The parsing context.  Errors accumulate here */
98824    int op,             /* The binary operation */
98825    ExprSpan *pLeft,    /* The left operand */
98826    ExprSpan *pRight    /* The right operand */
98827  ){
98828    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
98829    pOut->zStart = pLeft->zStart;
98830    pOut->zEnd = pRight->zEnd;
98831  }
98832
98833  /* Construct an expression node for a unary postfix operator
98834  */
98835  static void spanUnaryPostfix(
98836    ExprSpan *pOut,        /* Write the new expression node here */
98837    Parse *pParse,         /* Parsing context to record errors */
98838    int op,                /* The operator */
98839    ExprSpan *pOperand,    /* The operand */
98840    Token *pPostOp         /* The operand token for setting the span */
98841  ){
98842    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
98843    pOut->zStart = pOperand->zStart;
98844    pOut->zEnd = &pPostOp->z[pPostOp->n];
98845  }
98846
98847  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
98848  ** unary TK_ISNULL or TK_NOTNULL expression. */
98849  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
98850    sqlite3 *db = pParse->db;
98851    if( db->mallocFailed==0 && pY->op==TK_NULL ){
98852      pA->op = (u8)op;
98853      sqlite3ExprDelete(db, pA->pRight);
98854      pA->pRight = 0;
98855    }
98856  }
98857
98858  /* Construct an expression node for a unary prefix operator
98859  */
98860  static void spanUnaryPrefix(
98861    ExprSpan *pOut,        /* Write the new expression node here */
98862    Parse *pParse,         /* Parsing context to record errors */
98863    int op,                /* The operator */
98864    ExprSpan *pOperand,    /* The operand */
98865    Token *pPreOp         /* The operand token for setting the span */
98866  ){
98867    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
98868    pOut->zStart = pPreOp->z;
98869    pOut->zEnd = pOperand->zEnd;
98870  }
98871/* Next is all token values, in a form suitable for use by makeheaders.
98872** This section will be null unless lemon is run with the -m switch.
98873*/
98874/*
98875** These constants (all generated automatically by the parser generator)
98876** specify the various kinds of tokens (terminals) that the parser
98877** understands.
98878**
98879** Each symbol here is a terminal symbol in the grammar.
98880*/
98881/* Make sure the INTERFACE macro is defined.
98882*/
98883#ifndef INTERFACE
98884# define INTERFACE 1
98885#endif
98886/* The next thing included is series of defines which control
98887** various aspects of the generated parser.
98888**    YYCODETYPE         is the data type used for storing terminal
98889**                       and nonterminal numbers.  "unsigned char" is
98890**                       used if there are fewer than 250 terminals
98891**                       and nonterminals.  "int" is used otherwise.
98892**    YYNOCODE           is a number of type YYCODETYPE which corresponds
98893**                       to no legal terminal or nonterminal number.  This
98894**                       number is used to fill in empty slots of the hash
98895**                       table.
98896**    YYFALLBACK         If defined, this indicates that one or more tokens
98897**                       have fall-back values which should be used if the
98898**                       original value of the token will not parse.
98899**    YYACTIONTYPE       is the data type used for storing terminal
98900**                       and nonterminal numbers.  "unsigned char" is
98901**                       used if there are fewer than 250 rules and
98902**                       states combined.  "int" is used otherwise.
98903**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
98904**                       directly to the parser from the tokenizer.
98905**    YYMINORTYPE        is the data type used for all minor tokens.
98906**                       This is typically a union of many types, one of
98907**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
98908**                       for base tokens is called "yy0".
98909**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
98910**                       zero the stack is dynamically sized using realloc()
98911**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
98912**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
98913**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
98914**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
98915**    YYNSTATE           the combined number of states.
98916**    YYNRULE            the number of rules in the grammar
98917**    YYERRORSYMBOL      is the code number of the error symbol.  If not
98918**                       defined, then do no error processing.
98919*/
98920#define YYCODETYPE unsigned char
98921#define YYNOCODE 253
98922#define YYACTIONTYPE unsigned short int
98923#define YYWILDCARD 67
98924#define sqlite3ParserTOKENTYPE Token
98925typedef union {
98926  int yyinit;
98927  sqlite3ParserTOKENTYPE yy0;
98928  int yy4;
98929  struct TrigEvent yy90;
98930  ExprSpan yy118;
98931  TriggerStep* yy203;
98932  u8 yy210;
98933  struct {int value; int mask;} yy215;
98934  SrcList* yy259;
98935  struct LimitVal yy292;
98936  Expr* yy314;
98937  ExprList* yy322;
98938  struct LikeOp yy342;
98939  IdList* yy384;
98940  Select* yy387;
98941} YYMINORTYPE;
98942#ifndef YYSTACKDEPTH
98943#define YYSTACKDEPTH 100
98944#endif
98945#define sqlite3ParserARG_SDECL Parse *pParse;
98946#define sqlite3ParserARG_PDECL ,Parse *pParse
98947#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
98948#define sqlite3ParserARG_STORE yypParser->pParse = pParse
98949#define YYNSTATE 630
98950#define YYNRULE 329
98951#define YYFALLBACK 1
98952#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
98953#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
98954#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
98955
98956/* The yyzerominor constant is used to initialize instances of
98957** YYMINORTYPE objects to zero. */
98958static const YYMINORTYPE yyzerominor = { 0 };
98959
98960/* Define the yytestcase() macro to be a no-op if is not already defined
98961** otherwise.
98962**
98963** Applications can choose to define yytestcase() in the %include section
98964** to a macro that can assist in verifying code coverage.  For production
98965** code the yytestcase() macro should be turned off.  But it is useful
98966** for testing.
98967*/
98968#ifndef yytestcase
98969# define yytestcase(X)
98970#endif
98971
98972
98973/* Next are the tables used to determine what action to take based on the
98974** current state and lookahead token.  These tables are used to implement
98975** functions that take a state number and lookahead value and return an
98976** action integer.
98977**
98978** Suppose the action integer is N.  Then the action is determined as
98979** follows
98980**
98981**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
98982**                                      token onto the stack and goto state N.
98983**
98984**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
98985**
98986**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
98987**
98988**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
98989**
98990**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
98991**                                      slots in the yy_action[] table.
98992**
98993** The action table is constructed as a single large table named yy_action[].
98994** Given state S and lookahead X, the action is computed as
98995**
98996**      yy_action[ yy_shift_ofst[S] + X ]
98997**
98998** If the index value yy_shift_ofst[S]+X is out of range or if the value
98999** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
99000** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
99001** and that yy_default[S] should be used instead.
99002**
99003** The formula above is for computing the action when the lookahead is
99004** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
99005** a reduce action) then the yy_reduce_ofst[] array is used in place of
99006** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
99007** YY_SHIFT_USE_DFLT.
99008**
99009** The following are the tables generated in this section:
99010**
99011**  yy_action[]        A single table containing all actions.
99012**  yy_lookahead[]     A table containing the lookahead for each entry in
99013**                     yy_action.  Used to detect hash collisions.
99014**  yy_shift_ofst[]    For each state, the offset into yy_action for
99015**                     shifting terminals.
99016**  yy_reduce_ofst[]   For each state, the offset into yy_action for
99017**                     shifting non-terminals after a reduce.
99018**  yy_default[]       Default action for each state.
99019*/
99020#define YY_ACTTAB_COUNT (1557)
99021static const YYACTIONTYPE yy_action[] = {
99022 /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
99023 /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
99024 /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
99025 /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
99026 /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
99027 /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
99028 /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
99029 /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
99030 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99031 /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
99032 /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
99033 /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
99034 /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
99035 /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
99036 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
99037 /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
99038 /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
99039 /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
99040 /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
99041 /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
99042 /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
99043 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99044 /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
99045 /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
99046 /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
99047 /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
99048 /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
99049 /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
99050 /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
99051 /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
99052 /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
99053 /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
99054 /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
99055 /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
99056 /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
99057 /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
99058 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99059 /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
99060 /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
99061 /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
99062 /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
99063 /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
99064 /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
99065 /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
99066 /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
99067 /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
99068 /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
99069 /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
99070 /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
99071 /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
99072 /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
99073 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
99074 /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
99075 /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
99076 /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
99077 /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
99078 /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
99079 /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
99080 /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99081 /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
99082 /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
99083 /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
99084 /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
99085 /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
99086 /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
99087 /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
99088 /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
99089 /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
99090 /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
99091 /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
99092 /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
99093 /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
99094 /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
99095 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99096 /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
99097 /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
99098 /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
99099 /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
99100 /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
99101 /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
99102 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
99103 /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
99104 /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
99105 /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
99106 /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
99107 /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
99108 /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
99109 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
99110 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
99111 /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
99112 /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
99113 /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
99114 /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
99115 /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
99116 /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
99117 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
99118 /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
99119 /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
99120 /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
99121 /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
99122 /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
99123 /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
99124 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
99125 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
99126 /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
99127 /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
99128 /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
99129 /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
99130 /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
99131 /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
99132 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
99133 /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
99134 /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
99135 /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
99136 /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
99137 /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
99138 /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
99139 /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
99140 /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
99141 /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
99142 /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
99143 /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
99144 /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
99145 /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
99146 /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
99147 /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
99148 /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
99149 /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
99150 /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
99151 /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
99152 /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
99153 /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
99154 /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
99155 /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
99156 /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
99157 /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
99158 /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
99159 /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
99160 /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
99161 /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
99162 /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
99163 /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
99164 /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
99165 /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
99166 /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
99167 /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
99168 /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
99169 /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
99170 /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
99171 /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
99172 /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
99173 /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
99174 /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
99175 /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
99176 /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
99177 /*  1550 */   961,  961,  961,  961,  961,  961,  370,
99178};
99179static const YYCODETYPE yy_lookahead[] = {
99180 /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
99181 /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
99182 /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
99183 /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
99184 /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
99185 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99186 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
99187 /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
99188 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99189 /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
99190 /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
99191 /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
99192 /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
99193 /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
99194 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
99195 /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
99196 /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
99197 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
99198 /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
99199 /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
99200 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99201 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99202 /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
99203 /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
99204 /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
99205 /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
99206 /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
99207 /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
99208 /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
99209 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
99210 /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
99211 /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
99212 /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
99213 /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
99214 /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
99215 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
99216 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99217 /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
99218 /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
99219 /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
99220 /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
99221 /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
99222 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99223 /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
99224 /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
99225 /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
99226 /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
99227 /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
99228 /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
99229 /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
99230 /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
99231 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
99232 /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
99233 /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
99234 /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
99235 /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
99236 /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
99237 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99238 /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99239 /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
99240 /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
99241 /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
99242 /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
99243 /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
99244 /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
99245 /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
99246 /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
99247 /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
99248 /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
99249 /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
99250 /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
99251 /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
99252 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
99253 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99254 /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
99255 /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
99256 /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
99257 /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
99258 /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
99259 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
99260 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
99261 /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
99262 /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
99263 /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
99264 /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
99265 /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
99266 /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
99267 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
99268 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
99269 /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
99270 /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
99271 /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
99272 /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
99273 /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
99274 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
99275 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
99276 /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
99277 /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
99278 /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
99279 /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
99280 /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
99281 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
99282 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
99283 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
99284 /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
99285 /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
99286 /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
99287 /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
99288 /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
99289 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
99290 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
99291 /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
99292 /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
99293 /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
99294 /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
99295 /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
99296 /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
99297 /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
99298 /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
99299 /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
99300 /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
99301 /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
99302 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
99303 /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
99304 /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
99305 /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
99306 /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
99307 /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
99308 /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
99309 /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
99310 /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
99311 /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
99312 /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
99313 /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
99314 /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
99315 /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
99316 /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
99317 /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
99318 /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
99319 /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
99320 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
99321 /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
99322 /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
99323 /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
99324 /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
99325 /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
99326 /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
99327 /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
99328 /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
99329 /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
99330 /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
99331 /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
99332 /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
99333 /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
99334 /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
99335 /*  1550 */   252,  252,  252,  252,  252,  252,  236,
99336};
99337#define YY_SHIFT_USE_DFLT (-74)
99338#define YY_SHIFT_COUNT (418)
99339#define YY_SHIFT_MIN   (-73)
99340#define YY_SHIFT_MAX   (1468)
99341static const short yy_shift_ofst[] = {
99342 /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
99343 /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
99344 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99345 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99346 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
99347 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
99348 /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
99349 /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
99350 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
99351 /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
99352 /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
99353 /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99354 /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
99355 /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
99356 /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
99357 /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99358 /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99359 /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
99360 /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
99361 /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
99362 /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
99363 /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
99364 /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
99365 /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
99366 /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
99367 /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
99368 /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
99369 /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
99370 /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
99371 /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
99372 /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
99373 /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
99374 /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
99375 /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
99376 /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
99377 /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
99378 /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
99379 /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
99380 /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
99381 /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
99382 /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
99383 /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
99384};
99385#define YY_REDUCE_USE_DFLT (-142)
99386#define YY_REDUCE_COUNT (312)
99387#define YY_REDUCE_MIN   (-141)
99388#define YY_REDUCE_MAX   (1369)
99389static const short yy_reduce_ofst[] = {
99390 /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
99391 /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
99392 /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
99393 /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
99394 /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
99395 /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
99396 /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
99397 /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
99398 /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
99399 /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
99400 /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
99401 /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
99402 /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
99403 /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
99404 /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
99405 /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
99406 /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
99407 /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
99408 /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
99409 /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
99410 /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
99411 /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
99412 /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
99413 /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
99414 /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
99415 /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
99416 /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
99417 /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
99418 /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
99419 /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
99420 /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
99421 /*   310 */  1031, 1023, 1030,
99422};
99423static const YYACTIONTYPE yy_default[] = {
99424 /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
99425 /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
99426 /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99427 /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99428 /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99429 /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99430 /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
99431 /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
99432 /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
99433 /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
99434 /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
99435 /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99436 /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
99437 /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
99438 /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99439 /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
99440 /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99441 /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99442 /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
99443 /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
99444 /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
99445 /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
99446 /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
99447 /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
99448 /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
99449 /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
99450 /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
99451 /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
99452 /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
99453 /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
99454 /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
99455 /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
99456 /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99457 /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
99458 /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99459 /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
99460 /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
99461 /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99462 /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
99463 /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
99464 /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
99465 /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
99466 /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
99467 /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
99468 /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
99469 /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
99470 /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
99471 /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
99472 /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
99473 /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
99474 /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
99475 /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
99476 /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
99477 /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
99478 /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
99479 /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
99480 /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
99481 /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
99482 /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
99483 /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
99484 /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
99485 /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
99486 /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
99487};
99488
99489/* The next table maps tokens into fallback tokens.  If a construct
99490** like the following:
99491**
99492**      %fallback ID X Y Z.
99493**
99494** appears in the grammar, then ID becomes a fallback token for X, Y,
99495** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
99496** but it does not parse, the type of the token is changed to ID and
99497** the parse is retried before an error is thrown.
99498*/
99499#ifdef YYFALLBACK
99500static const YYCODETYPE yyFallback[] = {
99501    0,  /*          $ => nothing */
99502    0,  /*       SEMI => nothing */
99503   26,  /*    EXPLAIN => ID */
99504   26,  /*      QUERY => ID */
99505   26,  /*       PLAN => ID */
99506   26,  /*      BEGIN => ID */
99507    0,  /* TRANSACTION => nothing */
99508   26,  /*   DEFERRED => ID */
99509   26,  /*  IMMEDIATE => ID */
99510   26,  /*  EXCLUSIVE => ID */
99511    0,  /*     COMMIT => nothing */
99512   26,  /*        END => ID */
99513   26,  /*   ROLLBACK => ID */
99514   26,  /*  SAVEPOINT => ID */
99515   26,  /*    RELEASE => ID */
99516    0,  /*         TO => nothing */
99517    0,  /*      TABLE => nothing */
99518    0,  /*     CREATE => nothing */
99519   26,  /*         IF => ID */
99520    0,  /*        NOT => nothing */
99521    0,  /*     EXISTS => nothing */
99522   26,  /*       TEMP => ID */
99523    0,  /*         LP => nothing */
99524    0,  /*         RP => nothing */
99525    0,  /*         AS => nothing */
99526    0,  /*      COMMA => nothing */
99527    0,  /*         ID => nothing */
99528    0,  /*    INDEXED => nothing */
99529   26,  /*      ABORT => ID */
99530   26,  /*     ACTION => ID */
99531   26,  /*      AFTER => ID */
99532   26,  /*    ANALYZE => ID */
99533   26,  /*        ASC => ID */
99534   26,  /*     ATTACH => ID */
99535   26,  /*     BEFORE => ID */
99536   26,  /*         BY => ID */
99537   26,  /*    CASCADE => ID */
99538   26,  /*       CAST => ID */
99539   26,  /*   COLUMNKW => ID */
99540   26,  /*   CONFLICT => ID */
99541   26,  /*   DATABASE => ID */
99542   26,  /*       DESC => ID */
99543   26,  /*     DETACH => ID */
99544   26,  /*       EACH => ID */
99545   26,  /*       FAIL => ID */
99546   26,  /*        FOR => ID */
99547   26,  /*     IGNORE => ID */
99548   26,  /*  INITIALLY => ID */
99549   26,  /*    INSTEAD => ID */
99550   26,  /*    LIKE_KW => ID */
99551   26,  /*      MATCH => ID */
99552   26,  /*         NO => ID */
99553   26,  /*        KEY => ID */
99554   26,  /*         OF => ID */
99555   26,  /*     OFFSET => ID */
99556   26,  /*     PRAGMA => ID */
99557   26,  /*      RAISE => ID */
99558   26,  /*    REPLACE => ID */
99559   26,  /*   RESTRICT => ID */
99560   26,  /*        ROW => ID */
99561   26,  /*    TRIGGER => ID */
99562   26,  /*     VACUUM => ID */
99563   26,  /*       VIEW => ID */
99564   26,  /*    VIRTUAL => ID */
99565   26,  /*    REINDEX => ID */
99566   26,  /*     RENAME => ID */
99567   26,  /*   CTIME_KW => ID */
99568};
99569#endif /* YYFALLBACK */
99570
99571/* The following structure represents a single element of the
99572** parser's stack.  Information stored includes:
99573**
99574**   +  The state number for the parser at this level of the stack.
99575**
99576**   +  The value of the token stored at this level of the stack.
99577**      (In other words, the "major" token.)
99578**
99579**   +  The semantic value stored at this level of the stack.  This is
99580**      the information used by the action routines in the grammar.
99581**      It is sometimes called the "minor" token.
99582*/
99583struct yyStackEntry {
99584  YYACTIONTYPE stateno;  /* The state-number */
99585  YYCODETYPE major;      /* The major token value.  This is the code
99586                         ** number for the token at this stack level */
99587  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
99588                         ** is the value of the token  */
99589};
99590typedef struct yyStackEntry yyStackEntry;
99591
99592/* The state of the parser is completely contained in an instance of
99593** the following structure */
99594struct yyParser {
99595  int yyidx;                    /* Index of top element in stack */
99596#ifdef YYTRACKMAXSTACKDEPTH
99597  int yyidxMax;                 /* Maximum value of yyidx */
99598#endif
99599  int yyerrcnt;                 /* Shifts left before out of the error */
99600  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
99601#if YYSTACKDEPTH<=0
99602  int yystksz;                  /* Current side of the stack */
99603  yyStackEntry *yystack;        /* The parser's stack */
99604#else
99605  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
99606#endif
99607};
99608typedef struct yyParser yyParser;
99609
99610#ifndef NDEBUG
99611static FILE *yyTraceFILE = 0;
99612static char *yyTracePrompt = 0;
99613#endif /* NDEBUG */
99614
99615#ifndef NDEBUG
99616/*
99617** Turn parser tracing on by giving a stream to which to write the trace
99618** and a prompt to preface each trace message.  Tracing is turned off
99619** by making either argument NULL
99620**
99621** Inputs:
99622** <ul>
99623** <li> A FILE* to which trace output should be written.
99624**      If NULL, then tracing is turned off.
99625** <li> A prefix string written at the beginning of every
99626**      line of trace output.  If NULL, then tracing is
99627**      turned off.
99628** </ul>
99629**
99630** Outputs:
99631** None.
99632*/
99633SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
99634  yyTraceFILE = TraceFILE;
99635  yyTracePrompt = zTracePrompt;
99636  if( yyTraceFILE==0 ) yyTracePrompt = 0;
99637  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
99638}
99639#endif /* NDEBUG */
99640
99641#ifndef NDEBUG
99642/* For tracing shifts, the names of all terminals and nonterminals
99643** are required.  The following table supplies these names */
99644static const char *const yyTokenName[] = {
99645  "$",             "SEMI",          "EXPLAIN",       "QUERY",
99646  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
99647  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
99648  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
99649  "TABLE",         "CREATE",        "IF",            "NOT",
99650  "EXISTS",        "TEMP",          "LP",            "RP",
99651  "AS",            "COMMA",         "ID",            "INDEXED",
99652  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
99653  "ASC",           "ATTACH",        "BEFORE",        "BY",
99654  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
99655  "DATABASE",      "DESC",          "DETACH",        "EACH",
99656  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
99657  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
99658  "KEY",           "OF",            "OFFSET",        "PRAGMA",
99659  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
99660  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
99661  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
99662  "OR",            "AND",           "IS",            "BETWEEN",
99663  "IN",            "ISNULL",        "NOTNULL",       "NE",
99664  "EQ",            "GT",            "LE",            "LT",
99665  "GE",            "ESCAPE",        "BITAND",        "BITOR",
99666  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
99667  "STAR",          "SLASH",         "REM",           "CONCAT",
99668  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
99669  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
99670  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
99671  "ON",            "INSERT",        "DELETE",        "UPDATE",
99672  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
99673  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
99674  "SELECT",        "DISTINCT",      "DOT",           "FROM",
99675  "JOIN",          "USING",         "ORDER",         "GROUP",
99676  "HAVING",        "LIMIT",         "WHERE",         "INTO",
99677  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
99678  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
99679  "THEN",          "ELSE",          "INDEX",         "ALTER",
99680  "ADD",           "error",         "input",         "cmdlist",
99681  "ecmd",          "explain",       "cmdx",          "cmd",
99682  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
99683  "create_table",  "create_table_args",  "createkw",      "temp",
99684  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
99685  "select",        "column",        "columnid",      "type",
99686  "carglist",      "id",            "ids",           "typetoken",
99687  "typename",      "signed",        "plus_num",      "minus_num",
99688  "carg",          "ccons",         "term",          "expr",
99689  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
99690  "refargs",       "defer_subclause",  "refarg",        "refact",
99691  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
99692  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
99693  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
99694  "distinct",      "selcollist",    "from",          "where_opt",
99695  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
99696  "sclp",          "as",            "seltablist",    "stl_prefix",
99697  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
99698  "joinop2",       "inscollist",    "sortlist",      "sortitem",
99699  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
99700  "itemlist",      "exprlist",      "likeop",        "between_op",
99701  "in_op",         "case_operand",  "case_exprlist",  "case_else",
99702  "uniqueflag",    "collate",       "nmnum",         "plus_opt",
99703  "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
99704  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
99705  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
99706  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
99707  "vtabarg",       "vtabargtoken",  "lp",            "anylist",
99708};
99709#endif /* NDEBUG */
99710
99711#ifndef NDEBUG
99712/* For tracing reduce actions, the names of all rules are required.
99713*/
99714static const char *const yyRuleName[] = {
99715 /*   0 */ "input ::= cmdlist",
99716 /*   1 */ "cmdlist ::= cmdlist ecmd",
99717 /*   2 */ "cmdlist ::= ecmd",
99718 /*   3 */ "ecmd ::= SEMI",
99719 /*   4 */ "ecmd ::= explain cmdx SEMI",
99720 /*   5 */ "explain ::=",
99721 /*   6 */ "explain ::= EXPLAIN",
99722 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
99723 /*   8 */ "cmdx ::= cmd",
99724 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
99725 /*  10 */ "trans_opt ::=",
99726 /*  11 */ "trans_opt ::= TRANSACTION",
99727 /*  12 */ "trans_opt ::= TRANSACTION nm",
99728 /*  13 */ "transtype ::=",
99729 /*  14 */ "transtype ::= DEFERRED",
99730 /*  15 */ "transtype ::= IMMEDIATE",
99731 /*  16 */ "transtype ::= EXCLUSIVE",
99732 /*  17 */ "cmd ::= COMMIT trans_opt",
99733 /*  18 */ "cmd ::= END trans_opt",
99734 /*  19 */ "cmd ::= ROLLBACK trans_opt",
99735 /*  20 */ "savepoint_opt ::= SAVEPOINT",
99736 /*  21 */ "savepoint_opt ::=",
99737 /*  22 */ "cmd ::= SAVEPOINT nm",
99738 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
99739 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
99740 /*  25 */ "cmd ::= create_table create_table_args",
99741 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
99742 /*  27 */ "createkw ::= CREATE",
99743 /*  28 */ "ifnotexists ::=",
99744 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
99745 /*  30 */ "temp ::= TEMP",
99746 /*  31 */ "temp ::=",
99747 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
99748 /*  33 */ "create_table_args ::= AS select",
99749 /*  34 */ "columnlist ::= columnlist COMMA column",
99750 /*  35 */ "columnlist ::= column",
99751 /*  36 */ "column ::= columnid type carglist",
99752 /*  37 */ "columnid ::= nm",
99753 /*  38 */ "id ::= ID",
99754 /*  39 */ "id ::= INDEXED",
99755 /*  40 */ "ids ::= ID|STRING",
99756 /*  41 */ "nm ::= id",
99757 /*  42 */ "nm ::= STRING",
99758 /*  43 */ "nm ::= JOIN_KW",
99759 /*  44 */ "type ::=",
99760 /*  45 */ "type ::= typetoken",
99761 /*  46 */ "typetoken ::= typename",
99762 /*  47 */ "typetoken ::= typename LP signed RP",
99763 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
99764 /*  49 */ "typename ::= ids",
99765 /*  50 */ "typename ::= typename ids",
99766 /*  51 */ "signed ::= plus_num",
99767 /*  52 */ "signed ::= minus_num",
99768 /*  53 */ "carglist ::= carglist carg",
99769 /*  54 */ "carglist ::=",
99770 /*  55 */ "carg ::= CONSTRAINT nm ccons",
99771 /*  56 */ "carg ::= ccons",
99772 /*  57 */ "ccons ::= DEFAULT term",
99773 /*  58 */ "ccons ::= DEFAULT LP expr RP",
99774 /*  59 */ "ccons ::= DEFAULT PLUS term",
99775 /*  60 */ "ccons ::= DEFAULT MINUS term",
99776 /*  61 */ "ccons ::= DEFAULT id",
99777 /*  62 */ "ccons ::= NULL onconf",
99778 /*  63 */ "ccons ::= NOT NULL onconf",
99779 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
99780 /*  65 */ "ccons ::= UNIQUE onconf",
99781 /*  66 */ "ccons ::= CHECK LP expr RP",
99782 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
99783 /*  68 */ "ccons ::= defer_subclause",
99784 /*  69 */ "ccons ::= COLLATE ids",
99785 /*  70 */ "autoinc ::=",
99786 /*  71 */ "autoinc ::= AUTOINCR",
99787 /*  72 */ "refargs ::=",
99788 /*  73 */ "refargs ::= refargs refarg",
99789 /*  74 */ "refarg ::= MATCH nm",
99790 /*  75 */ "refarg ::= ON INSERT refact",
99791 /*  76 */ "refarg ::= ON DELETE refact",
99792 /*  77 */ "refarg ::= ON UPDATE refact",
99793 /*  78 */ "refact ::= SET NULL",
99794 /*  79 */ "refact ::= SET DEFAULT",
99795 /*  80 */ "refact ::= CASCADE",
99796 /*  81 */ "refact ::= RESTRICT",
99797 /*  82 */ "refact ::= NO ACTION",
99798 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
99799 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
99800 /*  85 */ "init_deferred_pred_opt ::=",
99801 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
99802 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
99803 /*  88 */ "conslist_opt ::=",
99804 /*  89 */ "conslist_opt ::= COMMA conslist",
99805 /*  90 */ "conslist ::= conslist COMMA tcons",
99806 /*  91 */ "conslist ::= conslist tcons",
99807 /*  92 */ "conslist ::= tcons",
99808 /*  93 */ "tcons ::= CONSTRAINT nm",
99809 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
99810 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
99811 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
99812 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
99813 /*  98 */ "defer_subclause_opt ::=",
99814 /*  99 */ "defer_subclause_opt ::= defer_subclause",
99815 /* 100 */ "onconf ::=",
99816 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
99817 /* 102 */ "orconf ::=",
99818 /* 103 */ "orconf ::= OR resolvetype",
99819 /* 104 */ "resolvetype ::= raisetype",
99820 /* 105 */ "resolvetype ::= IGNORE",
99821 /* 106 */ "resolvetype ::= REPLACE",
99822 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
99823 /* 108 */ "ifexists ::= IF EXISTS",
99824 /* 109 */ "ifexists ::=",
99825 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
99826 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
99827 /* 112 */ "cmd ::= select",
99828 /* 113 */ "select ::= oneselect",
99829 /* 114 */ "select ::= select multiselect_op oneselect",
99830 /* 115 */ "multiselect_op ::= UNION",
99831 /* 116 */ "multiselect_op ::= UNION ALL",
99832 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
99833 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
99834 /* 119 */ "distinct ::= DISTINCT",
99835 /* 120 */ "distinct ::= ALL",
99836 /* 121 */ "distinct ::=",
99837 /* 122 */ "sclp ::= selcollist COMMA",
99838 /* 123 */ "sclp ::=",
99839 /* 124 */ "selcollist ::= sclp expr as",
99840 /* 125 */ "selcollist ::= sclp STAR",
99841 /* 126 */ "selcollist ::= sclp nm DOT STAR",
99842 /* 127 */ "as ::= AS nm",
99843 /* 128 */ "as ::= ids",
99844 /* 129 */ "as ::=",
99845 /* 130 */ "from ::=",
99846 /* 131 */ "from ::= FROM seltablist",
99847 /* 132 */ "stl_prefix ::= seltablist joinop",
99848 /* 133 */ "stl_prefix ::=",
99849 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
99850 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
99851 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
99852 /* 137 */ "dbnm ::=",
99853 /* 138 */ "dbnm ::= DOT nm",
99854 /* 139 */ "fullname ::= nm dbnm",
99855 /* 140 */ "joinop ::= COMMA|JOIN",
99856 /* 141 */ "joinop ::= JOIN_KW JOIN",
99857 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
99858 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
99859 /* 144 */ "on_opt ::= ON expr",
99860 /* 145 */ "on_opt ::=",
99861 /* 146 */ "indexed_opt ::=",
99862 /* 147 */ "indexed_opt ::= INDEXED BY nm",
99863 /* 148 */ "indexed_opt ::= NOT INDEXED",
99864 /* 149 */ "using_opt ::= USING LP inscollist RP",
99865 /* 150 */ "using_opt ::=",
99866 /* 151 */ "orderby_opt ::=",
99867 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
99868 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
99869 /* 154 */ "sortlist ::= sortitem sortorder",
99870 /* 155 */ "sortitem ::= expr",
99871 /* 156 */ "sortorder ::= ASC",
99872 /* 157 */ "sortorder ::= DESC",
99873 /* 158 */ "sortorder ::=",
99874 /* 159 */ "groupby_opt ::=",
99875 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
99876 /* 161 */ "having_opt ::=",
99877 /* 162 */ "having_opt ::= HAVING expr",
99878 /* 163 */ "limit_opt ::=",
99879 /* 164 */ "limit_opt ::= LIMIT expr",
99880 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
99881 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
99882 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
99883 /* 168 */ "where_opt ::=",
99884 /* 169 */ "where_opt ::= WHERE expr",
99885 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
99886 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
99887 /* 172 */ "setlist ::= nm EQ expr",
99888 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
99889 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
99890 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
99891 /* 176 */ "insert_cmd ::= INSERT orconf",
99892 /* 177 */ "insert_cmd ::= REPLACE",
99893 /* 178 */ "itemlist ::= itemlist COMMA expr",
99894 /* 179 */ "itemlist ::= expr",
99895 /* 180 */ "inscollist_opt ::=",
99896 /* 181 */ "inscollist_opt ::= LP inscollist RP",
99897 /* 182 */ "inscollist ::= inscollist COMMA nm",
99898 /* 183 */ "inscollist ::= nm",
99899 /* 184 */ "expr ::= term",
99900 /* 185 */ "expr ::= LP expr RP",
99901 /* 186 */ "term ::= NULL",
99902 /* 187 */ "expr ::= id",
99903 /* 188 */ "expr ::= JOIN_KW",
99904 /* 189 */ "expr ::= nm DOT nm",
99905 /* 190 */ "expr ::= nm DOT nm DOT nm",
99906 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
99907 /* 192 */ "term ::= STRING",
99908 /* 193 */ "expr ::= REGISTER",
99909 /* 194 */ "expr ::= VARIABLE",
99910 /* 195 */ "expr ::= expr COLLATE ids",
99911 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
99912 /* 197 */ "expr ::= ID LP distinct exprlist RP",
99913 /* 198 */ "expr ::= ID LP STAR RP",
99914 /* 199 */ "term ::= CTIME_KW",
99915 /* 200 */ "expr ::= expr AND expr",
99916 /* 201 */ "expr ::= expr OR expr",
99917 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
99918 /* 203 */ "expr ::= expr EQ|NE expr",
99919 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
99920 /* 205 */ "expr ::= expr PLUS|MINUS expr",
99921 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
99922 /* 207 */ "expr ::= expr CONCAT expr",
99923 /* 208 */ "likeop ::= LIKE_KW",
99924 /* 209 */ "likeop ::= NOT LIKE_KW",
99925 /* 210 */ "likeop ::= MATCH",
99926 /* 211 */ "likeop ::= NOT MATCH",
99927 /* 212 */ "expr ::= expr likeop expr",
99928 /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
99929 /* 214 */ "expr ::= expr ISNULL|NOTNULL",
99930 /* 215 */ "expr ::= expr NOT NULL",
99931 /* 216 */ "expr ::= expr IS expr",
99932 /* 217 */ "expr ::= expr IS NOT expr",
99933 /* 218 */ "expr ::= NOT expr",
99934 /* 219 */ "expr ::= BITNOT expr",
99935 /* 220 */ "expr ::= MINUS expr",
99936 /* 221 */ "expr ::= PLUS expr",
99937 /* 222 */ "between_op ::= BETWEEN",
99938 /* 223 */ "between_op ::= NOT BETWEEN",
99939 /* 224 */ "expr ::= expr between_op expr AND expr",
99940 /* 225 */ "in_op ::= IN",
99941 /* 226 */ "in_op ::= NOT IN",
99942 /* 227 */ "expr ::= expr in_op LP exprlist RP",
99943 /* 228 */ "expr ::= LP select RP",
99944 /* 229 */ "expr ::= expr in_op LP select RP",
99945 /* 230 */ "expr ::= expr in_op nm dbnm",
99946 /* 231 */ "expr ::= EXISTS LP select RP",
99947 /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
99948 /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
99949 /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
99950 /* 235 */ "case_else ::= ELSE expr",
99951 /* 236 */ "case_else ::=",
99952 /* 237 */ "case_operand ::= expr",
99953 /* 238 */ "case_operand ::=",
99954 /* 239 */ "exprlist ::= nexprlist",
99955 /* 240 */ "exprlist ::=",
99956 /* 241 */ "nexprlist ::= nexprlist COMMA expr",
99957 /* 242 */ "nexprlist ::= expr",
99958 /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
99959 /* 244 */ "uniqueflag ::= UNIQUE",
99960 /* 245 */ "uniqueflag ::=",
99961 /* 246 */ "idxlist_opt ::=",
99962 /* 247 */ "idxlist_opt ::= LP idxlist RP",
99963 /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
99964 /* 249 */ "idxlist ::= nm collate sortorder",
99965 /* 250 */ "collate ::=",
99966 /* 251 */ "collate ::= COLLATE ids",
99967 /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
99968 /* 253 */ "cmd ::= VACUUM",
99969 /* 254 */ "cmd ::= VACUUM nm",
99970 /* 255 */ "cmd ::= PRAGMA nm dbnm",
99971 /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
99972 /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
99973 /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
99974 /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
99975 /* 260 */ "nmnum ::= plus_num",
99976 /* 261 */ "nmnum ::= nm",
99977 /* 262 */ "nmnum ::= ON",
99978 /* 263 */ "nmnum ::= DELETE",
99979 /* 264 */ "nmnum ::= DEFAULT",
99980 /* 265 */ "plus_num ::= plus_opt number",
99981 /* 266 */ "minus_num ::= MINUS number",
99982 /* 267 */ "number ::= INTEGER|FLOAT",
99983 /* 268 */ "plus_opt ::= PLUS",
99984 /* 269 */ "plus_opt ::=",
99985 /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
99986 /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
99987 /* 272 */ "trigger_time ::= BEFORE",
99988 /* 273 */ "trigger_time ::= AFTER",
99989 /* 274 */ "trigger_time ::= INSTEAD OF",
99990 /* 275 */ "trigger_time ::=",
99991 /* 276 */ "trigger_event ::= DELETE|INSERT",
99992 /* 277 */ "trigger_event ::= UPDATE",
99993 /* 278 */ "trigger_event ::= UPDATE OF inscollist",
99994 /* 279 */ "foreach_clause ::=",
99995 /* 280 */ "foreach_clause ::= FOR EACH ROW",
99996 /* 281 */ "when_clause ::=",
99997 /* 282 */ "when_clause ::= WHEN expr",
99998 /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
99999 /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
100000 /* 285 */ "trnm ::= nm",
100001 /* 286 */ "trnm ::= nm DOT nm",
100002 /* 287 */ "tridxby ::=",
100003 /* 288 */ "tridxby ::= INDEXED BY nm",
100004 /* 289 */ "tridxby ::= NOT INDEXED",
100005 /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
100006 /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
100007 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
100008 /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
100009 /* 294 */ "trigger_cmd ::= select",
100010 /* 295 */ "expr ::= RAISE LP IGNORE RP",
100011 /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
100012 /* 297 */ "raisetype ::= ROLLBACK",
100013 /* 298 */ "raisetype ::= ABORT",
100014 /* 299 */ "raisetype ::= FAIL",
100015 /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
100016 /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
100017 /* 302 */ "cmd ::= DETACH database_kw_opt expr",
100018 /* 303 */ "key_opt ::=",
100019 /* 304 */ "key_opt ::= KEY expr",
100020 /* 305 */ "database_kw_opt ::= DATABASE",
100021 /* 306 */ "database_kw_opt ::=",
100022 /* 307 */ "cmd ::= REINDEX",
100023 /* 308 */ "cmd ::= REINDEX nm dbnm",
100024 /* 309 */ "cmd ::= ANALYZE",
100025 /* 310 */ "cmd ::= ANALYZE nm dbnm",
100026 /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
100027 /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
100028 /* 313 */ "add_column_fullname ::= fullname",
100029 /* 314 */ "kwcolumn_opt ::=",
100030 /* 315 */ "kwcolumn_opt ::= COLUMNKW",
100031 /* 316 */ "cmd ::= create_vtab",
100032 /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
100033 /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
100034 /* 319 */ "vtabarglist ::= vtabarg",
100035 /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
100036 /* 321 */ "vtabarg ::=",
100037 /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
100038 /* 323 */ "vtabargtoken ::= ANY",
100039 /* 324 */ "vtabargtoken ::= lp anylist RP",
100040 /* 325 */ "lp ::= LP",
100041 /* 326 */ "anylist ::=",
100042 /* 327 */ "anylist ::= anylist LP anylist RP",
100043 /* 328 */ "anylist ::= anylist ANY",
100044};
100045#endif /* NDEBUG */
100046
100047
100048#if YYSTACKDEPTH<=0
100049/*
100050** Try to increase the size of the parser stack.
100051*/
100052static void yyGrowStack(yyParser *p){
100053  int newSize;
100054  yyStackEntry *pNew;
100055
100056  newSize = p->yystksz*2 + 100;
100057  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
100058  if( pNew ){
100059    p->yystack = pNew;
100060    p->yystksz = newSize;
100061#ifndef NDEBUG
100062    if( yyTraceFILE ){
100063      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
100064              yyTracePrompt, p->yystksz);
100065    }
100066#endif
100067  }
100068}
100069#endif
100070
100071/*
100072** This function allocates a new parser.
100073** The only argument is a pointer to a function which works like
100074** malloc.
100075**
100076** Inputs:
100077** A pointer to the function used to allocate memory.
100078**
100079** Outputs:
100080** A pointer to a parser.  This pointer is used in subsequent calls
100081** to sqlite3Parser and sqlite3ParserFree.
100082*/
100083SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
100084  yyParser *pParser;
100085  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
100086  if( pParser ){
100087    pParser->yyidx = -1;
100088#ifdef YYTRACKMAXSTACKDEPTH
100089    pParser->yyidxMax = 0;
100090#endif
100091#if YYSTACKDEPTH<=0
100092    pParser->yystack = NULL;
100093    pParser->yystksz = 0;
100094    yyGrowStack(pParser);
100095#endif
100096  }
100097  return pParser;
100098}
100099
100100/* The following function deletes the value associated with a
100101** symbol.  The symbol can be either a terminal or nonterminal.
100102** "yymajor" is the symbol code, and "yypminor" is a pointer to
100103** the value.
100104*/
100105static void yy_destructor(
100106  yyParser *yypParser,    /* The parser */
100107  YYCODETYPE yymajor,     /* Type code for object to destroy */
100108  YYMINORTYPE *yypminor   /* The object to be destroyed */
100109){
100110  sqlite3ParserARG_FETCH;
100111  switch( yymajor ){
100112    /* Here is inserted the actions which take place when a
100113    ** terminal or non-terminal is destroyed.  This can happen
100114    ** when the symbol is popped from the stack during a
100115    ** reduce or during error processing or when a parser is
100116    ** being destroyed before it is finished parsing.
100117    **
100118    ** Note: during a reduce, the only symbols destroyed are those
100119    ** which appear on the RHS of the rule, but which are not used
100120    ** inside the C code.
100121    */
100122    case 160: /* select */
100123    case 194: /* oneselect */
100124{
100125sqlite3SelectDelete(pParse->db, (yypminor->yy387));
100126}
100127      break;
100128    case 174: /* term */
100129    case 175: /* expr */
100130{
100131sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
100132}
100133      break;
100134    case 179: /* idxlist_opt */
100135    case 187: /* idxlist */
100136    case 197: /* selcollist */
100137    case 200: /* groupby_opt */
100138    case 202: /* orderby_opt */
100139    case 204: /* sclp */
100140    case 214: /* sortlist */
100141    case 216: /* nexprlist */
100142    case 217: /* setlist */
100143    case 220: /* itemlist */
100144    case 221: /* exprlist */
100145    case 226: /* case_exprlist */
100146{
100147sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
100148}
100149      break;
100150    case 193: /* fullname */
100151    case 198: /* from */
100152    case 206: /* seltablist */
100153    case 207: /* stl_prefix */
100154{
100155sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
100156}
100157      break;
100158    case 199: /* where_opt */
100159    case 201: /* having_opt */
100160    case 210: /* on_opt */
100161    case 215: /* sortitem */
100162    case 225: /* case_operand */
100163    case 227: /* case_else */
100164    case 238: /* when_clause */
100165    case 243: /* key_opt */
100166{
100167sqlite3ExprDelete(pParse->db, (yypminor->yy314));
100168}
100169      break;
100170    case 211: /* using_opt */
100171    case 213: /* inscollist */
100172    case 219: /* inscollist_opt */
100173{
100174sqlite3IdListDelete(pParse->db, (yypminor->yy384));
100175}
100176      break;
100177    case 234: /* trigger_cmd_list */
100178    case 239: /* trigger_cmd */
100179{
100180sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
100181}
100182      break;
100183    case 236: /* trigger_event */
100184{
100185sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
100186}
100187      break;
100188    default:  break;   /* If no destructor action specified: do nothing */
100189  }
100190}
100191
100192/*
100193** Pop the parser's stack once.
100194**
100195** If there is a destructor routine associated with the token which
100196** is popped from the stack, then call it.
100197**
100198** Return the major token number for the symbol popped.
100199*/
100200static int yy_pop_parser_stack(yyParser *pParser){
100201  YYCODETYPE yymajor;
100202  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
100203
100204  /* There is no mechanism by which the parser stack can be popped below
100205  ** empty in SQLite.  */
100206  if( NEVER(pParser->yyidx<0) ) return 0;
100207#ifndef NDEBUG
100208  if( yyTraceFILE && pParser->yyidx>=0 ){
100209    fprintf(yyTraceFILE,"%sPopping %s\n",
100210      yyTracePrompt,
100211      yyTokenName[yytos->major]);
100212  }
100213#endif
100214  yymajor = yytos->major;
100215  yy_destructor(pParser, yymajor, &yytos->minor);
100216  pParser->yyidx--;
100217  return yymajor;
100218}
100219
100220/*
100221** Deallocate and destroy a parser.  Destructors are all called for
100222** all stack elements before shutting the parser down.
100223**
100224** Inputs:
100225** <ul>
100226** <li>  A pointer to the parser.  This should be a pointer
100227**       obtained from sqlite3ParserAlloc.
100228** <li>  A pointer to a function used to reclaim memory obtained
100229**       from malloc.
100230** </ul>
100231*/
100232SQLITE_PRIVATE void sqlite3ParserFree(
100233  void *p,                    /* The parser to be deleted */
100234  void (*freeProc)(void*)     /* Function used to reclaim memory */
100235){
100236  yyParser *pParser = (yyParser*)p;
100237  /* In SQLite, we never try to destroy a parser that was not successfully
100238  ** created in the first place. */
100239  if( NEVER(pParser==0) ) return;
100240  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
100241#if YYSTACKDEPTH<=0
100242  free(pParser->yystack);
100243#endif
100244  (*freeProc)((void*)pParser);
100245}
100246
100247/*
100248** Return the peak depth of the stack for a parser.
100249*/
100250#ifdef YYTRACKMAXSTACKDEPTH
100251SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
100252  yyParser *pParser = (yyParser*)p;
100253  return pParser->yyidxMax;
100254}
100255#endif
100256
100257/*
100258** Find the appropriate action for a parser given the terminal
100259** look-ahead token iLookAhead.
100260**
100261** If the look-ahead token is YYNOCODE, then check to see if the action is
100262** independent of the look-ahead.  If it is, return the action, otherwise
100263** return YY_NO_ACTION.
100264*/
100265static int yy_find_shift_action(
100266  yyParser *pParser,        /* The parser */
100267  YYCODETYPE iLookAhead     /* The look-ahead token */
100268){
100269  int i;
100270  int stateno = pParser->yystack[pParser->yyidx].stateno;
100271
100272  if( stateno>YY_SHIFT_COUNT
100273   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
100274    return yy_default[stateno];
100275  }
100276  assert( iLookAhead!=YYNOCODE );
100277  i += iLookAhead;
100278  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
100279    if( iLookAhead>0 ){
100280#ifdef YYFALLBACK
100281      YYCODETYPE iFallback;            /* Fallback token */
100282      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
100283             && (iFallback = yyFallback[iLookAhead])!=0 ){
100284#ifndef NDEBUG
100285        if( yyTraceFILE ){
100286          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
100287             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
100288        }
100289#endif
100290        return yy_find_shift_action(pParser, iFallback);
100291      }
100292#endif
100293#ifdef YYWILDCARD
100294      {
100295        int j = i - iLookAhead + YYWILDCARD;
100296        if(
100297#if YY_SHIFT_MIN+YYWILDCARD<0
100298          j>=0 &&
100299#endif
100300#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
100301          j<YY_ACTTAB_COUNT &&
100302#endif
100303          yy_lookahead[j]==YYWILDCARD
100304        ){
100305#ifndef NDEBUG
100306          if( yyTraceFILE ){
100307            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
100308               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
100309          }
100310#endif /* NDEBUG */
100311          return yy_action[j];
100312        }
100313      }
100314#endif /* YYWILDCARD */
100315    }
100316    return yy_default[stateno];
100317  }else{
100318    return yy_action[i];
100319  }
100320}
100321
100322/*
100323** Find the appropriate action for a parser given the non-terminal
100324** look-ahead token iLookAhead.
100325**
100326** If the look-ahead token is YYNOCODE, then check to see if the action is
100327** independent of the look-ahead.  If it is, return the action, otherwise
100328** return YY_NO_ACTION.
100329*/
100330static int yy_find_reduce_action(
100331  int stateno,              /* Current state number */
100332  YYCODETYPE iLookAhead     /* The look-ahead token */
100333){
100334  int i;
100335#ifdef YYERRORSYMBOL
100336  if( stateno>YY_REDUCE_COUNT ){
100337    return yy_default[stateno];
100338  }
100339#else
100340  assert( stateno<=YY_REDUCE_COUNT );
100341#endif
100342  i = yy_reduce_ofst[stateno];
100343  assert( i!=YY_REDUCE_USE_DFLT );
100344  assert( iLookAhead!=YYNOCODE );
100345  i += iLookAhead;
100346#ifdef YYERRORSYMBOL
100347  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
100348    return yy_default[stateno];
100349  }
100350#else
100351  assert( i>=0 && i<YY_ACTTAB_COUNT );
100352  assert( yy_lookahead[i]==iLookAhead );
100353#endif
100354  return yy_action[i];
100355}
100356
100357/*
100358** The following routine is called if the stack overflows.
100359*/
100360static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
100361   sqlite3ParserARG_FETCH;
100362   yypParser->yyidx--;
100363#ifndef NDEBUG
100364   if( yyTraceFILE ){
100365     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
100366   }
100367#endif
100368   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
100369   /* Here code is inserted which will execute if the parser
100370   ** stack every overflows */
100371
100372  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
100373  sqlite3ErrorMsg(pParse, "parser stack overflow");
100374  pParse->parseError = 1;
100375   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
100376}
100377
100378/*
100379** Perform a shift action.
100380*/
100381static void yy_shift(
100382  yyParser *yypParser,          /* The parser to be shifted */
100383  int yyNewState,               /* The new state to shift in */
100384  int yyMajor,                  /* The major token to shift in */
100385  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
100386){
100387  yyStackEntry *yytos;
100388  yypParser->yyidx++;
100389#ifdef YYTRACKMAXSTACKDEPTH
100390  if( yypParser->yyidx>yypParser->yyidxMax ){
100391    yypParser->yyidxMax = yypParser->yyidx;
100392  }
100393#endif
100394#if YYSTACKDEPTH>0
100395  if( yypParser->yyidx>=YYSTACKDEPTH ){
100396    yyStackOverflow(yypParser, yypMinor);
100397    return;
100398  }
100399#else
100400  if( yypParser->yyidx>=yypParser->yystksz ){
100401    yyGrowStack(yypParser);
100402    if( yypParser->yyidx>=yypParser->yystksz ){
100403      yyStackOverflow(yypParser, yypMinor);
100404      return;
100405    }
100406  }
100407#endif
100408  yytos = &yypParser->yystack[yypParser->yyidx];
100409  yytos->stateno = (YYACTIONTYPE)yyNewState;
100410  yytos->major = (YYCODETYPE)yyMajor;
100411  yytos->minor = *yypMinor;
100412#ifndef NDEBUG
100413  if( yyTraceFILE && yypParser->yyidx>0 ){
100414    int i;
100415    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
100416    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
100417    for(i=1; i<=yypParser->yyidx; i++)
100418      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
100419    fprintf(yyTraceFILE,"\n");
100420  }
100421#endif
100422}
100423
100424/* The following table contains information about every rule that
100425** is used during the reduce.
100426*/
100427static const struct {
100428  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
100429  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
100430} yyRuleInfo[] = {
100431  { 142, 1 },
100432  { 143, 2 },
100433  { 143, 1 },
100434  { 144, 1 },
100435  { 144, 3 },
100436  { 145, 0 },
100437  { 145, 1 },
100438  { 145, 3 },
100439  { 146, 1 },
100440  { 147, 3 },
100441  { 149, 0 },
100442  { 149, 1 },
100443  { 149, 2 },
100444  { 148, 0 },
100445  { 148, 1 },
100446  { 148, 1 },
100447  { 148, 1 },
100448  { 147, 2 },
100449  { 147, 2 },
100450  { 147, 2 },
100451  { 151, 1 },
100452  { 151, 0 },
100453  { 147, 2 },
100454  { 147, 3 },
100455  { 147, 5 },
100456  { 147, 2 },
100457  { 152, 6 },
100458  { 154, 1 },
100459  { 156, 0 },
100460  { 156, 3 },
100461  { 155, 1 },
100462  { 155, 0 },
100463  { 153, 4 },
100464  { 153, 2 },
100465  { 158, 3 },
100466  { 158, 1 },
100467  { 161, 3 },
100468  { 162, 1 },
100469  { 165, 1 },
100470  { 165, 1 },
100471  { 166, 1 },
100472  { 150, 1 },
100473  { 150, 1 },
100474  { 150, 1 },
100475  { 163, 0 },
100476  { 163, 1 },
100477  { 167, 1 },
100478  { 167, 4 },
100479  { 167, 6 },
100480  { 168, 1 },
100481  { 168, 2 },
100482  { 169, 1 },
100483  { 169, 1 },
100484  { 164, 2 },
100485  { 164, 0 },
100486  { 172, 3 },
100487  { 172, 1 },
100488  { 173, 2 },
100489  { 173, 4 },
100490  { 173, 3 },
100491  { 173, 3 },
100492  { 173, 2 },
100493  { 173, 2 },
100494  { 173, 3 },
100495  { 173, 5 },
100496  { 173, 2 },
100497  { 173, 4 },
100498  { 173, 4 },
100499  { 173, 1 },
100500  { 173, 2 },
100501  { 178, 0 },
100502  { 178, 1 },
100503  { 180, 0 },
100504  { 180, 2 },
100505  { 182, 2 },
100506  { 182, 3 },
100507  { 182, 3 },
100508  { 182, 3 },
100509  { 183, 2 },
100510  { 183, 2 },
100511  { 183, 1 },
100512  { 183, 1 },
100513  { 183, 2 },
100514  { 181, 3 },
100515  { 181, 2 },
100516  { 184, 0 },
100517  { 184, 2 },
100518  { 184, 2 },
100519  { 159, 0 },
100520  { 159, 2 },
100521  { 185, 3 },
100522  { 185, 2 },
100523  { 185, 1 },
100524  { 186, 2 },
100525  { 186, 7 },
100526  { 186, 5 },
100527  { 186, 5 },
100528  { 186, 10 },
100529  { 188, 0 },
100530  { 188, 1 },
100531  { 176, 0 },
100532  { 176, 3 },
100533  { 189, 0 },
100534  { 189, 2 },
100535  { 190, 1 },
100536  { 190, 1 },
100537  { 190, 1 },
100538  { 147, 4 },
100539  { 192, 2 },
100540  { 192, 0 },
100541  { 147, 8 },
100542  { 147, 4 },
100543  { 147, 1 },
100544  { 160, 1 },
100545  { 160, 3 },
100546  { 195, 1 },
100547  { 195, 2 },
100548  { 195, 1 },
100549  { 194, 9 },
100550  { 196, 1 },
100551  { 196, 1 },
100552  { 196, 0 },
100553  { 204, 2 },
100554  { 204, 0 },
100555  { 197, 3 },
100556  { 197, 2 },
100557  { 197, 4 },
100558  { 205, 2 },
100559  { 205, 1 },
100560  { 205, 0 },
100561  { 198, 0 },
100562  { 198, 2 },
100563  { 207, 2 },
100564  { 207, 0 },
100565  { 206, 7 },
100566  { 206, 7 },
100567  { 206, 7 },
100568  { 157, 0 },
100569  { 157, 2 },
100570  { 193, 2 },
100571  { 208, 1 },
100572  { 208, 2 },
100573  { 208, 3 },
100574  { 208, 4 },
100575  { 210, 2 },
100576  { 210, 0 },
100577  { 209, 0 },
100578  { 209, 3 },
100579  { 209, 2 },
100580  { 211, 4 },
100581  { 211, 0 },
100582  { 202, 0 },
100583  { 202, 3 },
100584  { 214, 4 },
100585  { 214, 2 },
100586  { 215, 1 },
100587  { 177, 1 },
100588  { 177, 1 },
100589  { 177, 0 },
100590  { 200, 0 },
100591  { 200, 3 },
100592  { 201, 0 },
100593  { 201, 2 },
100594  { 203, 0 },
100595  { 203, 2 },
100596  { 203, 4 },
100597  { 203, 4 },
100598  { 147, 5 },
100599  { 199, 0 },
100600  { 199, 2 },
100601  { 147, 7 },
100602  { 217, 5 },
100603  { 217, 3 },
100604  { 147, 8 },
100605  { 147, 5 },
100606  { 147, 6 },
100607  { 218, 2 },
100608  { 218, 1 },
100609  { 220, 3 },
100610  { 220, 1 },
100611  { 219, 0 },
100612  { 219, 3 },
100613  { 213, 3 },
100614  { 213, 1 },
100615  { 175, 1 },
100616  { 175, 3 },
100617  { 174, 1 },
100618  { 175, 1 },
100619  { 175, 1 },
100620  { 175, 3 },
100621  { 175, 5 },
100622  { 174, 1 },
100623  { 174, 1 },
100624  { 175, 1 },
100625  { 175, 1 },
100626  { 175, 3 },
100627  { 175, 6 },
100628  { 175, 5 },
100629  { 175, 4 },
100630  { 174, 1 },
100631  { 175, 3 },
100632  { 175, 3 },
100633  { 175, 3 },
100634  { 175, 3 },
100635  { 175, 3 },
100636  { 175, 3 },
100637  { 175, 3 },
100638  { 175, 3 },
100639  { 222, 1 },
100640  { 222, 2 },
100641  { 222, 1 },
100642  { 222, 2 },
100643  { 175, 3 },
100644  { 175, 5 },
100645  { 175, 2 },
100646  { 175, 3 },
100647  { 175, 3 },
100648  { 175, 4 },
100649  { 175, 2 },
100650  { 175, 2 },
100651  { 175, 2 },
100652  { 175, 2 },
100653  { 223, 1 },
100654  { 223, 2 },
100655  { 175, 5 },
100656  { 224, 1 },
100657  { 224, 2 },
100658  { 175, 5 },
100659  { 175, 3 },
100660  { 175, 5 },
100661  { 175, 4 },
100662  { 175, 4 },
100663  { 175, 5 },
100664  { 226, 5 },
100665  { 226, 4 },
100666  { 227, 2 },
100667  { 227, 0 },
100668  { 225, 1 },
100669  { 225, 0 },
100670  { 221, 1 },
100671  { 221, 0 },
100672  { 216, 3 },
100673  { 216, 1 },
100674  { 147, 11 },
100675  { 228, 1 },
100676  { 228, 0 },
100677  { 179, 0 },
100678  { 179, 3 },
100679  { 187, 5 },
100680  { 187, 3 },
100681  { 229, 0 },
100682  { 229, 2 },
100683  { 147, 4 },
100684  { 147, 1 },
100685  { 147, 2 },
100686  { 147, 3 },
100687  { 147, 5 },
100688  { 147, 6 },
100689  { 147, 5 },
100690  { 147, 6 },
100691  { 230, 1 },
100692  { 230, 1 },
100693  { 230, 1 },
100694  { 230, 1 },
100695  { 230, 1 },
100696  { 170, 2 },
100697  { 171, 2 },
100698  { 232, 1 },
100699  { 231, 1 },
100700  { 231, 0 },
100701  { 147, 5 },
100702  { 233, 11 },
100703  { 235, 1 },
100704  { 235, 1 },
100705  { 235, 2 },
100706  { 235, 0 },
100707  { 236, 1 },
100708  { 236, 1 },
100709  { 236, 3 },
100710  { 237, 0 },
100711  { 237, 3 },
100712  { 238, 0 },
100713  { 238, 2 },
100714  { 234, 3 },
100715  { 234, 2 },
100716  { 240, 1 },
100717  { 240, 3 },
100718  { 241, 0 },
100719  { 241, 3 },
100720  { 241, 2 },
100721  { 239, 7 },
100722  { 239, 8 },
100723  { 239, 5 },
100724  { 239, 5 },
100725  { 239, 1 },
100726  { 175, 4 },
100727  { 175, 6 },
100728  { 191, 1 },
100729  { 191, 1 },
100730  { 191, 1 },
100731  { 147, 4 },
100732  { 147, 6 },
100733  { 147, 3 },
100734  { 243, 0 },
100735  { 243, 2 },
100736  { 242, 1 },
100737  { 242, 0 },
100738  { 147, 1 },
100739  { 147, 3 },
100740  { 147, 1 },
100741  { 147, 3 },
100742  { 147, 6 },
100743  { 147, 6 },
100744  { 244, 1 },
100745  { 245, 0 },
100746  { 245, 1 },
100747  { 147, 1 },
100748  { 147, 4 },
100749  { 246, 7 },
100750  { 247, 1 },
100751  { 247, 3 },
100752  { 248, 0 },
100753  { 248, 2 },
100754  { 249, 1 },
100755  { 249, 3 },
100756  { 250, 1 },
100757  { 251, 0 },
100758  { 251, 4 },
100759  { 251, 2 },
100760};
100761
100762static void yy_accept(yyParser*);  /* Forward Declaration */
100763
100764/*
100765** Perform a reduce action and the shift that must immediately
100766** follow the reduce.
100767*/
100768static void yy_reduce(
100769  yyParser *yypParser,         /* The parser */
100770  int yyruleno                 /* Number of the rule by which to reduce */
100771){
100772  int yygoto;                     /* The next state */
100773  int yyact;                      /* The next action */
100774  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
100775  yyStackEntry *yymsp;            /* The top of the parser's stack */
100776  int yysize;                     /* Amount to pop the stack */
100777  sqlite3ParserARG_FETCH;
100778  yymsp = &yypParser->yystack[yypParser->yyidx];
100779#ifndef NDEBUG
100780  if( yyTraceFILE && yyruleno>=0
100781        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
100782    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
100783      yyRuleName[yyruleno]);
100784  }
100785#endif /* NDEBUG */
100786
100787  /* Silence complaints from purify about yygotominor being uninitialized
100788  ** in some cases when it is copied into the stack after the following
100789  ** switch.  yygotominor is uninitialized when a rule reduces that does
100790  ** not set the value of its left-hand side nonterminal.  Leaving the
100791  ** value of the nonterminal uninitialized is utterly harmless as long
100792  ** as the value is never used.  So really the only thing this code
100793  ** accomplishes is to quieten purify.
100794  **
100795  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
100796  ** without this code, their parser segfaults.  I'm not sure what there
100797  ** parser is doing to make this happen.  This is the second bug report
100798  ** from wireshark this week.  Clearly they are stressing Lemon in ways
100799  ** that it has not been previously stressed...  (SQLite ticket #2172)
100800  */
100801  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
100802  yygotominor = yyzerominor;
100803
100804
100805  switch( yyruleno ){
100806  /* Beginning here are the reduction cases.  A typical example
100807  ** follows:
100808  **   case 0:
100809  **  #line <lineno> <grammarfile>
100810  **     { ... }           // User supplied code
100811  **  #line <lineno> <thisfile>
100812  **     break;
100813  */
100814      case 5: /* explain ::= */
100815{ sqlite3BeginParse(pParse, 0); }
100816        break;
100817      case 6: /* explain ::= EXPLAIN */
100818{ sqlite3BeginParse(pParse, 1); }
100819        break;
100820      case 7: /* explain ::= EXPLAIN QUERY PLAN */
100821{ sqlite3BeginParse(pParse, 2); }
100822        break;
100823      case 8: /* cmdx ::= cmd */
100824{ sqlite3FinishCoding(pParse); }
100825        break;
100826      case 9: /* cmd ::= BEGIN transtype trans_opt */
100827{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
100828        break;
100829      case 13: /* transtype ::= */
100830{yygotominor.yy4 = TK_DEFERRED;}
100831        break;
100832      case 14: /* transtype ::= DEFERRED */
100833      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
100834      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
100835      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
100836      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
100837{yygotominor.yy4 = yymsp[0].major;}
100838        break;
100839      case 17: /* cmd ::= COMMIT trans_opt */
100840      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
100841{sqlite3CommitTransaction(pParse);}
100842        break;
100843      case 19: /* cmd ::= ROLLBACK trans_opt */
100844{sqlite3RollbackTransaction(pParse);}
100845        break;
100846      case 22: /* cmd ::= SAVEPOINT nm */
100847{
100848  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
100849}
100850        break;
100851      case 23: /* cmd ::= RELEASE savepoint_opt nm */
100852{
100853  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
100854}
100855        break;
100856      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
100857{
100858  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
100859}
100860        break;
100861      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
100862{
100863   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
100864}
100865        break;
100866      case 27: /* createkw ::= CREATE */
100867{
100868  pParse->db->lookaside.bEnabled = 0;
100869  yygotominor.yy0 = yymsp[0].minor.yy0;
100870}
100871        break;
100872      case 28: /* ifnotexists ::= */
100873      case 31: /* temp ::= */ yytestcase(yyruleno==31);
100874      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
100875      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
100876      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
100877      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
100878      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
100879      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
100880      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
100881      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
100882      case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
100883      case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
100884{yygotominor.yy4 = 0;}
100885        break;
100886      case 29: /* ifnotexists ::= IF NOT EXISTS */
100887      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
100888      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
100889      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
100890      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
100891      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
100892      case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
100893      case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
100894{yygotominor.yy4 = 1;}
100895        break;
100896      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
100897{
100898  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
100899}
100900        break;
100901      case 33: /* create_table_args ::= AS select */
100902{
100903  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
100904  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
100905}
100906        break;
100907      case 36: /* column ::= columnid type carglist */
100908{
100909  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
100910  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
100911}
100912        break;
100913      case 37: /* columnid ::= nm */
100914{
100915  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
100916  yygotominor.yy0 = yymsp[0].minor.yy0;
100917}
100918        break;
100919      case 38: /* id ::= ID */
100920      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
100921      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
100922      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
100923      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
100924      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
100925      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
100926      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
100927      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
100928      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
100929      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
100930      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
100931      case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
100932      case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
100933      case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
100934      case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
100935      case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
100936      case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
100937      case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
100938      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
100939      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
100940      case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
100941{yygotominor.yy0 = yymsp[0].minor.yy0;}
100942        break;
100943      case 45: /* type ::= typetoken */
100944{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
100945        break;
100946      case 47: /* typetoken ::= typename LP signed RP */
100947{
100948  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
100949  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
100950}
100951        break;
100952      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
100953{
100954  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
100955  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
100956}
100957        break;
100958      case 50: /* typename ::= typename ids */
100959{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);}
100960        break;
100961      case 57: /* ccons ::= DEFAULT term */
100962      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
100963{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
100964        break;
100965      case 58: /* ccons ::= DEFAULT LP expr RP */
100966{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
100967        break;
100968      case 60: /* ccons ::= DEFAULT MINUS term */
100969{
100970  ExprSpan v;
100971  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
100972  v.zStart = yymsp[-1].minor.yy0.z;
100973  v.zEnd = yymsp[0].minor.yy118.zEnd;
100974  sqlite3AddDefaultValue(pParse,&v);
100975}
100976        break;
100977      case 61: /* ccons ::= DEFAULT id */
100978{
100979  ExprSpan v;
100980  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
100981  sqlite3AddDefaultValue(pParse,&v);
100982}
100983        break;
100984      case 63: /* ccons ::= NOT NULL onconf */
100985{sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
100986        break;
100987      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
100988{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
100989        break;
100990      case 65: /* ccons ::= UNIQUE onconf */
100991{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
100992        break;
100993      case 66: /* ccons ::= CHECK LP expr RP */
100994{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
100995        break;
100996      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
100997{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
100998        break;
100999      case 68: /* ccons ::= defer_subclause */
101000{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
101001        break;
101002      case 69: /* ccons ::= COLLATE ids */
101003{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
101004        break;
101005      case 72: /* refargs ::= */
101006{ yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
101007        break;
101008      case 73: /* refargs ::= refargs refarg */
101009{ yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
101010        break;
101011      case 74: /* refarg ::= MATCH nm */
101012      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
101013{ yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
101014        break;
101015      case 76: /* refarg ::= ON DELETE refact */
101016{ yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
101017        break;
101018      case 77: /* refarg ::= ON UPDATE refact */
101019{ yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
101020        break;
101021      case 78: /* refact ::= SET NULL */
101022{ yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
101023        break;
101024      case 79: /* refact ::= SET DEFAULT */
101025{ yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
101026        break;
101027      case 80: /* refact ::= CASCADE */
101028{ yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
101029        break;
101030      case 81: /* refact ::= RESTRICT */
101031{ yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
101032        break;
101033      case 82: /* refact ::= NO ACTION */
101034{ yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
101035        break;
101036      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
101037      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
101038      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
101039      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
101040{yygotominor.yy4 = yymsp[0].minor.yy4;}
101041        break;
101042      case 88: /* conslist_opt ::= */
101043{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
101044        break;
101045      case 89: /* conslist_opt ::= COMMA conslist */
101046{yygotominor.yy0 = yymsp[-1].minor.yy0;}
101047        break;
101048      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
101049{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
101050        break;
101051      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
101052{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
101053        break;
101054      case 96: /* tcons ::= CHECK LP expr RP onconf */
101055{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
101056        break;
101057      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
101058{
101059    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
101060    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
101061}
101062        break;
101063      case 100: /* onconf ::= */
101064{yygotominor.yy4 = OE_Default;}
101065        break;
101066      case 102: /* orconf ::= */
101067{yygotominor.yy210 = OE_Default;}
101068        break;
101069      case 103: /* orconf ::= OR resolvetype */
101070{yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
101071        break;
101072      case 105: /* resolvetype ::= IGNORE */
101073{yygotominor.yy4 = OE_Ignore;}
101074        break;
101075      case 106: /* resolvetype ::= REPLACE */
101076{yygotominor.yy4 = OE_Replace;}
101077        break;
101078      case 107: /* cmd ::= DROP TABLE ifexists fullname */
101079{
101080  sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
101081}
101082        break;
101083      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
101084{
101085  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
101086}
101087        break;
101088      case 111: /* cmd ::= DROP VIEW ifexists fullname */
101089{
101090  sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
101091}
101092        break;
101093      case 112: /* cmd ::= select */
101094{
101095  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
101096  sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
101097  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
101098}
101099        break;
101100      case 113: /* select ::= oneselect */
101101{yygotominor.yy387 = yymsp[0].minor.yy387;}
101102        break;
101103      case 114: /* select ::= select multiselect_op oneselect */
101104{
101105  if( yymsp[0].minor.yy387 ){
101106    yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
101107    yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
101108  }else{
101109    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
101110  }
101111  yygotominor.yy387 = yymsp[0].minor.yy387;
101112}
101113        break;
101114      case 116: /* multiselect_op ::= UNION ALL */
101115{yygotominor.yy4 = TK_ALL;}
101116        break;
101117      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
101118{
101119  yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
101120}
101121        break;
101122      case 122: /* sclp ::= selcollist COMMA */
101123      case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
101124{yygotominor.yy322 = yymsp[-1].minor.yy322;}
101125        break;
101126      case 123: /* sclp ::= */
101127      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
101128      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
101129      case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
101130      case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
101131{yygotominor.yy322 = 0;}
101132        break;
101133      case 124: /* selcollist ::= sclp expr as */
101134{
101135   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
101136   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
101137   sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
101138}
101139        break;
101140      case 125: /* selcollist ::= sclp STAR */
101141{
101142  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
101143  yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
101144}
101145        break;
101146      case 126: /* selcollist ::= sclp nm DOT STAR */
101147{
101148  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
101149  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101150  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
101151  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
101152}
101153        break;
101154      case 129: /* as ::= */
101155{yygotominor.yy0.n = 0;}
101156        break;
101157      case 130: /* from ::= */
101158{yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
101159        break;
101160      case 131: /* from ::= FROM seltablist */
101161{
101162  yygotominor.yy259 = yymsp[0].minor.yy259;
101163  sqlite3SrcListShiftJoinType(yygotominor.yy259);
101164}
101165        break;
101166      case 132: /* stl_prefix ::= seltablist joinop */
101167{
101168   yygotominor.yy259 = yymsp[-1].minor.yy259;
101169   if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
101170}
101171        break;
101172      case 133: /* stl_prefix ::= */
101173{yygotominor.yy259 = 0;}
101174        break;
101175      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
101176{
101177  yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
101178  sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
101179}
101180        break;
101181      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
101182{
101183    yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
101184  }
101185        break;
101186      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
101187{
101188    if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
101189      yygotominor.yy259 = yymsp[-4].minor.yy259;
101190    }else{
101191      Select *pSubquery;
101192      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
101193      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
101194      yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
101195    }
101196  }
101197        break;
101198      case 137: /* dbnm ::= */
101199      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
101200{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
101201        break;
101202      case 139: /* fullname ::= nm dbnm */
101203{yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
101204        break;
101205      case 140: /* joinop ::= COMMA|JOIN */
101206{ yygotominor.yy4 = JT_INNER; }
101207        break;
101208      case 141: /* joinop ::= JOIN_KW JOIN */
101209{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
101210        break;
101211      case 142: /* joinop ::= JOIN_KW nm JOIN */
101212{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
101213        break;
101214      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
101215{ yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
101216        break;
101217      case 144: /* on_opt ::= ON expr */
101218      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
101219      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
101220      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
101221      case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
101222      case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
101223{yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
101224        break;
101225      case 145: /* on_opt ::= */
101226      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
101227      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
101228      case 236: /* case_else ::= */ yytestcase(yyruleno==236);
101229      case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
101230{yygotominor.yy314 = 0;}
101231        break;
101232      case 148: /* indexed_opt ::= NOT INDEXED */
101233{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
101234        break;
101235      case 149: /* using_opt ::= USING LP inscollist RP */
101236      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
101237{yygotominor.yy384 = yymsp[-1].minor.yy384;}
101238        break;
101239      case 150: /* using_opt ::= */
101240      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
101241{yygotominor.yy384 = 0;}
101242        break;
101243      case 152: /* orderby_opt ::= ORDER BY sortlist */
101244      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
101245      case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
101246{yygotominor.yy322 = yymsp[0].minor.yy322;}
101247        break;
101248      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
101249{
101250  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
101251  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
101252}
101253        break;
101254      case 154: /* sortlist ::= sortitem sortorder */
101255{
101256  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
101257  if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
101258}
101259        break;
101260      case 156: /* sortorder ::= ASC */
101261      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
101262{yygotominor.yy4 = SQLITE_SO_ASC;}
101263        break;
101264      case 157: /* sortorder ::= DESC */
101265{yygotominor.yy4 = SQLITE_SO_DESC;}
101266        break;
101267      case 163: /* limit_opt ::= */
101268{yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
101269        break;
101270      case 164: /* limit_opt ::= LIMIT expr */
101271{yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
101272        break;
101273      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
101274{yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
101275        break;
101276      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
101277{yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
101278        break;
101279      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
101280{
101281  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
101282  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
101283}
101284        break;
101285      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
101286{
101287  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
101288  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
101289  sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
101290}
101291        break;
101292      case 171: /* setlist ::= setlist COMMA nm EQ expr */
101293{
101294  yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
101295  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
101296}
101297        break;
101298      case 172: /* setlist ::= nm EQ expr */
101299{
101300  yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
101301  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
101302}
101303        break;
101304      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
101305{sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
101306        break;
101307      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
101308{sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
101309        break;
101310      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
101311{sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
101312        break;
101313      case 176: /* insert_cmd ::= INSERT orconf */
101314{yygotominor.yy210 = yymsp[0].minor.yy210;}
101315        break;
101316      case 177: /* insert_cmd ::= REPLACE */
101317{yygotominor.yy210 = OE_Replace;}
101318        break;
101319      case 178: /* itemlist ::= itemlist COMMA expr */
101320      case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
101321{yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
101322        break;
101323      case 179: /* itemlist ::= expr */
101324      case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
101325{yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
101326        break;
101327      case 182: /* inscollist ::= inscollist COMMA nm */
101328{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
101329        break;
101330      case 183: /* inscollist ::= nm */
101331{yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
101332        break;
101333      case 184: /* expr ::= term */
101334{yygotominor.yy118 = yymsp[0].minor.yy118;}
101335        break;
101336      case 185: /* expr ::= LP expr RP */
101337{yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
101338        break;
101339      case 186: /* term ::= NULL */
101340      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
101341      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
101342{spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
101343        break;
101344      case 187: /* expr ::= id */
101345      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
101346{spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
101347        break;
101348      case 189: /* expr ::= nm DOT nm */
101349{
101350  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101351  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
101352  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
101353  spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
101354}
101355        break;
101356      case 190: /* expr ::= nm DOT nm DOT nm */
101357{
101358  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
101359  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
101360  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
101361  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
101362  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
101363  spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
101364}
101365        break;
101366      case 193: /* expr ::= REGISTER */
101367{
101368  /* When doing a nested parse, one can include terms in an expression
101369  ** that look like this:   #1 #2 ...  These terms refer to registers
101370  ** in the virtual machine.  #N is the N-th register. */
101371  if( pParse->nested==0 ){
101372    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
101373    yygotominor.yy118.pExpr = 0;
101374  }else{
101375    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
101376    if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
101377  }
101378  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101379}
101380        break;
101381      case 194: /* expr ::= VARIABLE */
101382{
101383  spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
101384  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
101385  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101386}
101387        break;
101388      case 195: /* expr ::= expr COLLATE ids */
101389{
101390  yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
101391  yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
101392  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101393}
101394        break;
101395      case 196: /* expr ::= CAST LP expr AS typetoken RP */
101396{
101397  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
101398  spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
101399}
101400        break;
101401      case 197: /* expr ::= ID LP distinct exprlist RP */
101402{
101403  if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
101404    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
101405  }
101406  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
101407  spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
101408  if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
101409    yygotominor.yy118.pExpr->flags |= EP_Distinct;
101410  }
101411}
101412        break;
101413      case 198: /* expr ::= ID LP STAR RP */
101414{
101415  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
101416  spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
101417}
101418        break;
101419      case 199: /* term ::= CTIME_KW */
101420{
101421  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
101422  ** treated as functions that return constants */
101423  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
101424  if( yygotominor.yy118.pExpr ){
101425    yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
101426  }
101427  spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
101428}
101429        break;
101430      case 200: /* expr ::= expr AND expr */
101431      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
101432      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
101433      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
101434      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
101435      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
101436      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
101437      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
101438{spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
101439        break;
101440      case 208: /* likeop ::= LIKE_KW */
101441      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
101442{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
101443        break;
101444      case 209: /* likeop ::= NOT LIKE_KW */
101445      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
101446{yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
101447        break;
101448      case 212: /* expr ::= expr likeop expr */
101449{
101450  ExprList *pList;
101451  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
101452  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
101453  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
101454  if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101455  yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
101456  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
101457  if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
101458}
101459        break;
101460      case 213: /* expr ::= expr likeop expr ESCAPE expr */
101461{
101462  ExprList *pList;
101463  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
101464  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
101465  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
101466  yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
101467  if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101468  yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
101469  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
101470  if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
101471}
101472        break;
101473      case 214: /* expr ::= expr ISNULL|NOTNULL */
101474{spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
101475        break;
101476      case 215: /* expr ::= expr NOT NULL */
101477{spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
101478        break;
101479      case 216: /* expr ::= expr IS expr */
101480{
101481  spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
101482  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
101483}
101484        break;
101485      case 217: /* expr ::= expr IS NOT expr */
101486{
101487  spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
101488  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
101489}
101490        break;
101491      case 218: /* expr ::= NOT expr */
101492      case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
101493{spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
101494        break;
101495      case 220: /* expr ::= MINUS expr */
101496{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
101497        break;
101498      case 221: /* expr ::= PLUS expr */
101499{spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
101500        break;
101501      case 224: /* expr ::= expr between_op expr AND expr */
101502{
101503  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
101504  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
101505  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
101506  if( yygotominor.yy118.pExpr ){
101507    yygotominor.yy118.pExpr->x.pList = pList;
101508  }else{
101509    sqlite3ExprListDelete(pParse->db, pList);
101510  }
101511  if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101512  yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
101513  yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
101514}
101515        break;
101516      case 227: /* expr ::= expr in_op LP exprlist RP */
101517{
101518    if( yymsp[-1].minor.yy322==0 ){
101519      /* Expressions of the form
101520      **
101521      **      expr1 IN ()
101522      **      expr1 NOT IN ()
101523      **
101524      ** simplify to constants 0 (false) and 1 (true), respectively,
101525      ** regardless of the value of expr1.
101526      */
101527      yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
101528      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
101529    }else{
101530      yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
101531      if( yygotominor.yy118.pExpr ){
101532        yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
101533        sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
101534      }else{
101535        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
101536      }
101537      if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101538    }
101539    yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
101540    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101541  }
101542        break;
101543      case 228: /* expr ::= LP select RP */
101544{
101545    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
101546    if( yygotominor.yy118.pExpr ){
101547      yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
101548      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
101549      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
101550    }else{
101551      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
101552    }
101553    yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
101554    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101555  }
101556        break;
101557      case 229: /* expr ::= expr in_op LP select RP */
101558{
101559    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
101560    if( yygotominor.yy118.pExpr ){
101561      yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
101562      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
101563      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
101564    }else{
101565      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
101566    }
101567    if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101568    yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
101569    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101570  }
101571        break;
101572      case 230: /* expr ::= expr in_op nm dbnm */
101573{
101574    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
101575    yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
101576    if( yygotominor.yy118.pExpr ){
101577      yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
101578      ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
101579      sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
101580    }else{
101581      sqlite3SrcListDelete(pParse->db, pSrc);
101582    }
101583    if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
101584    yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
101585    yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
101586  }
101587        break;
101588      case 231: /* expr ::= EXISTS LP select RP */
101589{
101590    Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
101591    if( p ){
101592      p->x.pSelect = yymsp[-1].minor.yy387;
101593      ExprSetProperty(p, EP_xIsSelect);
101594      sqlite3ExprSetHeight(pParse, p);
101595    }else{
101596      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
101597    }
101598    yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
101599    yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101600  }
101601        break;
101602      case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
101603{
101604  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
101605  if( yygotominor.yy118.pExpr ){
101606    yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
101607    sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
101608  }else{
101609    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
101610  }
101611  yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
101612  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101613}
101614        break;
101615      case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
101616{
101617  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
101618  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
101619}
101620        break;
101621      case 234: /* case_exprlist ::= WHEN expr THEN expr */
101622{
101623  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
101624  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
101625}
101626        break;
101627      case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
101628{
101629  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
101630                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
101631                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
101632}
101633        break;
101634      case 244: /* uniqueflag ::= UNIQUE */
101635      case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
101636{yygotominor.yy4 = OE_Abort;}
101637        break;
101638      case 245: /* uniqueflag ::= */
101639{yygotominor.yy4 = OE_None;}
101640        break;
101641      case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
101642{
101643  Expr *p = 0;
101644  if( yymsp[-1].minor.yy0.n>0 ){
101645    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
101646    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
101647  }
101648  yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
101649  sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
101650  sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
101651  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
101652}
101653        break;
101654      case 249: /* idxlist ::= nm collate sortorder */
101655{
101656  Expr *p = 0;
101657  if( yymsp[-1].minor.yy0.n>0 ){
101658    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
101659    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
101660  }
101661  yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
101662  sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
101663  sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
101664  if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
101665}
101666        break;
101667      case 250: /* collate ::= */
101668{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
101669        break;
101670      case 252: /* cmd ::= DROP INDEX ifexists fullname */
101671{sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
101672        break;
101673      case 253: /* cmd ::= VACUUM */
101674      case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
101675{sqlite3Vacuum(pParse);}
101676        break;
101677      case 255: /* cmd ::= PRAGMA nm dbnm */
101678{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
101679        break;
101680      case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
101681{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
101682        break;
101683      case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
101684{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
101685        break;
101686      case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
101687{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
101688        break;
101689      case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
101690{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
101691        break;
101692      case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
101693{
101694  Token all;
101695  all.z = yymsp[-3].minor.yy0.z;
101696  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
101697  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
101698}
101699        break;
101700      case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
101701{
101702  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
101703  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
101704}
101705        break;
101706      case 272: /* trigger_time ::= BEFORE */
101707      case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
101708{ yygotominor.yy4 = TK_BEFORE; }
101709        break;
101710      case 273: /* trigger_time ::= AFTER */
101711{ yygotominor.yy4 = TK_AFTER;  }
101712        break;
101713      case 274: /* trigger_time ::= INSTEAD OF */
101714{ yygotominor.yy4 = TK_INSTEAD;}
101715        break;
101716      case 276: /* trigger_event ::= DELETE|INSERT */
101717      case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
101718{yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
101719        break;
101720      case 278: /* trigger_event ::= UPDATE OF inscollist */
101721{yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
101722        break;
101723      case 281: /* when_clause ::= */
101724      case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
101725{ yygotominor.yy314 = 0; }
101726        break;
101727      case 282: /* when_clause ::= WHEN expr */
101728      case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
101729{ yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
101730        break;
101731      case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
101732{
101733  assert( yymsp[-2].minor.yy203!=0 );
101734  yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
101735  yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
101736  yygotominor.yy203 = yymsp[-2].minor.yy203;
101737}
101738        break;
101739      case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
101740{
101741  assert( yymsp[-1].minor.yy203!=0 );
101742  yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
101743  yygotominor.yy203 = yymsp[-1].minor.yy203;
101744}
101745        break;
101746      case 286: /* trnm ::= nm DOT nm */
101747{
101748  yygotominor.yy0 = yymsp[0].minor.yy0;
101749  sqlite3ErrorMsg(pParse,
101750        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
101751        "statements within triggers");
101752}
101753        break;
101754      case 288: /* tridxby ::= INDEXED BY nm */
101755{
101756  sqlite3ErrorMsg(pParse,
101757        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
101758        "within triggers");
101759}
101760        break;
101761      case 289: /* tridxby ::= NOT INDEXED */
101762{
101763  sqlite3ErrorMsg(pParse,
101764        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
101765        "within triggers");
101766}
101767        break;
101768      case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
101769{ yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
101770        break;
101771      case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
101772{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
101773        break;
101774      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
101775{yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
101776        break;
101777      case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
101778{yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
101779        break;
101780      case 294: /* trigger_cmd ::= select */
101781{yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
101782        break;
101783      case 295: /* expr ::= RAISE LP IGNORE RP */
101784{
101785  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
101786  if( yygotominor.yy118.pExpr ){
101787    yygotominor.yy118.pExpr->affinity = OE_Ignore;
101788  }
101789  yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
101790  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101791}
101792        break;
101793      case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
101794{
101795  yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
101796  if( yygotominor.yy118.pExpr ) {
101797    yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
101798  }
101799  yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
101800  yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
101801}
101802        break;
101803      case 297: /* raisetype ::= ROLLBACK */
101804{yygotominor.yy4 = OE_Rollback;}
101805        break;
101806      case 299: /* raisetype ::= FAIL */
101807{yygotominor.yy4 = OE_Fail;}
101808        break;
101809      case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
101810{
101811  sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
101812}
101813        break;
101814      case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
101815{
101816  sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
101817}
101818        break;
101819      case 302: /* cmd ::= DETACH database_kw_opt expr */
101820{
101821  sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
101822}
101823        break;
101824      case 307: /* cmd ::= REINDEX */
101825{sqlite3Reindex(pParse, 0, 0);}
101826        break;
101827      case 308: /* cmd ::= REINDEX nm dbnm */
101828{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
101829        break;
101830      case 309: /* cmd ::= ANALYZE */
101831{sqlite3Analyze(pParse, 0, 0);}
101832        break;
101833      case 310: /* cmd ::= ANALYZE nm dbnm */
101834{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
101835        break;
101836      case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
101837{
101838  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
101839}
101840        break;
101841      case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
101842{
101843  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
101844}
101845        break;
101846      case 313: /* add_column_fullname ::= fullname */
101847{
101848  pParse->db->lookaside.bEnabled = 0;
101849  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
101850}
101851        break;
101852      case 316: /* cmd ::= create_vtab */
101853{sqlite3VtabFinishParse(pParse,0);}
101854        break;
101855      case 317: /* cmd ::= create_vtab LP vtabarglist RP */
101856{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
101857        break;
101858      case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
101859{
101860    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
101861}
101862        break;
101863      case 321: /* vtabarg ::= */
101864{sqlite3VtabArgInit(pParse);}
101865        break;
101866      case 323: /* vtabargtoken ::= ANY */
101867      case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
101868      case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
101869{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
101870        break;
101871      default:
101872      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
101873      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
101874      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
101875      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
101876      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
101877      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
101878      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
101879      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
101880      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
101881      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
101882      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
101883      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
101884      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
101885      /* (44) type ::= */ yytestcase(yyruleno==44);
101886      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
101887      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
101888      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
101889      /* (54) carglist ::= */ yytestcase(yyruleno==54);
101890      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
101891      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
101892      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
101893      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
101894      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
101895      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
101896      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
101897      /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
101898      /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
101899      /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
101900      /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
101901      /* (287) tridxby ::= */ yytestcase(yyruleno==287);
101902      /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
101903      /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
101904      /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
101905      /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
101906      /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
101907      /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
101908      /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
101909      /* (326) anylist ::= */ yytestcase(yyruleno==326);
101910      /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
101911      /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
101912        break;
101913  };
101914  yygoto = yyRuleInfo[yyruleno].lhs;
101915  yysize = yyRuleInfo[yyruleno].nrhs;
101916  yypParser->yyidx -= yysize;
101917  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
101918  if( yyact < YYNSTATE ){
101919#ifdef NDEBUG
101920    /* If we are not debugging and the reduce action popped at least
101921    ** one element off the stack, then we can push the new element back
101922    ** onto the stack here, and skip the stack overflow test in yy_shift().
101923    ** That gives a significant speed improvement. */
101924    if( yysize ){
101925      yypParser->yyidx++;
101926      yymsp -= yysize-1;
101927      yymsp->stateno = (YYACTIONTYPE)yyact;
101928      yymsp->major = (YYCODETYPE)yygoto;
101929      yymsp->minor = yygotominor;
101930    }else
101931#endif
101932    {
101933      yy_shift(yypParser,yyact,yygoto,&yygotominor);
101934    }
101935  }else{
101936    assert( yyact == YYNSTATE + YYNRULE + 1 );
101937    yy_accept(yypParser);
101938  }
101939}
101940
101941/*
101942** The following code executes when the parse fails
101943*/
101944#ifndef YYNOERRORRECOVERY
101945static void yy_parse_failed(
101946  yyParser *yypParser           /* The parser */
101947){
101948  sqlite3ParserARG_FETCH;
101949#ifndef NDEBUG
101950  if( yyTraceFILE ){
101951    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
101952  }
101953#endif
101954  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
101955  /* Here code is inserted which will be executed whenever the
101956  ** parser fails */
101957  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101958}
101959#endif /* YYNOERRORRECOVERY */
101960
101961/*
101962** The following code executes when a syntax error first occurs.
101963*/
101964static void yy_syntax_error(
101965  yyParser *yypParser,           /* The parser */
101966  int yymajor,                   /* The major type of the error token */
101967  YYMINORTYPE yyminor            /* The minor type of the error token */
101968){
101969  sqlite3ParserARG_FETCH;
101970#define TOKEN (yyminor.yy0)
101971
101972  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
101973  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
101974  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
101975  pParse->parseError = 1;
101976  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101977}
101978
101979/*
101980** The following is executed when the parser accepts
101981*/
101982static void yy_accept(
101983  yyParser *yypParser           /* The parser */
101984){
101985  sqlite3ParserARG_FETCH;
101986#ifndef NDEBUG
101987  if( yyTraceFILE ){
101988    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
101989  }
101990#endif
101991  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
101992  /* Here code is inserted which will be executed whenever the
101993  ** parser accepts */
101994  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
101995}
101996
101997/* The main parser program.
101998** The first argument is a pointer to a structure obtained from
101999** "sqlite3ParserAlloc" which describes the current state of the parser.
102000** The second argument is the major token number.  The third is
102001** the minor token.  The fourth optional argument is whatever the
102002** user wants (and specified in the grammar) and is available for
102003** use by the action routines.
102004**
102005** Inputs:
102006** <ul>
102007** <li> A pointer to the parser (an opaque structure.)
102008** <li> The major token number.
102009** <li> The minor token number.
102010** <li> An option argument of a grammar-specified type.
102011** </ul>
102012**
102013** Outputs:
102014** None.
102015*/
102016SQLITE_PRIVATE void sqlite3Parser(
102017  void *yyp,                   /* The parser */
102018  int yymajor,                 /* The major token code number */
102019  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
102020  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
102021){
102022  YYMINORTYPE yyminorunion;
102023  int yyact;            /* The parser action. */
102024  int yyendofinput;     /* True if we are at the end of input */
102025#ifdef YYERRORSYMBOL
102026  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
102027#endif
102028  yyParser *yypParser;  /* The parser */
102029
102030  /* (re)initialize the parser, if necessary */
102031  yypParser = (yyParser*)yyp;
102032  if( yypParser->yyidx<0 ){
102033#if YYSTACKDEPTH<=0
102034    if( yypParser->yystksz <=0 ){
102035      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
102036      yyminorunion = yyzerominor;
102037      yyStackOverflow(yypParser, &yyminorunion);
102038      return;
102039    }
102040#endif
102041    yypParser->yyidx = 0;
102042    yypParser->yyerrcnt = -1;
102043    yypParser->yystack[0].stateno = 0;
102044    yypParser->yystack[0].major = 0;
102045  }
102046  yyminorunion.yy0 = yyminor;
102047  yyendofinput = (yymajor==0);
102048  sqlite3ParserARG_STORE;
102049
102050#ifndef NDEBUG
102051  if( yyTraceFILE ){
102052    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
102053  }
102054#endif
102055
102056  do{
102057    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
102058    if( yyact<YYNSTATE ){
102059      assert( !yyendofinput );  /* Impossible to shift the $ token */
102060      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
102061      yypParser->yyerrcnt--;
102062      yymajor = YYNOCODE;
102063    }else if( yyact < YYNSTATE + YYNRULE ){
102064      yy_reduce(yypParser,yyact-YYNSTATE);
102065    }else{
102066      assert( yyact == YY_ERROR_ACTION );
102067#ifdef YYERRORSYMBOL
102068      int yymx;
102069#endif
102070#ifndef NDEBUG
102071      if( yyTraceFILE ){
102072        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
102073      }
102074#endif
102075#ifdef YYERRORSYMBOL
102076      /* A syntax error has occurred.
102077      ** The response to an error depends upon whether or not the
102078      ** grammar defines an error token "ERROR".
102079      **
102080      ** This is what we do if the grammar does define ERROR:
102081      **
102082      **  * Call the %syntax_error function.
102083      **
102084      **  * Begin popping the stack until we enter a state where
102085      **    it is legal to shift the error symbol, then shift
102086      **    the error symbol.
102087      **
102088      **  * Set the error count to three.
102089      **
102090      **  * Begin accepting and shifting new tokens.  No new error
102091      **    processing will occur until three tokens have been
102092      **    shifted successfully.
102093      **
102094      */
102095      if( yypParser->yyerrcnt<0 ){
102096        yy_syntax_error(yypParser,yymajor,yyminorunion);
102097      }
102098      yymx = yypParser->yystack[yypParser->yyidx].major;
102099      if( yymx==YYERRORSYMBOL || yyerrorhit ){
102100#ifndef NDEBUG
102101        if( yyTraceFILE ){
102102          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
102103             yyTracePrompt,yyTokenName[yymajor]);
102104        }
102105#endif
102106        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
102107        yymajor = YYNOCODE;
102108      }else{
102109         while(
102110          yypParser->yyidx >= 0 &&
102111          yymx != YYERRORSYMBOL &&
102112          (yyact = yy_find_reduce_action(
102113                        yypParser->yystack[yypParser->yyidx].stateno,
102114                        YYERRORSYMBOL)) >= YYNSTATE
102115        ){
102116          yy_pop_parser_stack(yypParser);
102117        }
102118        if( yypParser->yyidx < 0 || yymajor==0 ){
102119          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
102120          yy_parse_failed(yypParser);
102121          yymajor = YYNOCODE;
102122        }else if( yymx!=YYERRORSYMBOL ){
102123          YYMINORTYPE u2;
102124          u2.YYERRSYMDT = 0;
102125          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
102126        }
102127      }
102128      yypParser->yyerrcnt = 3;
102129      yyerrorhit = 1;
102130#elif defined(YYNOERRORRECOVERY)
102131      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
102132      ** do any kind of error recovery.  Instead, simply invoke the syntax
102133      ** error routine and continue going as if nothing had happened.
102134      **
102135      ** Applications can set this macro (for example inside %include) if
102136      ** they intend to abandon the parse upon the first syntax error seen.
102137      */
102138      yy_syntax_error(yypParser,yymajor,yyminorunion);
102139      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
102140      yymajor = YYNOCODE;
102141
102142#else  /* YYERRORSYMBOL is not defined */
102143      /* This is what we do if the grammar does not define ERROR:
102144      **
102145      **  * Report an error message, and throw away the input token.
102146      **
102147      **  * If the input token is $, then fail the parse.
102148      **
102149      ** As before, subsequent error messages are suppressed until
102150      ** three input tokens have been successfully shifted.
102151      */
102152      if( yypParser->yyerrcnt<=0 ){
102153        yy_syntax_error(yypParser,yymajor,yyminorunion);
102154      }
102155      yypParser->yyerrcnt = 3;
102156      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
102157      if( yyendofinput ){
102158        yy_parse_failed(yypParser);
102159      }
102160      yymajor = YYNOCODE;
102161#endif
102162    }
102163  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
102164  return;
102165}
102166
102167/************** End of parse.c ***********************************************/
102168/************** Begin file tokenize.c ****************************************/
102169/*
102170** 2001 September 15
102171**
102172** The author disclaims copyright to this source code.  In place of
102173** a legal notice, here is a blessing:
102174**
102175**    May you do good and not evil.
102176**    May you find forgiveness for yourself and forgive others.
102177**    May you share freely, never taking more than you give.
102178**
102179*************************************************************************
102180** An tokenizer for SQL
102181**
102182** This file contains C code that splits an SQL input string up into
102183** individual tokens and sends those tokens one-by-one over to the
102184** parser for analysis.
102185*/
102186
102187/*
102188** The charMap() macro maps alphabetic characters into their
102189** lower-case ASCII equivalent.  On ASCII machines, this is just
102190** an upper-to-lower case map.  On EBCDIC machines we also need
102191** to adjust the encoding.  Only alphabetic characters and underscores
102192** need to be translated.
102193*/
102194#ifdef SQLITE_ASCII
102195# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
102196#endif
102197#ifdef SQLITE_EBCDIC
102198# define charMap(X) ebcdicToAscii[(unsigned char)X]
102199const unsigned char ebcdicToAscii[] = {
102200/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
102201   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
102202   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
102203   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
102204   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
102205   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
102206   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
102207   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
102208   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
102209   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
102210   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
102211   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
102212   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
102213   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
102214   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
102215   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
102216   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
102217};
102218#endif
102219
102220/*
102221** The sqlite3KeywordCode function looks up an identifier to determine if
102222** it is a keyword.  If it is a keyword, the token code of that keyword is
102223** returned.  If the input is not a keyword, TK_ID is returned.
102224**
102225** The implementation of this routine was generated by a program,
102226** mkkeywordhash.h, located in the tool subdirectory of the distribution.
102227** The output of the mkkeywordhash.c program is written into a file
102228** named keywordhash.h and then included into this source file by
102229** the #include below.
102230*/
102231/************** Include keywordhash.h in the middle of tokenize.c ************/
102232/************** Begin file keywordhash.h *************************************/
102233/***** This file contains automatically generated code ******
102234**
102235** The code in this file has been automatically generated by
102236**
102237**   sqlite/tool/mkkeywordhash.c
102238**
102239** The code in this file implements a function that determines whether
102240** or not a given identifier is really an SQL keyword.  The same thing
102241** might be implemented more directly using a hand-written hash table.
102242** But by using this automatically generated code, the size of the code
102243** is substantially reduced.  This is important for embedded applications
102244** on platforms with limited memory.
102245*/
102246/* Hash score: 175 */
102247static int keywordCode(const char *z, int n){
102248  /* zText[] encodes 811 bytes of keywords in 541 bytes */
102249  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
102250  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
102251  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
102252  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
102253  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
102254  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
102255  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
102256  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
102257  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
102258  /*   INITIALLY                                                          */
102259  static const char zText[540] = {
102260    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
102261    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
102262    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
102263    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
102264    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
102265    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
102266    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
102267    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
102268    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
102269    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
102270    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
102271    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
102272    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
102273    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
102274    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
102275    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
102276    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
102277    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
102278    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
102279    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
102280    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
102281    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
102282    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
102283    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
102284    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
102285    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
102286    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
102287    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
102288    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
102289    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
102290  };
102291  static const unsigned char aHash[127] = {
102292      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
102293      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
102294     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
102295       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
102296       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
102297      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
102298      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
102299      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
102300      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
102301      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
102302  };
102303  static const unsigned char aNext[121] = {
102304       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
102305       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
102306       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
102307       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
102308       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
102309      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
102310      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
102311       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
102312     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
102313      35,  64,   0,   0,
102314  };
102315  static const unsigned char aLen[121] = {
102316       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
102317       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
102318      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
102319       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
102320       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
102321       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
102322       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
102323       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
102324       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
102325       6,   4,   9,   3,
102326  };
102327  static const unsigned short int aOffset[121] = {
102328       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
102329      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
102330      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
102331     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
102332     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
102333     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
102334     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
102335     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
102336     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
102337     521, 527, 531, 536,
102338  };
102339  static const unsigned char aCode[121] = {
102340    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
102341    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
102342    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
102343    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
102344    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
102345    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
102346    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
102347    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
102348    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
102349    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
102350    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
102351    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
102352    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
102353    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
102354    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
102355    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
102356    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
102357    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
102358    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
102359    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
102360    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
102361    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
102362    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
102363    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
102364    TK_ALL,
102365  };
102366  int h, i;
102367  if( n<2 ) return TK_ID;
102368  h = ((charMap(z[0])*4) ^
102369      (charMap(z[n-1])*3) ^
102370      n) % 127;
102371  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
102372    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
102373      testcase( i==0 ); /* REINDEX */
102374      testcase( i==1 ); /* INDEXED */
102375      testcase( i==2 ); /* INDEX */
102376      testcase( i==3 ); /* DESC */
102377      testcase( i==4 ); /* ESCAPE */
102378      testcase( i==5 ); /* EACH */
102379      testcase( i==6 ); /* CHECK */
102380      testcase( i==7 ); /* KEY */
102381      testcase( i==8 ); /* BEFORE */
102382      testcase( i==9 ); /* FOREIGN */
102383      testcase( i==10 ); /* FOR */
102384      testcase( i==11 ); /* IGNORE */
102385      testcase( i==12 ); /* REGEXP */
102386      testcase( i==13 ); /* EXPLAIN */
102387      testcase( i==14 ); /* INSTEAD */
102388      testcase( i==15 ); /* ADD */
102389      testcase( i==16 ); /* DATABASE */
102390      testcase( i==17 ); /* AS */
102391      testcase( i==18 ); /* SELECT */
102392      testcase( i==19 ); /* TABLE */
102393      testcase( i==20 ); /* LEFT */
102394      testcase( i==21 ); /* THEN */
102395      testcase( i==22 ); /* END */
102396      testcase( i==23 ); /* DEFERRABLE */
102397      testcase( i==24 ); /* ELSE */
102398      testcase( i==25 ); /* EXCEPT */
102399      testcase( i==26 ); /* TRANSACTION */
102400      testcase( i==27 ); /* ACTION */
102401      testcase( i==28 ); /* ON */
102402      testcase( i==29 ); /* NATURAL */
102403      testcase( i==30 ); /* ALTER */
102404      testcase( i==31 ); /* RAISE */
102405      testcase( i==32 ); /* EXCLUSIVE */
102406      testcase( i==33 ); /* EXISTS */
102407      testcase( i==34 ); /* SAVEPOINT */
102408      testcase( i==35 ); /* INTERSECT */
102409      testcase( i==36 ); /* TRIGGER */
102410      testcase( i==37 ); /* REFERENCES */
102411      testcase( i==38 ); /* CONSTRAINT */
102412      testcase( i==39 ); /* INTO */
102413      testcase( i==40 ); /* OFFSET */
102414      testcase( i==41 ); /* OF */
102415      testcase( i==42 ); /* SET */
102416      testcase( i==43 ); /* TEMPORARY */
102417      testcase( i==44 ); /* TEMP */
102418      testcase( i==45 ); /* OR */
102419      testcase( i==46 ); /* UNIQUE */
102420      testcase( i==47 ); /* QUERY */
102421      testcase( i==48 ); /* ATTACH */
102422      testcase( i==49 ); /* HAVING */
102423      testcase( i==50 ); /* GROUP */
102424      testcase( i==51 ); /* UPDATE */
102425      testcase( i==52 ); /* BEGIN */
102426      testcase( i==53 ); /* INNER */
102427      testcase( i==54 ); /* RELEASE */
102428      testcase( i==55 ); /* BETWEEN */
102429      testcase( i==56 ); /* NOTNULL */
102430      testcase( i==57 ); /* NOT */
102431      testcase( i==58 ); /* NO */
102432      testcase( i==59 ); /* NULL */
102433      testcase( i==60 ); /* LIKE */
102434      testcase( i==61 ); /* CASCADE */
102435      testcase( i==62 ); /* ASC */
102436      testcase( i==63 ); /* DELETE */
102437      testcase( i==64 ); /* CASE */
102438      testcase( i==65 ); /* COLLATE */
102439      testcase( i==66 ); /* CREATE */
102440      testcase( i==67 ); /* CURRENT_DATE */
102441      testcase( i==68 ); /* DETACH */
102442      testcase( i==69 ); /* IMMEDIATE */
102443      testcase( i==70 ); /* JOIN */
102444      testcase( i==71 ); /* INSERT */
102445      testcase( i==72 ); /* MATCH */
102446      testcase( i==73 ); /* PLAN */
102447      testcase( i==74 ); /* ANALYZE */
102448      testcase( i==75 ); /* PRAGMA */
102449      testcase( i==76 ); /* ABORT */
102450      testcase( i==77 ); /* VALUES */
102451      testcase( i==78 ); /* VIRTUAL */
102452      testcase( i==79 ); /* LIMIT */
102453      testcase( i==80 ); /* WHEN */
102454      testcase( i==81 ); /* WHERE */
102455      testcase( i==82 ); /* RENAME */
102456      testcase( i==83 ); /* AFTER */
102457      testcase( i==84 ); /* REPLACE */
102458      testcase( i==85 ); /* AND */
102459      testcase( i==86 ); /* DEFAULT */
102460      testcase( i==87 ); /* AUTOINCREMENT */
102461      testcase( i==88 ); /* TO */
102462      testcase( i==89 ); /* IN */
102463      testcase( i==90 ); /* CAST */
102464      testcase( i==91 ); /* COLUMN */
102465      testcase( i==92 ); /* COMMIT */
102466      testcase( i==93 ); /* CONFLICT */
102467      testcase( i==94 ); /* CROSS */
102468      testcase( i==95 ); /* CURRENT_TIMESTAMP */
102469      testcase( i==96 ); /* CURRENT_TIME */
102470      testcase( i==97 ); /* PRIMARY */
102471      testcase( i==98 ); /* DEFERRED */
102472      testcase( i==99 ); /* DISTINCT */
102473      testcase( i==100 ); /* IS */
102474      testcase( i==101 ); /* DROP */
102475      testcase( i==102 ); /* FAIL */
102476      testcase( i==103 ); /* FROM */
102477      testcase( i==104 ); /* FULL */
102478      testcase( i==105 ); /* GLOB */
102479      testcase( i==106 ); /* BY */
102480      testcase( i==107 ); /* IF */
102481      testcase( i==108 ); /* ISNULL */
102482      testcase( i==109 ); /* ORDER */
102483      testcase( i==110 ); /* RESTRICT */
102484      testcase( i==111 ); /* OUTER */
102485      testcase( i==112 ); /* RIGHT */
102486      testcase( i==113 ); /* ROLLBACK */
102487      testcase( i==114 ); /* ROW */
102488      testcase( i==115 ); /* UNION */
102489      testcase( i==116 ); /* USING */
102490      testcase( i==117 ); /* VACUUM */
102491      testcase( i==118 ); /* VIEW */
102492      testcase( i==119 ); /* INITIALLY */
102493      testcase( i==120 ); /* ALL */
102494      return aCode[i];
102495    }
102496  }
102497  return TK_ID;
102498}
102499SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
102500  return keywordCode((char*)z, n);
102501}
102502#define SQLITE_N_KEYWORD 121
102503
102504/************** End of keywordhash.h *****************************************/
102505/************** Continuing where we left off in tokenize.c *******************/
102506
102507
102508/*
102509** If X is a character that can be used in an identifier then
102510** IdChar(X) will be true.  Otherwise it is false.
102511**
102512** For ASCII, any character with the high-order bit set is
102513** allowed in an identifier.  For 7-bit characters,
102514** sqlite3IsIdChar[X] must be 1.
102515**
102516** For EBCDIC, the rules are more complex but have the same
102517** end result.
102518**
102519** Ticket #1066.  the SQL standard does not allow '$' in the
102520** middle of identfiers.  But many SQL implementations do.
102521** SQLite will allow '$' in identifiers for compatibility.
102522** But the feature is undocumented.
102523*/
102524#ifdef SQLITE_ASCII
102525#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
102526#endif
102527#ifdef SQLITE_EBCDIC
102528SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
102529/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
102530    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
102531    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
102532    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
102533    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
102534    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
102535    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
102536    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
102537    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
102538    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
102539    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
102540    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
102541    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
102542};
102543#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
102544#endif
102545
102546
102547/*
102548** Return the length of the token that begins at z[0].
102549** Store the token type in *tokenType before returning.
102550*/
102551SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
102552  int i, c;
102553  switch( *z ){
102554    case ' ': case '\t': case '\n': case '\f': case '\r': {
102555      testcase( z[0]==' ' );
102556      testcase( z[0]=='\t' );
102557      testcase( z[0]=='\n' );
102558      testcase( z[0]=='\f' );
102559      testcase( z[0]=='\r' );
102560      for(i=1; sqlite3Isspace(z[i]); i++){}
102561      *tokenType = TK_SPACE;
102562      return i;
102563    }
102564    case '-': {
102565      if( z[1]=='-' ){
102566        /* IMP: R-15891-05542 -- syntax diagram for comments */
102567        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
102568        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
102569        return i;
102570      }
102571      *tokenType = TK_MINUS;
102572      return 1;
102573    }
102574    case '(': {
102575      *tokenType = TK_LP;
102576      return 1;
102577    }
102578    case ')': {
102579      *tokenType = TK_RP;
102580      return 1;
102581    }
102582    case ';': {
102583      *tokenType = TK_SEMI;
102584      return 1;
102585    }
102586    case '+': {
102587      *tokenType = TK_PLUS;
102588      return 1;
102589    }
102590    case '*': {
102591      *tokenType = TK_STAR;
102592      return 1;
102593    }
102594    case '/': {
102595      if( z[1]!='*' || z[2]==0 ){
102596        *tokenType = TK_SLASH;
102597        return 1;
102598      }
102599      /* IMP: R-15891-05542 -- syntax diagram for comments */
102600      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
102601      if( c ) i++;
102602      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
102603      return i;
102604    }
102605    case '%': {
102606      *tokenType = TK_REM;
102607      return 1;
102608    }
102609    case '=': {
102610      *tokenType = TK_EQ;
102611      return 1 + (z[1]=='=');
102612    }
102613    case '<': {
102614      if( (c=z[1])=='=' ){
102615        *tokenType = TK_LE;
102616        return 2;
102617      }else if( c=='>' ){
102618        *tokenType = TK_NE;
102619        return 2;
102620      }else if( c=='<' ){
102621        *tokenType = TK_LSHIFT;
102622        return 2;
102623      }else{
102624        *tokenType = TK_LT;
102625        return 1;
102626      }
102627    }
102628    case '>': {
102629      if( (c=z[1])=='=' ){
102630        *tokenType = TK_GE;
102631        return 2;
102632      }else if( c=='>' ){
102633        *tokenType = TK_RSHIFT;
102634        return 2;
102635      }else{
102636        *tokenType = TK_GT;
102637        return 1;
102638      }
102639    }
102640    case '!': {
102641      if( z[1]!='=' ){
102642        *tokenType = TK_ILLEGAL;
102643        return 2;
102644      }else{
102645        *tokenType = TK_NE;
102646        return 2;
102647      }
102648    }
102649    case '|': {
102650      if( z[1]!='|' ){
102651        *tokenType = TK_BITOR;
102652        return 1;
102653      }else{
102654        *tokenType = TK_CONCAT;
102655        return 2;
102656      }
102657    }
102658    case ',': {
102659      *tokenType = TK_COMMA;
102660      return 1;
102661    }
102662    case '&': {
102663      *tokenType = TK_BITAND;
102664      return 1;
102665    }
102666    case '~': {
102667      *tokenType = TK_BITNOT;
102668      return 1;
102669    }
102670    case '`':
102671    case '\'':
102672    case '"': {
102673      int delim = z[0];
102674      testcase( delim=='`' );
102675      testcase( delim=='\'' );
102676      testcase( delim=='"' );
102677      for(i=1; (c=z[i])!=0; i++){
102678        if( c==delim ){
102679          if( z[i+1]==delim ){
102680            i++;
102681          }else{
102682            break;
102683          }
102684        }
102685      }
102686      if( c=='\'' ){
102687        *tokenType = TK_STRING;
102688        return i+1;
102689      }else if( c!=0 ){
102690        *tokenType = TK_ID;
102691        return i+1;
102692      }else{
102693        *tokenType = TK_ILLEGAL;
102694        return i;
102695      }
102696    }
102697    case '.': {
102698#ifndef SQLITE_OMIT_FLOATING_POINT
102699      if( !sqlite3Isdigit(z[1]) )
102700#endif
102701      {
102702        *tokenType = TK_DOT;
102703        return 1;
102704      }
102705      /* If the next character is a digit, this is a floating point
102706      ** number that begins with ".".  Fall thru into the next case */
102707    }
102708    case '0': case '1': case '2': case '3': case '4':
102709    case '5': case '6': case '7': case '8': case '9': {
102710      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
102711      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
102712      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
102713      testcase( z[0]=='9' );
102714      *tokenType = TK_INTEGER;
102715      for(i=0; sqlite3Isdigit(z[i]); i++){}
102716#ifndef SQLITE_OMIT_FLOATING_POINT
102717      if( z[i]=='.' ){
102718        i++;
102719        while( sqlite3Isdigit(z[i]) ){ i++; }
102720        *tokenType = TK_FLOAT;
102721      }
102722      if( (z[i]=='e' || z[i]=='E') &&
102723           ( sqlite3Isdigit(z[i+1])
102724            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
102725           )
102726      ){
102727        i += 2;
102728        while( sqlite3Isdigit(z[i]) ){ i++; }
102729        *tokenType = TK_FLOAT;
102730      }
102731#endif
102732      while( IdChar(z[i]) ){
102733        *tokenType = TK_ILLEGAL;
102734        i++;
102735      }
102736      return i;
102737    }
102738    case '[': {
102739      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
102740      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
102741      return i;
102742    }
102743    case '?': {
102744      *tokenType = TK_VARIABLE;
102745      for(i=1; sqlite3Isdigit(z[i]); i++){}
102746      return i;
102747    }
102748    case '#': {
102749      for(i=1; sqlite3Isdigit(z[i]); i++){}
102750      if( i>1 ){
102751        /* Parameters of the form #NNN (where NNN is a number) are used
102752        ** internally by sqlite3NestedParse.  */
102753        *tokenType = TK_REGISTER;
102754        return i;
102755      }
102756      /* Fall through into the next case if the '#' is not followed by
102757      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
102758    }
102759#ifndef SQLITE_OMIT_TCL_VARIABLE
102760    case '$':
102761#endif
102762    case '@':  /* For compatibility with MS SQL Server */
102763    case ':': {
102764      int n = 0;
102765      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
102766      *tokenType = TK_VARIABLE;
102767      for(i=1; (c=z[i])!=0; i++){
102768        if( IdChar(c) ){
102769          n++;
102770#ifndef SQLITE_OMIT_TCL_VARIABLE
102771        }else if( c=='(' && n>0 ){
102772          do{
102773            i++;
102774          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
102775          if( c==')' ){
102776            i++;
102777          }else{
102778            *tokenType = TK_ILLEGAL;
102779          }
102780          break;
102781        }else if( c==':' && z[i+1]==':' ){
102782          i++;
102783#endif
102784        }else{
102785          break;
102786        }
102787      }
102788      if( n==0 ) *tokenType = TK_ILLEGAL;
102789      return i;
102790    }
102791#ifndef SQLITE_OMIT_BLOB_LITERAL
102792    case 'x': case 'X': {
102793      testcase( z[0]=='x' ); testcase( z[0]=='X' );
102794      if( z[1]=='\'' ){
102795        *tokenType = TK_BLOB;
102796        for(i=2; (c=z[i])!=0 && c!='\''; i++){
102797          if( !sqlite3Isxdigit(c) ){
102798            *tokenType = TK_ILLEGAL;
102799          }
102800        }
102801        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
102802        if( c ) i++;
102803        return i;
102804      }
102805      /* Otherwise fall through to the next case */
102806    }
102807#endif
102808    default: {
102809      if( !IdChar(*z) ){
102810        break;
102811      }
102812      for(i=1; IdChar(z[i]); i++){}
102813      *tokenType = keywordCode((char*)z, i);
102814      return i;
102815    }
102816  }
102817  *tokenType = TK_ILLEGAL;
102818  return 1;
102819}
102820
102821/*
102822** Run the parser on the given SQL string.  The parser structure is
102823** passed in.  An SQLITE_ status code is returned.  If an error occurs
102824** then an and attempt is made to write an error message into
102825** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
102826** error message.
102827*/
102828SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
102829  int nErr = 0;                   /* Number of errors encountered */
102830  int i;                          /* Loop counter */
102831  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
102832  int tokenType;                  /* type of the next token */
102833  int lastTokenParsed = -1;       /* type of the previous token */
102834  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
102835  sqlite3 *db = pParse->db;       /* The database connection */
102836  int mxSqlLen;                   /* Max length of an SQL string */
102837
102838
102839  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
102840  if( db->activeVdbeCnt==0 ){
102841    db->u1.isInterrupted = 0;
102842  }
102843  pParse->rc = SQLITE_OK;
102844  pParse->zTail = zSql;
102845  i = 0;
102846  assert( pzErrMsg!=0 );
102847  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
102848  if( pEngine==0 ){
102849    db->mallocFailed = 1;
102850    return SQLITE_NOMEM;
102851  }
102852  assert( pParse->pNewTable==0 );
102853  assert( pParse->pNewTrigger==0 );
102854  assert( pParse->nVar==0 );
102855  assert( pParse->nVarExpr==0 );
102856  assert( pParse->nVarExprAlloc==0 );
102857  assert( pParse->apVarExpr==0 );
102858  enableLookaside = db->lookaside.bEnabled;
102859  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
102860  while( !db->mallocFailed && zSql[i]!=0 ){
102861    assert( i>=0 );
102862    pParse->sLastToken.z = &zSql[i];
102863    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
102864    i += pParse->sLastToken.n;
102865    if( i>mxSqlLen ){
102866      pParse->rc = SQLITE_TOOBIG;
102867      break;
102868    }
102869    switch( tokenType ){
102870      case TK_SPACE: {
102871        if( db->u1.isInterrupted ){
102872          sqlite3ErrorMsg(pParse, "interrupt");
102873          pParse->rc = SQLITE_INTERRUPT;
102874          goto abort_parse;
102875        }
102876        break;
102877      }
102878      case TK_ILLEGAL: {
102879        sqlite3DbFree(db, *pzErrMsg);
102880        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
102881                        &pParse->sLastToken);
102882        nErr++;
102883        goto abort_parse;
102884      }
102885      case TK_SEMI: {
102886        pParse->zTail = &zSql[i];
102887        /* Fall thru into the default case */
102888      }
102889      default: {
102890        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
102891        lastTokenParsed = tokenType;
102892        if( pParse->rc!=SQLITE_OK ){
102893          goto abort_parse;
102894        }
102895        break;
102896      }
102897    }
102898  }
102899abort_parse:
102900  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
102901    if( lastTokenParsed!=TK_SEMI ){
102902      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
102903      pParse->zTail = &zSql[i];
102904    }
102905    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
102906  }
102907#ifdef YYTRACKMAXSTACKDEPTH
102908  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
102909      sqlite3ParserStackPeak(pEngine)
102910  );
102911#endif /* YYDEBUG */
102912  sqlite3ParserFree(pEngine, sqlite3_free);
102913  db->lookaside.bEnabled = enableLookaside;
102914  if( db->mallocFailed ){
102915    pParse->rc = SQLITE_NOMEM;
102916  }
102917  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
102918    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
102919  }
102920  assert( pzErrMsg!=0 );
102921  if( pParse->zErrMsg ){
102922    *pzErrMsg = pParse->zErrMsg;
102923    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
102924    pParse->zErrMsg = 0;
102925    nErr++;
102926  }
102927  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
102928    sqlite3VdbeDelete(pParse->pVdbe);
102929    pParse->pVdbe = 0;
102930  }
102931#ifndef SQLITE_OMIT_SHARED_CACHE
102932  if( pParse->nested==0 ){
102933    sqlite3DbFree(db, pParse->aTableLock);
102934    pParse->aTableLock = 0;
102935    pParse->nTableLock = 0;
102936  }
102937#endif
102938#ifndef SQLITE_OMIT_VIRTUALTABLE
102939  sqlite3_free(pParse->apVtabLock);
102940#endif
102941
102942  if( !IN_DECLARE_VTAB ){
102943    /* If the pParse->declareVtab flag is set, do not delete any table
102944    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
102945    ** will take responsibility for freeing the Table structure.
102946    */
102947    sqlite3DeleteTable(db, pParse->pNewTable);
102948  }
102949
102950  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
102951  sqlite3DbFree(db, pParse->apVarExpr);
102952  sqlite3DbFree(db, pParse->aAlias);
102953  while( pParse->pAinc ){
102954    AutoincInfo *p = pParse->pAinc;
102955    pParse->pAinc = p->pNext;
102956    sqlite3DbFree(db, p);
102957  }
102958  while( pParse->pZombieTab ){
102959    Table *p = pParse->pZombieTab;
102960    pParse->pZombieTab = p->pNextZombie;
102961    sqlite3DeleteTable(db, p);
102962  }
102963  if( nErr>0 && pParse->rc==SQLITE_OK ){
102964    pParse->rc = SQLITE_ERROR;
102965  }
102966  return nErr;
102967}
102968
102969/************** End of tokenize.c ********************************************/
102970/************** Begin file complete.c ****************************************/
102971/*
102972** 2001 September 15
102973**
102974** The author disclaims copyright to this source code.  In place of
102975** a legal notice, here is a blessing:
102976**
102977**    May you do good and not evil.
102978**    May you find forgiveness for yourself and forgive others.
102979**    May you share freely, never taking more than you give.
102980**
102981*************************************************************************
102982** An tokenizer for SQL
102983**
102984** This file contains C code that implements the sqlite3_complete() API.
102985** This code used to be part of the tokenizer.c source file.  But by
102986** separating it out, the code will be automatically omitted from
102987** static links that do not use it.
102988*/
102989#ifndef SQLITE_OMIT_COMPLETE
102990
102991/*
102992** This is defined in tokenize.c.  We just have to import the definition.
102993*/
102994#ifndef SQLITE_AMALGAMATION
102995#ifdef SQLITE_ASCII
102996#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
102997#endif
102998#ifdef SQLITE_EBCDIC
102999SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
103000#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
103001#endif
103002#endif /* SQLITE_AMALGAMATION */
103003
103004
103005/*
103006** Token types used by the sqlite3_complete() routine.  See the header
103007** comments on that procedure for additional information.
103008*/
103009#define tkSEMI    0
103010#define tkWS      1
103011#define tkOTHER   2
103012#ifndef SQLITE_OMIT_TRIGGER
103013#define tkEXPLAIN 3
103014#define tkCREATE  4
103015#define tkTEMP    5
103016#define tkTRIGGER 6
103017#define tkEND     7
103018#endif
103019
103020/*
103021** Return TRUE if the given SQL string ends in a semicolon.
103022**
103023** Special handling is require for CREATE TRIGGER statements.
103024** Whenever the CREATE TRIGGER keywords are seen, the statement
103025** must end with ";END;".
103026**
103027** This implementation uses a state machine with 8 states:
103028**
103029**   (0) INVALID   We have not yet seen a non-whitespace character.
103030**
103031**   (1) START     At the beginning or end of an SQL statement.  This routine
103032**                 returns 1 if it ends in the START state and 0 if it ends
103033**                 in any other state.
103034**
103035**   (2) NORMAL    We are in the middle of statement which ends with a single
103036**                 semicolon.
103037**
103038**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
103039**                 a statement.
103040**
103041**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
103042**                 statement, possibly preceeded by EXPLAIN and/or followed by
103043**                 TEMP or TEMPORARY
103044**
103045**   (5) TRIGGER   We are in the middle of a trigger definition that must be
103046**                 ended by a semicolon, the keyword END, and another semicolon.
103047**
103048**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
103049**                 the end of a trigger definition.
103050**
103051**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
103052**                 of a trigger difinition.
103053**
103054** Transitions between states above are determined by tokens extracted
103055** from the input.  The following tokens are significant:
103056**
103057**   (0) tkSEMI      A semicolon.
103058**   (1) tkWS        Whitespace.
103059**   (2) tkOTHER     Any other SQL token.
103060**   (3) tkEXPLAIN   The "explain" keyword.
103061**   (4) tkCREATE    The "create" keyword.
103062**   (5) tkTEMP      The "temp" or "temporary" keyword.
103063**   (6) tkTRIGGER   The "trigger" keyword.
103064**   (7) tkEND       The "end" keyword.
103065**
103066** Whitespace never causes a state transition and is always ignored.
103067** This means that a SQL string of all whitespace is invalid.
103068**
103069** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
103070** to recognize the end of a trigger can be omitted.  All we have to do
103071** is look for a semicolon that is not part of an string or comment.
103072*/
103073SQLITE_API int sqlite3_complete(const char *zSql){
103074  u8 state = 0;   /* Current state, using numbers defined in header comment */
103075  u8 token;       /* Value of the next token */
103076
103077#ifndef SQLITE_OMIT_TRIGGER
103078  /* A complex statement machine used to detect the end of a CREATE TRIGGER
103079  ** statement.  This is the normal case.
103080  */
103081  static const u8 trans[8][8] = {
103082                     /* Token:                                                */
103083     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
103084     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
103085     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
103086     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
103087     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
103088     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
103089     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
103090     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
103091     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
103092  };
103093#else
103094  /* If triggers are not supported by this compile then the statement machine
103095  ** used to detect the end of a statement is much simplier
103096  */
103097  static const u8 trans[3][3] = {
103098                     /* Token:           */
103099     /* State:       **  SEMI  WS  OTHER */
103100     /* 0 INVALID: */ {    1,  0,     2, },
103101     /* 1   START: */ {    1,  1,     2, },
103102     /* 2  NORMAL: */ {    1,  2,     2, },
103103  };
103104#endif /* SQLITE_OMIT_TRIGGER */
103105
103106  while( *zSql ){
103107    switch( *zSql ){
103108      case ';': {  /* A semicolon */
103109        token = tkSEMI;
103110        break;
103111      }
103112      case ' ':
103113      case '\r':
103114      case '\t':
103115      case '\n':
103116      case '\f': {  /* White space is ignored */
103117        token = tkWS;
103118        break;
103119      }
103120      case '/': {   /* C-style comments */
103121        if( zSql[1]!='*' ){
103122          token = tkOTHER;
103123          break;
103124        }
103125        zSql += 2;
103126        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
103127        if( zSql[0]==0 ) return 0;
103128        zSql++;
103129        token = tkWS;
103130        break;
103131      }
103132      case '-': {   /* SQL-style comments from "--" to end of line */
103133        if( zSql[1]!='-' ){
103134          token = tkOTHER;
103135          break;
103136        }
103137        while( *zSql && *zSql!='\n' ){ zSql++; }
103138        if( *zSql==0 ) return state==1;
103139        token = tkWS;
103140        break;
103141      }
103142      case '[': {   /* Microsoft-style identifiers in [...] */
103143        zSql++;
103144        while( *zSql && *zSql!=']' ){ zSql++; }
103145        if( *zSql==0 ) return 0;
103146        token = tkOTHER;
103147        break;
103148      }
103149      case '`':     /* Grave-accent quoted symbols used by MySQL */
103150      case '"':     /* single- and double-quoted strings */
103151      case '\'': {
103152        int c = *zSql;
103153        zSql++;
103154        while( *zSql && *zSql!=c ){ zSql++; }
103155        if( *zSql==0 ) return 0;
103156        token = tkOTHER;
103157        break;
103158      }
103159      default: {
103160#ifdef SQLITE_EBCDIC
103161        unsigned char c;
103162#endif
103163        if( IdChar((u8)*zSql) ){
103164          /* Keywords and unquoted identifiers */
103165          int nId;
103166          for(nId=1; IdChar(zSql[nId]); nId++){}
103167#ifdef SQLITE_OMIT_TRIGGER
103168          token = tkOTHER;
103169#else
103170          switch( *zSql ){
103171            case 'c': case 'C': {
103172              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
103173                token = tkCREATE;
103174              }else{
103175                token = tkOTHER;
103176              }
103177              break;
103178            }
103179            case 't': case 'T': {
103180              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
103181                token = tkTRIGGER;
103182              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
103183                token = tkTEMP;
103184              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
103185                token = tkTEMP;
103186              }else{
103187                token = tkOTHER;
103188              }
103189              break;
103190            }
103191            case 'e':  case 'E': {
103192              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
103193                token = tkEND;
103194              }else
103195#ifndef SQLITE_OMIT_EXPLAIN
103196              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
103197                token = tkEXPLAIN;
103198              }else
103199#endif
103200              {
103201                token = tkOTHER;
103202              }
103203              break;
103204            }
103205            default: {
103206              token = tkOTHER;
103207              break;
103208            }
103209          }
103210#endif /* SQLITE_OMIT_TRIGGER */
103211          zSql += nId-1;
103212        }else{
103213          /* Operators and special symbols */
103214          token = tkOTHER;
103215        }
103216        break;
103217      }
103218    }
103219    state = trans[state][token];
103220    zSql++;
103221  }
103222  return state==1;
103223}
103224
103225#ifndef SQLITE_OMIT_UTF16
103226/*
103227** This routine is the same as the sqlite3_complete() routine described
103228** above, except that the parameter is required to be UTF-16 encoded, not
103229** UTF-8.
103230*/
103231SQLITE_API int sqlite3_complete16(const void *zSql){
103232  sqlite3_value *pVal;
103233  char const *zSql8;
103234  int rc = SQLITE_NOMEM;
103235
103236#ifndef SQLITE_OMIT_AUTOINIT
103237  rc = sqlite3_initialize();
103238  if( rc ) return rc;
103239#endif
103240  pVal = sqlite3ValueNew(0);
103241  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
103242  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
103243  if( zSql8 ){
103244    rc = sqlite3_complete(zSql8);
103245  }else{
103246    rc = SQLITE_NOMEM;
103247  }
103248  sqlite3ValueFree(pVal);
103249  return sqlite3ApiExit(0, rc);
103250}
103251#endif /* SQLITE_OMIT_UTF16 */
103252#endif /* SQLITE_OMIT_COMPLETE */
103253
103254/************** End of complete.c ********************************************/
103255/************** Begin file main.c ********************************************/
103256/*
103257** 2001 September 15
103258**
103259** The author disclaims copyright to this source code.  In place of
103260** a legal notice, here is a blessing:
103261**
103262**    May you do good and not evil.
103263**    May you find forgiveness for yourself and forgive others.
103264**    May you share freely, never taking more than you give.
103265**
103266*************************************************************************
103267** Main file for the SQLite library.  The routines in this file
103268** implement the programmer interface to the library.  Routines in
103269** other files are for internal use by SQLite and should not be
103270** accessed by users of the library.
103271*/
103272
103273#ifdef SQLITE_ENABLE_FTS3
103274/************** Include fts3.h in the middle of main.c ***********************/
103275/************** Begin file fts3.h ********************************************/
103276/*
103277** 2006 Oct 10
103278**
103279** The author disclaims copyright to this source code.  In place of
103280** a legal notice, here is a blessing:
103281**
103282**    May you do good and not evil.
103283**    May you find forgiveness for yourself and forgive others.
103284**    May you share freely, never taking more than you give.
103285**
103286******************************************************************************
103287**
103288** This header file is used by programs that want to link against the
103289** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
103290*/
103291
103292#if 0
103293extern "C" {
103294#endif  /* __cplusplus */
103295
103296SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
103297
103298#if 0
103299}  /* extern "C" */
103300#endif  /* __cplusplus */
103301
103302/************** End of fts3.h ************************************************/
103303/************** Continuing where we left off in main.c ***********************/
103304#endif
103305#ifdef SQLITE_ENABLE_RTREE
103306/************** Include rtree.h in the middle of main.c **********************/
103307/************** Begin file rtree.h *******************************************/
103308/*
103309** 2008 May 26
103310**
103311** The author disclaims copyright to this source code.  In place of
103312** a legal notice, here is a blessing:
103313**
103314**    May you do good and not evil.
103315**    May you find forgiveness for yourself and forgive others.
103316**    May you share freely, never taking more than you give.
103317**
103318******************************************************************************
103319**
103320** This header file is used by programs that want to link against the
103321** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
103322*/
103323
103324#if 0
103325extern "C" {
103326#endif  /* __cplusplus */
103327
103328SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
103329
103330#if 0
103331}  /* extern "C" */
103332#endif  /* __cplusplus */
103333
103334/************** End of rtree.h ***********************************************/
103335/************** Continuing where we left off in main.c ***********************/
103336#endif
103337#ifdef SQLITE_ENABLE_ICU
103338/************** Include sqliteicu.h in the middle of main.c ******************/
103339/************** Begin file sqliteicu.h ***************************************/
103340/*
103341** 2008 May 26
103342**
103343** The author disclaims copyright to this source code.  In place of
103344** a legal notice, here is a blessing:
103345**
103346**    May you do good and not evil.
103347**    May you find forgiveness for yourself and forgive others.
103348**    May you share freely, never taking more than you give.
103349**
103350******************************************************************************
103351**
103352** This header file is used by programs that want to link against the
103353** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
103354*/
103355
103356#if 0
103357extern "C" {
103358#endif  /* __cplusplus */
103359
103360SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
103361
103362#if 0
103363}  /* extern "C" */
103364#endif  /* __cplusplus */
103365
103366
103367/************** End of sqliteicu.h *******************************************/
103368/************** Continuing where we left off in main.c ***********************/
103369#endif
103370
103371/*
103372** The version of the library
103373*/
103374#ifndef SQLITE_AMALGAMATION
103375SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
103376#endif
103377SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
103378SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
103379SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
103380SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
103381
103382#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
103383/*
103384** If the following function pointer is not NULL and if
103385** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
103386** I/O active are written using this function.  These messages
103387** are intended for debugging activity only.
103388*/
103389SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
103390#endif
103391
103392/*
103393** If the following global variable points to a string which is the
103394** name of a directory, then that directory will be used to store
103395** temporary files.
103396**
103397** See also the "PRAGMA temp_store_directory" SQL command.
103398*/
103399SQLITE_API char *sqlite3_temp_directory = 0;
103400
103401/*
103402** Initialize SQLite.
103403**
103404** This routine must be called to initialize the memory allocation,
103405** VFS, and mutex subsystems prior to doing any serious work with
103406** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
103407** this routine will be called automatically by key routines such as
103408** sqlite3_open().
103409**
103410** This routine is a no-op except on its very first call for the process,
103411** or for the first call after a call to sqlite3_shutdown.
103412**
103413** The first thread to call this routine runs the initialization to
103414** completion.  If subsequent threads call this routine before the first
103415** thread has finished the initialization process, then the subsequent
103416** threads must block until the first thread finishes with the initialization.
103417**
103418** The first thread might call this routine recursively.  Recursive
103419** calls to this routine should not block, of course.  Otherwise the
103420** initialization process would never complete.
103421**
103422** Let X be the first thread to enter this routine.  Let Y be some other
103423** thread.  Then while the initial invocation of this routine by X is
103424** incomplete, it is required that:
103425**
103426**    *  Calls to this routine from Y must block until the outer-most
103427**       call by X completes.
103428**
103429**    *  Recursive calls to this routine from thread X return immediately
103430**       without blocking.
103431*/
103432SQLITE_API int sqlite3_initialize(void){
103433  sqlite3_mutex *pMaster;                      /* The main static mutex */
103434  int rc;                                      /* Result code */
103435
103436#ifdef SQLITE_OMIT_WSD
103437  rc = sqlite3_wsd_init(4096, 24);
103438  if( rc!=SQLITE_OK ){
103439    return rc;
103440  }
103441#endif
103442
103443  /* If SQLite is already completely initialized, then this call
103444  ** to sqlite3_initialize() should be a no-op.  But the initialization
103445  ** must be complete.  So isInit must not be set until the very end
103446  ** of this routine.
103447  */
103448  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
103449
103450  /* Make sure the mutex subsystem is initialized.  If unable to
103451  ** initialize the mutex subsystem, return early with the error.
103452  ** If the system is so sick that we are unable to allocate a mutex,
103453  ** there is not much SQLite is going to be able to do.
103454  **
103455  ** The mutex subsystem must take care of serializing its own
103456  ** initialization.
103457  */
103458  rc = sqlite3MutexInit();
103459  if( rc ) return rc;
103460
103461  /* Initialize the malloc() system and the recursive pInitMutex mutex.
103462  ** This operation is protected by the STATIC_MASTER mutex.  Note that
103463  ** MutexAlloc() is called for a static mutex prior to initializing the
103464  ** malloc subsystem - this implies that the allocation of a static
103465  ** mutex must not require support from the malloc subsystem.
103466  */
103467  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
103468  sqlite3_mutex_enter(pMaster);
103469  sqlite3GlobalConfig.isMutexInit = 1;
103470  if( !sqlite3GlobalConfig.isMallocInit ){
103471    rc = sqlite3MallocInit();
103472  }
103473  if( rc==SQLITE_OK ){
103474    sqlite3GlobalConfig.isMallocInit = 1;
103475    if( !sqlite3GlobalConfig.pInitMutex ){
103476      sqlite3GlobalConfig.pInitMutex =
103477           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
103478      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
103479        rc = SQLITE_NOMEM;
103480      }
103481    }
103482  }
103483  if( rc==SQLITE_OK ){
103484    sqlite3GlobalConfig.nRefInitMutex++;
103485  }
103486  sqlite3_mutex_leave(pMaster);
103487
103488  /* If rc is not SQLITE_OK at this point, then either the malloc
103489  ** subsystem could not be initialized or the system failed to allocate
103490  ** the pInitMutex mutex. Return an error in either case.  */
103491  if( rc!=SQLITE_OK ){
103492    return rc;
103493  }
103494
103495  /* Do the rest of the initialization under the recursive mutex so
103496  ** that we will be able to handle recursive calls into
103497  ** sqlite3_initialize().  The recursive calls normally come through
103498  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
103499  ** recursive calls might also be possible.
103500  */
103501  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
103502  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
103503    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
103504    sqlite3GlobalConfig.inProgress = 1;
103505    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
103506    sqlite3RegisterGlobalFunctions();
103507    if( sqlite3GlobalConfig.isPCacheInit==0 ){
103508      rc = sqlite3PcacheInitialize();
103509    }
103510    if( rc==SQLITE_OK ){
103511      sqlite3GlobalConfig.isPCacheInit = 1;
103512      rc = sqlite3OsInit();
103513    }
103514    if( rc==SQLITE_OK ){
103515      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
103516          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
103517      sqlite3GlobalConfig.isInit = 1;
103518    }
103519    sqlite3GlobalConfig.inProgress = 0;
103520  }
103521  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
103522
103523  /* Go back under the static mutex and clean up the recursive
103524  ** mutex to prevent a resource leak.
103525  */
103526  sqlite3_mutex_enter(pMaster);
103527  sqlite3GlobalConfig.nRefInitMutex--;
103528  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
103529    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
103530    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
103531    sqlite3GlobalConfig.pInitMutex = 0;
103532  }
103533  sqlite3_mutex_leave(pMaster);
103534
103535  /* The following is just a sanity check to make sure SQLite has
103536  ** been compiled correctly.  It is important to run this code, but
103537  ** we don't want to run it too often and soak up CPU cycles for no
103538  ** reason.  So we run it once during initialization.
103539  */
103540#ifndef NDEBUG
103541#ifndef SQLITE_OMIT_FLOATING_POINT
103542  /* This section of code's only "output" is via assert() statements. */
103543  if ( rc==SQLITE_OK ){
103544    u64 x = (((u64)1)<<63)-1;
103545    double y;
103546    assert(sizeof(x)==8);
103547    assert(sizeof(x)==sizeof(y));
103548    memcpy(&y, &x, 8);
103549    assert( sqlite3IsNaN(y) );
103550  }
103551#endif
103552#endif
103553
103554  return rc;
103555}
103556
103557/*
103558** Undo the effects of sqlite3_initialize().  Must not be called while
103559** there are outstanding database connections or memory allocations or
103560** while any part of SQLite is otherwise in use in any thread.  This
103561** routine is not threadsafe.  But it is safe to invoke this routine
103562** on when SQLite is already shut down.  If SQLite is already shut down
103563** when this routine is invoked, then this routine is a harmless no-op.
103564*/
103565SQLITE_API int sqlite3_shutdown(void){
103566  if( sqlite3GlobalConfig.isInit ){
103567    sqlite3_os_end();
103568    sqlite3_reset_auto_extension();
103569    sqlite3GlobalConfig.isInit = 0;
103570  }
103571  if( sqlite3GlobalConfig.isPCacheInit ){
103572    sqlite3PcacheShutdown();
103573    sqlite3GlobalConfig.isPCacheInit = 0;
103574  }
103575  if( sqlite3GlobalConfig.isMallocInit ){
103576    sqlite3MallocEnd();
103577    sqlite3GlobalConfig.isMallocInit = 0;
103578  }
103579  if( sqlite3GlobalConfig.isMutexInit ){
103580    sqlite3MutexEnd();
103581    sqlite3GlobalConfig.isMutexInit = 0;
103582  }
103583
103584  return SQLITE_OK;
103585}
103586
103587/*
103588** This API allows applications to modify the global configuration of
103589** the SQLite library at run-time.
103590**
103591** This routine should only be called when there are no outstanding
103592** database connections or memory allocations.  This routine is not
103593** threadsafe.  Failure to heed these warnings can lead to unpredictable
103594** behavior.
103595*/
103596SQLITE_API int sqlite3_config(int op, ...){
103597  va_list ap;
103598  int rc = SQLITE_OK;
103599
103600  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
103601  ** the SQLite library is in use. */
103602  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
103603
103604  va_start(ap, op);
103605  switch( op ){
103606
103607    /* Mutex configuration options are only available in a threadsafe
103608    ** compile.
103609    */
103610#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
103611    case SQLITE_CONFIG_SINGLETHREAD: {
103612      /* Disable all mutexing */
103613      sqlite3GlobalConfig.bCoreMutex = 0;
103614      sqlite3GlobalConfig.bFullMutex = 0;
103615      break;
103616    }
103617    case SQLITE_CONFIG_MULTITHREAD: {
103618      /* Disable mutexing of database connections */
103619      /* Enable mutexing of core data structures */
103620      sqlite3GlobalConfig.bCoreMutex = 1;
103621      sqlite3GlobalConfig.bFullMutex = 0;
103622      break;
103623    }
103624    case SQLITE_CONFIG_SERIALIZED: {
103625      /* Enable all mutexing */
103626      sqlite3GlobalConfig.bCoreMutex = 1;
103627      sqlite3GlobalConfig.bFullMutex = 1;
103628      break;
103629    }
103630    case SQLITE_CONFIG_MUTEX: {
103631      /* Specify an alternative mutex implementation */
103632      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
103633      break;
103634    }
103635    case SQLITE_CONFIG_GETMUTEX: {
103636      /* Retrieve the current mutex implementation */
103637      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
103638      break;
103639    }
103640#endif
103641
103642
103643    case SQLITE_CONFIG_MALLOC: {
103644      /* Specify an alternative malloc implementation */
103645      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
103646      break;
103647    }
103648    case SQLITE_CONFIG_GETMALLOC: {
103649      /* Retrieve the current malloc() implementation */
103650      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
103651      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
103652      break;
103653    }
103654    case SQLITE_CONFIG_MEMSTATUS: {
103655      /* Enable or disable the malloc status collection */
103656      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
103657      break;
103658    }
103659    case SQLITE_CONFIG_SCRATCH: {
103660      /* Designate a buffer for scratch memory space */
103661      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
103662      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
103663      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
103664      break;
103665    }
103666    case SQLITE_CONFIG_PAGECACHE: {
103667      /* Designate a buffer for page cache memory space */
103668      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
103669      sqlite3GlobalConfig.szPage = va_arg(ap, int);
103670      sqlite3GlobalConfig.nPage = va_arg(ap, int);
103671      break;
103672    }
103673
103674    case SQLITE_CONFIG_PCACHE: {
103675      /* Specify an alternative page cache implementation */
103676      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
103677      break;
103678    }
103679
103680    case SQLITE_CONFIG_GETPCACHE: {
103681      if( sqlite3GlobalConfig.pcache.xInit==0 ){
103682        sqlite3PCacheSetDefault();
103683      }
103684      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
103685      break;
103686    }
103687
103688#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
103689    case SQLITE_CONFIG_HEAP: {
103690      /* Designate a buffer for heap memory space */
103691      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
103692      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
103693      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
103694
103695      if( sqlite3GlobalConfig.pHeap==0 ){
103696        /* If the heap pointer is NULL, then restore the malloc implementation
103697        ** back to NULL pointers too.  This will cause the malloc to go
103698        ** back to its default implementation when sqlite3_initialize() is
103699        ** run.
103700        */
103701        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
103702      }else{
103703        /* The heap pointer is not NULL, then install one of the
103704        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
103705        ** ENABLE_MEMSYS5 is defined, return an error.
103706        */
103707#ifdef SQLITE_ENABLE_MEMSYS3
103708        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
103709#endif
103710#ifdef SQLITE_ENABLE_MEMSYS5
103711        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
103712#endif
103713      }
103714      break;
103715    }
103716#endif
103717
103718    case SQLITE_CONFIG_LOOKASIDE: {
103719      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
103720      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
103721      break;
103722    }
103723
103724    /* Record a pointer to the logger funcction and its first argument.
103725    ** The default is NULL.  Logging is disabled if the function pointer is
103726    ** NULL.
103727    */
103728    case SQLITE_CONFIG_LOG: {
103729      /* MSVC is picky about pulling func ptrs from va lists.
103730      ** http://support.microsoft.com/kb/47961
103731      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
103732      */
103733      typedef void(*LOGFUNC_t)(void*,int,const char*);
103734      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
103735      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
103736      break;
103737    }
103738
103739    default: {
103740      rc = SQLITE_ERROR;
103741      break;
103742    }
103743  }
103744  va_end(ap);
103745  return rc;
103746}
103747
103748/*
103749** Set up the lookaside buffers for a database connection.
103750** Return SQLITE_OK on success.
103751** If lookaside is already active, return SQLITE_BUSY.
103752**
103753** The sz parameter is the number of bytes in each lookaside slot.
103754** The cnt parameter is the number of slots.  If pStart is NULL the
103755** space for the lookaside memory is obtained from sqlite3_malloc().
103756** If pStart is not NULL then it is sz*cnt bytes of memory to use for
103757** the lookaside memory.
103758*/
103759static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
103760  void *pStart;
103761  if( db->lookaside.nOut ){
103762    return SQLITE_BUSY;
103763  }
103764  /* Free any existing lookaside buffer for this handle before
103765  ** allocating a new one so we don't have to have space for
103766  ** both at the same time.
103767  */
103768  if( db->lookaside.bMalloced ){
103769    sqlite3_free(db->lookaside.pStart);
103770  }
103771  /* The size of a lookaside slot needs to be larger than a pointer
103772  ** to be useful.
103773  */
103774  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
103775  if( cnt<0 ) cnt = 0;
103776  if( sz==0 || cnt==0 ){
103777    sz = 0;
103778    pStart = 0;
103779  }else if( pBuf==0 ){
103780    sz = ROUND8(sz);
103781    sqlite3BeginBenignMalloc();
103782    pStart = sqlite3Malloc( sz*cnt );
103783    sqlite3EndBenignMalloc();
103784  }else{
103785    sz = ROUNDDOWN8(sz);
103786    pStart = pBuf;
103787  }
103788  db->lookaside.pStart = pStart;
103789  db->lookaside.pFree = 0;
103790  db->lookaside.sz = (u16)sz;
103791  if( pStart ){
103792    int i;
103793    LookasideSlot *p;
103794    assert( sz > (int)sizeof(LookasideSlot*) );
103795    p = (LookasideSlot*)pStart;
103796    for(i=cnt-1; i>=0; i--){
103797      p->pNext = db->lookaside.pFree;
103798      db->lookaside.pFree = p;
103799      p = (LookasideSlot*)&((u8*)p)[sz];
103800    }
103801    db->lookaside.pEnd = p;
103802    db->lookaside.bEnabled = 1;
103803    db->lookaside.bMalloced = pBuf==0 ?1:0;
103804  }else{
103805    db->lookaside.pEnd = 0;
103806    db->lookaside.bEnabled = 0;
103807    db->lookaside.bMalloced = 0;
103808  }
103809  return SQLITE_OK;
103810}
103811
103812/*
103813** Return the mutex associated with a database connection.
103814*/
103815SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
103816  return db->mutex;
103817}
103818
103819/*
103820** Configuration settings for an individual database connection
103821*/
103822SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
103823  va_list ap;
103824  int rc;
103825  va_start(ap, op);
103826  switch( op ){
103827    case SQLITE_DBCONFIG_LOOKASIDE: {
103828      void *pBuf = va_arg(ap, void*);
103829      int sz = va_arg(ap, int);
103830      int cnt = va_arg(ap, int);
103831      rc = setupLookaside(db, pBuf, sz, cnt);
103832      break;
103833    }
103834    default: {
103835      rc = SQLITE_ERROR;
103836      break;
103837    }
103838  }
103839  va_end(ap);
103840  return rc;
103841}
103842
103843
103844/*
103845** Return true if the buffer z[0..n-1] contains all spaces.
103846*/
103847static int allSpaces(const char *z, int n){
103848  while( n>0 && z[n-1]==' ' ){ n--; }
103849  return n==0;
103850}
103851
103852/*
103853** This is the default collating function named "BINARY" which is always
103854** available.
103855**
103856** If the padFlag argument is not NULL then space padding at the end
103857** of strings is ignored.  This implements the RTRIM collation.
103858*/
103859static int binCollFunc(
103860  void *padFlag,
103861  int nKey1, const void *pKey1,
103862  int nKey2, const void *pKey2
103863){
103864  int rc, n;
103865  n = nKey1<nKey2 ? nKey1 : nKey2;
103866  rc = memcmp(pKey1, pKey2, n);
103867  if( rc==0 ){
103868    if( padFlag
103869     && allSpaces(((char*)pKey1)+n, nKey1-n)
103870     && allSpaces(((char*)pKey2)+n, nKey2-n)
103871    ){
103872      /* Leave rc unchanged at 0 */
103873    }else{
103874      rc = nKey1 - nKey2;
103875    }
103876  }
103877  return rc;
103878}
103879
103880/*
103881** Another built-in collating sequence: NOCASE.
103882**
103883** This collating sequence is intended to be used for "case independant
103884** comparison". SQLite's knowledge of upper and lower case equivalents
103885** extends only to the 26 characters used in the English language.
103886**
103887** At the moment there is only a UTF-8 implementation.
103888*/
103889static int nocaseCollatingFunc(
103890  void *NotUsed,
103891  int nKey1, const void *pKey1,
103892  int nKey2, const void *pKey2
103893){
103894  int r = sqlite3StrNICmp(
103895      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
103896  UNUSED_PARAMETER(NotUsed);
103897  if( 0==r ){
103898    r = nKey1-nKey2;
103899  }
103900  return r;
103901}
103902
103903/*
103904** Return the ROWID of the most recent insert
103905*/
103906SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
103907  return db->lastRowid;
103908}
103909
103910/*
103911** Return the number of changes in the most recent call to sqlite3_exec().
103912*/
103913SQLITE_API int sqlite3_changes(sqlite3 *db){
103914  return db->nChange;
103915}
103916
103917/*
103918** Return the number of changes since the database handle was opened.
103919*/
103920SQLITE_API int sqlite3_total_changes(sqlite3 *db){
103921  return db->nTotalChange;
103922}
103923
103924/*
103925** Close all open savepoints. This function only manipulates fields of the
103926** database handle object, it does not close any savepoints that may be open
103927** at the b-tree/pager level.
103928*/
103929SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
103930  while( db->pSavepoint ){
103931    Savepoint *pTmp = db->pSavepoint;
103932    db->pSavepoint = pTmp->pNext;
103933    sqlite3DbFree(db, pTmp);
103934  }
103935  db->nSavepoint = 0;
103936  db->nStatement = 0;
103937  db->isTransactionSavepoint = 0;
103938}
103939
103940/*
103941** Close an existing SQLite database
103942*/
103943SQLITE_API int sqlite3_close(sqlite3 *db){
103944  HashElem *i;
103945  int j;
103946
103947  if( !db ){
103948    return SQLITE_OK;
103949  }
103950  if( !sqlite3SafetyCheckSickOrOk(db) ){
103951    return SQLITE_MISUSE_BKPT;
103952  }
103953  sqlite3_mutex_enter(db->mutex);
103954
103955  sqlite3ResetInternalSchema(db, 0);
103956
103957  /* If a transaction is open, the ResetInternalSchema() call above
103958  ** will not have called the xDisconnect() method on any virtual
103959  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
103960  ** call will do so. We need to do this before the check for active
103961  ** SQL statements below, as the v-table implementation may be storing
103962  ** some prepared statements internally.
103963  */
103964  sqlite3VtabRollback(db);
103965
103966  /* If there are any outstanding VMs, return SQLITE_BUSY. */
103967  if( db->pVdbe ){
103968    sqlite3Error(db, SQLITE_BUSY,
103969        "unable to close due to unfinalised statements");
103970    sqlite3_mutex_leave(db->mutex);
103971    return SQLITE_BUSY;
103972  }
103973  assert( sqlite3SafetyCheckSickOrOk(db) );
103974
103975  for(j=0; j<db->nDb; j++){
103976    Btree *pBt = db->aDb[j].pBt;
103977    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
103978      sqlite3Error(db, SQLITE_BUSY,
103979          "unable to close due to unfinished backup operation");
103980      sqlite3_mutex_leave(db->mutex);
103981      return SQLITE_BUSY;
103982    }
103983  }
103984
103985  /* Free any outstanding Savepoint structures. */
103986  sqlite3CloseSavepoints(db);
103987
103988  for(j=0; j<db->nDb; j++){
103989    struct Db *pDb = &db->aDb[j];
103990    if( pDb->pBt ){
103991      sqlite3BtreeClose(pDb->pBt);
103992      pDb->pBt = 0;
103993      if( j!=1 ){
103994        pDb->pSchema = 0;
103995      }
103996    }
103997  }
103998  sqlite3ResetInternalSchema(db, 0);
103999
104000  /* Tell the code in notify.c that the connection no longer holds any
104001  ** locks and does not require any further unlock-notify callbacks.
104002  */
104003  sqlite3ConnectionClosed(db);
104004
104005  assert( db->nDb<=2 );
104006  assert( db->aDb==db->aDbStatic );
104007  for(j=0; j<ArraySize(db->aFunc.a); j++){
104008    FuncDef *pNext, *pHash, *p;
104009    for(p=db->aFunc.a[j]; p; p=pHash){
104010      pHash = p->pHash;
104011      while( p ){
104012        pNext = p->pNext;
104013        sqlite3DbFree(db, p);
104014        p = pNext;
104015      }
104016    }
104017  }
104018  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
104019    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
104020    /* Invoke any destructors registered for collation sequence user data. */
104021    for(j=0; j<3; j++){
104022      if( pColl[j].xDel ){
104023        pColl[j].xDel(pColl[j].pUser);
104024      }
104025    }
104026    sqlite3DbFree(db, pColl);
104027  }
104028  sqlite3HashClear(&db->aCollSeq);
104029#ifndef SQLITE_OMIT_VIRTUALTABLE
104030  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
104031    Module *pMod = (Module *)sqliteHashData(i);
104032    if( pMod->xDestroy ){
104033      pMod->xDestroy(pMod->pAux);
104034    }
104035    sqlite3DbFree(db, pMod);
104036  }
104037  sqlite3HashClear(&db->aModule);
104038#endif
104039
104040  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
104041  if( db->pErr ){
104042    sqlite3ValueFree(db->pErr);
104043  }
104044  sqlite3CloseExtensions(db);
104045
104046  db->magic = SQLITE_MAGIC_ERROR;
104047
104048  /* The temp-database schema is allocated differently from the other schema
104049  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
104050  ** So it needs to be freed here. Todo: Why not roll the temp schema into
104051  ** the same sqliteMalloc() as the one that allocates the database
104052  ** structure?
104053  */
104054  sqlite3DbFree(db, db->aDb[1].pSchema);
104055  sqlite3_mutex_leave(db->mutex);
104056  db->magic = SQLITE_MAGIC_CLOSED;
104057  sqlite3_mutex_free(db->mutex);
104058  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
104059  if( db->lookaside.bMalloced ){
104060    sqlite3_free(db->lookaside.pStart);
104061  }
104062  sqlite3_free(db);
104063  return SQLITE_OK;
104064}
104065
104066/*
104067** Rollback all database files.
104068*/
104069SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
104070  int i;
104071  int inTrans = 0;
104072  assert( sqlite3_mutex_held(db->mutex) );
104073  sqlite3BeginBenignMalloc();
104074  for(i=0; i<db->nDb; i++){
104075    if( db->aDb[i].pBt ){
104076      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
104077        inTrans = 1;
104078      }
104079      sqlite3BtreeRollback(db->aDb[i].pBt);
104080      db->aDb[i].inTrans = 0;
104081    }
104082  }
104083  sqlite3VtabRollback(db);
104084  sqlite3EndBenignMalloc();
104085
104086  if( db->flags&SQLITE_InternChanges ){
104087    sqlite3ExpirePreparedStatements(db);
104088    sqlite3ResetInternalSchema(db, 0);
104089  }
104090
104091  /* Any deferred constraint violations have now been resolved. */
104092  db->nDeferredCons = 0;
104093
104094  /* If one has been configured, invoke the rollback-hook callback */
104095  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
104096    db->xRollbackCallback(db->pRollbackArg);
104097  }
104098}
104099
104100/*
104101** Return a static string that describes the kind of error specified in the
104102** argument.
104103*/
104104SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
104105  static const char* const aMsg[] = {
104106    /* SQLITE_OK          */ "not an error",
104107    /* SQLITE_ERROR       */ "SQL logic error or missing database",
104108    /* SQLITE_INTERNAL    */ 0,
104109    /* SQLITE_PERM        */ "access permission denied",
104110    /* SQLITE_ABORT       */ "callback requested query abort",
104111    /* SQLITE_BUSY        */ "database is locked",
104112    /* SQLITE_LOCKED      */ "database table is locked",
104113    /* SQLITE_NOMEM       */ "out of memory",
104114    /* SQLITE_READONLY    */ "attempt to write a readonly database",
104115    /* SQLITE_INTERRUPT   */ "interrupted",
104116    /* SQLITE_IOERR       */ "disk I/O error",
104117    /* SQLITE_CORRUPT     */ "database disk image is malformed",
104118    /* SQLITE_NOTFOUND    */ 0,
104119    /* SQLITE_FULL        */ "database or disk is full",
104120    /* SQLITE_CANTOPEN    */ "unable to open database file",
104121    /* SQLITE_PROTOCOL    */ "locking protocol",
104122    /* SQLITE_EMPTY       */ "table contains no data",
104123    /* SQLITE_SCHEMA      */ "database schema has changed",
104124    /* SQLITE_TOOBIG      */ "string or blob too big",
104125    /* SQLITE_CONSTRAINT  */ "constraint failed",
104126    /* SQLITE_MISMATCH    */ "datatype mismatch",
104127    /* SQLITE_MISUSE      */ "library routine called out of sequence",
104128    /* SQLITE_NOLFS       */ "large file support is disabled",
104129    /* SQLITE_AUTH        */ "authorization denied",
104130    /* SQLITE_FORMAT      */ "auxiliary database format error",
104131    /* SQLITE_RANGE       */ "bind or column index out of range",
104132    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
104133  };
104134  rc &= 0xff;
104135  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
104136    return aMsg[rc];
104137  }else{
104138    return "unknown error";
104139  }
104140}
104141
104142/*
104143** This routine implements a busy callback that sleeps and tries
104144** again until a timeout value is reached.  The timeout value is
104145** an integer number of milliseconds passed in as the first
104146** argument.
104147*/
104148static int sqliteDefaultBusyCallback(
104149 void *ptr,               /* Database connection */
104150 int count                /* Number of times table has been busy */
104151){
104152#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
104153  static const u8 delays[] =
104154     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
104155  static const u8 totals[] =
104156     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
104157# define NDELAY (sizeof(delays)/sizeof(delays[0]))
104158  sqlite3 *db = (sqlite3 *)ptr;
104159  int timeout = db->busyTimeout;
104160  int delay, prior;
104161
104162  assert( count>=0 );
104163  if( count < NDELAY ){
104164    delay = delays[count];
104165    prior = totals[count];
104166  }else{
104167    delay = delays[NDELAY-1];
104168    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
104169  }
104170  if( prior + delay > timeout ){
104171    delay = timeout - prior;
104172    if( delay<=0 ) return 0;
104173  }
104174  sqlite3OsSleep(db->pVfs, delay*1000);
104175  return 1;
104176#else
104177  sqlite3 *db = (sqlite3 *)ptr;
104178  int timeout = ((sqlite3 *)ptr)->busyTimeout;
104179  if( (count+1)*1000 > timeout ){
104180    return 0;
104181  }
104182  sqlite3OsSleep(db->pVfs, 1000000);
104183  return 1;
104184#endif
104185}
104186
104187/*
104188** Invoke the given busy handler.
104189**
104190** This routine is called when an operation failed with a lock.
104191** If this routine returns non-zero, the lock is retried.  If it
104192** returns 0, the operation aborts with an SQLITE_BUSY error.
104193*/
104194SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
104195  int rc;
104196  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
104197  rc = p->xFunc(p->pArg, p->nBusy);
104198  if( rc==0 ){
104199    p->nBusy = -1;
104200  }else{
104201    p->nBusy++;
104202  }
104203  return rc;
104204}
104205
104206/*
104207** This routine sets the busy callback for an Sqlite database to the
104208** given callback function with the given argument.
104209*/
104210SQLITE_API int sqlite3_busy_handler(
104211  sqlite3 *db,
104212  int (*xBusy)(void*,int),
104213  void *pArg
104214){
104215  sqlite3_mutex_enter(db->mutex);
104216  db->busyHandler.xFunc = xBusy;
104217  db->busyHandler.pArg = pArg;
104218  db->busyHandler.nBusy = 0;
104219  sqlite3_mutex_leave(db->mutex);
104220  return SQLITE_OK;
104221}
104222
104223#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
104224/*
104225** This routine sets the progress callback for an Sqlite database to the
104226** given callback function with the given argument. The progress callback will
104227** be invoked every nOps opcodes.
104228*/
104229SQLITE_API void sqlite3_progress_handler(
104230  sqlite3 *db,
104231  int nOps,
104232  int (*xProgress)(void*),
104233  void *pArg
104234){
104235  sqlite3_mutex_enter(db->mutex);
104236  if( nOps>0 ){
104237    db->xProgress = xProgress;
104238    db->nProgressOps = nOps;
104239    db->pProgressArg = pArg;
104240  }else{
104241    db->xProgress = 0;
104242    db->nProgressOps = 0;
104243    db->pProgressArg = 0;
104244  }
104245  sqlite3_mutex_leave(db->mutex);
104246}
104247#endif
104248
104249
104250/*
104251** This routine installs a default busy handler that waits for the
104252** specified number of milliseconds before returning 0.
104253*/
104254SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
104255  if( ms>0 ){
104256    db->busyTimeout = ms;
104257    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
104258  }else{
104259    sqlite3_busy_handler(db, 0, 0);
104260  }
104261  return SQLITE_OK;
104262}
104263
104264/*
104265** Cause any pending operation to stop at its earliest opportunity.
104266*/
104267SQLITE_API void sqlite3_interrupt(sqlite3 *db){
104268  db->u1.isInterrupted = 1;
104269}
104270
104271
104272/*
104273** This function is exactly the same as sqlite3_create_function(), except
104274** that it is designed to be called by internal code. The difference is
104275** that if a malloc() fails in sqlite3_create_function(), an error code
104276** is returned and the mallocFailed flag cleared.
104277*/
104278SQLITE_PRIVATE int sqlite3CreateFunc(
104279  sqlite3 *db,
104280  const char *zFunctionName,
104281  int nArg,
104282  int enc,
104283  void *pUserData,
104284  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104285  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104286  void (*xFinal)(sqlite3_context*)
104287){
104288  FuncDef *p;
104289  int nName;
104290
104291  assert( sqlite3_mutex_held(db->mutex) );
104292  if( zFunctionName==0 ||
104293      (xFunc && (xFinal || xStep)) ||
104294      (!xFunc && (xFinal && !xStep)) ||
104295      (!xFunc && (!xFinal && xStep)) ||
104296      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
104297      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
104298    return SQLITE_MISUSE_BKPT;
104299  }
104300
104301#ifndef SQLITE_OMIT_UTF16
104302  /* If SQLITE_UTF16 is specified as the encoding type, transform this
104303  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
104304  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
104305  **
104306  ** If SQLITE_ANY is specified, add three versions of the function
104307  ** to the hash table.
104308  */
104309  if( enc==SQLITE_UTF16 ){
104310    enc = SQLITE_UTF16NATIVE;
104311  }else if( enc==SQLITE_ANY ){
104312    int rc;
104313    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
104314         pUserData, xFunc, xStep, xFinal);
104315    if( rc==SQLITE_OK ){
104316      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
104317          pUserData, xFunc, xStep, xFinal);
104318    }
104319    if( rc!=SQLITE_OK ){
104320      return rc;
104321    }
104322    enc = SQLITE_UTF16BE;
104323  }
104324#else
104325  enc = SQLITE_UTF8;
104326#endif
104327
104328  /* Check if an existing function is being overridden or deleted. If so,
104329  ** and there are active VMs, then return SQLITE_BUSY. If a function
104330  ** is being overridden/deleted but there are no active VMs, allow the
104331  ** operation to continue but invalidate all precompiled statements.
104332  */
104333  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
104334  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
104335    if( db->activeVdbeCnt ){
104336      sqlite3Error(db, SQLITE_BUSY,
104337        "unable to delete/modify user-function due to active statements");
104338      assert( !db->mallocFailed );
104339      return SQLITE_BUSY;
104340    }else{
104341      sqlite3ExpirePreparedStatements(db);
104342    }
104343  }
104344
104345  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
104346  assert(p || db->mallocFailed);
104347  if( !p ){
104348    return SQLITE_NOMEM;
104349  }
104350  p->flags = 0;
104351  p->xFunc = xFunc;
104352  p->xStep = xStep;
104353  p->xFinalize = xFinal;
104354  p->pUserData = pUserData;
104355  p->nArg = (u16)nArg;
104356  return SQLITE_OK;
104357}
104358
104359/*
104360** Create new user functions.
104361*/
104362SQLITE_API int sqlite3_create_function(
104363  sqlite3 *db,
104364  const char *zFunctionName,
104365  int nArg,
104366  int enc,
104367  void *p,
104368  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104369  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104370  void (*xFinal)(sqlite3_context*)
104371){
104372  int rc;
104373  sqlite3_mutex_enter(db->mutex);
104374  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
104375  rc = sqlite3ApiExit(db, rc);
104376  sqlite3_mutex_leave(db->mutex);
104377  return rc;
104378}
104379
104380#ifndef SQLITE_OMIT_UTF16
104381SQLITE_API int sqlite3_create_function16(
104382  sqlite3 *db,
104383  const void *zFunctionName,
104384  int nArg,
104385  int eTextRep,
104386  void *p,
104387  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
104388  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
104389  void (*xFinal)(sqlite3_context*)
104390){
104391  int rc;
104392  char *zFunc8;
104393  sqlite3_mutex_enter(db->mutex);
104394  assert( !db->mallocFailed );
104395  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
104396  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
104397  sqlite3DbFree(db, zFunc8);
104398  rc = sqlite3ApiExit(db, rc);
104399  sqlite3_mutex_leave(db->mutex);
104400  return rc;
104401}
104402#endif
104403
104404
104405/*
104406** Declare that a function has been overloaded by a virtual table.
104407**
104408** If the function already exists as a regular global function, then
104409** this routine is a no-op.  If the function does not exist, then create
104410** a new one that always throws a run-time error.
104411**
104412** When virtual tables intend to provide an overloaded function, they
104413** should call this routine to make sure the global function exists.
104414** A global function must exist in order for name resolution to work
104415** properly.
104416*/
104417SQLITE_API int sqlite3_overload_function(
104418  sqlite3 *db,
104419  const char *zName,
104420  int nArg
104421){
104422  int nName = sqlite3Strlen30(zName);
104423  int rc;
104424  sqlite3_mutex_enter(db->mutex);
104425  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
104426    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
104427                      0, sqlite3InvalidFunction, 0, 0);
104428  }
104429  rc = sqlite3ApiExit(db, SQLITE_OK);
104430  sqlite3_mutex_leave(db->mutex);
104431  return rc;
104432}
104433
104434#ifndef SQLITE_OMIT_TRACE
104435/*
104436** Register a trace function.  The pArg from the previously registered trace
104437** is returned.
104438**
104439** A NULL trace function means that no tracing is executes.  A non-NULL
104440** trace is a pointer to a function that is invoked at the start of each
104441** SQL statement.
104442*/
104443SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
104444  void *pOld;
104445  sqlite3_mutex_enter(db->mutex);
104446  pOld = db->pTraceArg;
104447  db->xTrace = xTrace;
104448  db->pTraceArg = pArg;
104449  sqlite3_mutex_leave(db->mutex);
104450  return pOld;
104451}
104452/*
104453** Register a profile function.  The pArg from the previously registered
104454** profile function is returned.
104455**
104456** A NULL profile function means that no profiling is executes.  A non-NULL
104457** profile is a pointer to a function that is invoked at the conclusion of
104458** each SQL statement that is run.
104459*/
104460SQLITE_API void *sqlite3_profile(
104461  sqlite3 *db,
104462  void (*xProfile)(void*,const char*,sqlite_uint64),
104463  void *pArg
104464){
104465  void *pOld;
104466  sqlite3_mutex_enter(db->mutex);
104467  pOld = db->pProfileArg;
104468  db->xProfile = xProfile;
104469  db->pProfileArg = pArg;
104470  sqlite3_mutex_leave(db->mutex);
104471  return pOld;
104472}
104473#endif /* SQLITE_OMIT_TRACE */
104474
104475/*** EXPERIMENTAL ***
104476**
104477** Register a function to be invoked when a transaction comments.
104478** If the invoked function returns non-zero, then the commit becomes a
104479** rollback.
104480*/
104481SQLITE_API void *sqlite3_commit_hook(
104482  sqlite3 *db,              /* Attach the hook to this database */
104483  int (*xCallback)(void*),  /* Function to invoke on each commit */
104484  void *pArg                /* Argument to the function */
104485){
104486  void *pOld;
104487  sqlite3_mutex_enter(db->mutex);
104488  pOld = db->pCommitArg;
104489  db->xCommitCallback = xCallback;
104490  db->pCommitArg = pArg;
104491  sqlite3_mutex_leave(db->mutex);
104492  return pOld;
104493}
104494
104495/*
104496** Register a callback to be invoked each time a row is updated,
104497** inserted or deleted using this database connection.
104498*/
104499SQLITE_API void *sqlite3_update_hook(
104500  sqlite3 *db,              /* Attach the hook to this database */
104501  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
104502  void *pArg                /* Argument to the function */
104503){
104504  void *pRet;
104505  sqlite3_mutex_enter(db->mutex);
104506  pRet = db->pUpdateArg;
104507  db->xUpdateCallback = xCallback;
104508  db->pUpdateArg = pArg;
104509  sqlite3_mutex_leave(db->mutex);
104510  return pRet;
104511}
104512
104513/*
104514** Register a callback to be invoked each time a transaction is rolled
104515** back by this database connection.
104516*/
104517SQLITE_API void *sqlite3_rollback_hook(
104518  sqlite3 *db,              /* Attach the hook to this database */
104519  void (*xCallback)(void*), /* Callback function */
104520  void *pArg                /* Argument to the function */
104521){
104522  void *pRet;
104523  sqlite3_mutex_enter(db->mutex);
104524  pRet = db->pRollbackArg;
104525  db->xRollbackCallback = xCallback;
104526  db->pRollbackArg = pArg;
104527  sqlite3_mutex_leave(db->mutex);
104528  return pRet;
104529}
104530
104531#ifndef SQLITE_OMIT_WAL
104532/*
104533** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
104534** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
104535** is greater than sqlite3.pWalArg cast to an integer (the value configured by
104536** wal_autocheckpoint()).
104537*/
104538SQLITE_PRIVATE int sqlite3WalDefaultHook(
104539  void *pClientData,     /* Argument */
104540  sqlite3 *db,           /* Connection */
104541  const char *zDb,       /* Database */
104542  int nFrame             /* Size of WAL */
104543){
104544  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
104545    sqlite3BeginBenignMalloc();
104546    sqlite3_wal_checkpoint(db, zDb);
104547    sqlite3EndBenignMalloc();
104548  }
104549  return SQLITE_OK;
104550}
104551#endif /* SQLITE_OMIT_WAL */
104552
104553/*
104554** Configure an sqlite3_wal_hook() callback to automatically checkpoint
104555** a database after committing a transaction if there are nFrame or
104556** more frames in the log file. Passing zero or a negative value as the
104557** nFrame parameter disables automatic checkpoints entirely.
104558**
104559** The callback registered by this function replaces any existing callback
104560** registered using sqlite3_wal_hook(). Likewise, registering a callback
104561** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
104562** configured by this function.
104563*/
104564SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
104565#ifndef SQLITE_OMIT_WAL
104566  if( nFrame>0 ){
104567    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
104568  }else{
104569    sqlite3_wal_hook(db, 0, 0);
104570  }
104571#endif
104572  return SQLITE_OK;
104573}
104574
104575/*
104576** Register a callback to be invoked each time a transaction is written
104577** into the write-ahead-log by this database connection.
104578*/
104579SQLITE_API void *sqlite3_wal_hook(
104580  sqlite3 *db,                    /* Attach the hook to this db handle */
104581  int(*xCallback)(void *, sqlite3*, const char*, int),
104582  void *pArg                      /* First argument passed to xCallback() */
104583){
104584#ifndef SQLITE_OMIT_WAL
104585  void *pRet;
104586  sqlite3_mutex_enter(db->mutex);
104587  pRet = db->pWalArg;
104588  db->xWalCallback = xCallback;
104589  db->pWalArg = pArg;
104590  sqlite3_mutex_leave(db->mutex);
104591  return pRet;
104592#else
104593  return 0;
104594#endif
104595}
104596
104597
104598/*
104599** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
104600** to contains a zero-length string, all attached databases are
104601** checkpointed.
104602*/
104603SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
104604#ifdef SQLITE_OMIT_WAL
104605  return SQLITE_OK;
104606#else
104607  int rc;                         /* Return code */
104608  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
104609
104610  sqlite3_mutex_enter(db->mutex);
104611  if( zDb && zDb[0] ){
104612    iDb = sqlite3FindDbName(db, zDb);
104613  }
104614  if( iDb<0 ){
104615    rc = SQLITE_ERROR;
104616    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
104617  }else{
104618    rc = sqlite3Checkpoint(db, iDb);
104619    sqlite3Error(db, rc, 0);
104620  }
104621  rc = sqlite3ApiExit(db, rc);
104622  sqlite3_mutex_leave(db->mutex);
104623  return rc;
104624#endif
104625}
104626
104627#ifndef SQLITE_OMIT_WAL
104628/*
104629** Run a checkpoint on database iDb. This is a no-op if database iDb is
104630** not currently open in WAL mode.
104631**
104632** If a transaction is open on the database being checkpointed, this
104633** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
104634** an error occurs while running the checkpoint, an SQLite error code is
104635** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
104636**
104637** The mutex on database handle db should be held by the caller. The mutex
104638** associated with the specific b-tree being checkpointed is taken by
104639** this function while the checkpoint is running.
104640**
104641** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
104642** checkpointed. If an error is encountered it is returned immediately -
104643** no attempt is made to checkpoint any remaining databases.
104644*/
104645SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
104646  int rc = SQLITE_OK;             /* Return code */
104647  int i;                          /* Used to iterate through attached dbs */
104648
104649  assert( sqlite3_mutex_held(db->mutex) );
104650
104651  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
104652    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
104653      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt);
104654    }
104655  }
104656
104657  return rc;
104658}
104659#endif /* SQLITE_OMIT_WAL */
104660
104661/*
104662** This function returns true if main-memory should be used instead of
104663** a temporary file for transient pager files and statement journals.
104664** The value returned depends on the value of db->temp_store (runtime
104665** parameter) and the compile time value of SQLITE_TEMP_STORE. The
104666** following table describes the relationship between these two values
104667** and this functions return value.
104668**
104669**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
104670**   -----------------     --------------     ------------------------------
104671**   0                     any                file      (return 0)
104672**   1                     1                  file      (return 0)
104673**   1                     2                  memory    (return 1)
104674**   1                     0                  file      (return 0)
104675**   2                     1                  file      (return 0)
104676**   2                     2                  memory    (return 1)
104677**   2                     0                  memory    (return 1)
104678**   3                     any                memory    (return 1)
104679*/
104680SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
104681#if SQLITE_TEMP_STORE==1
104682  return ( db->temp_store==2 );
104683#endif
104684#if SQLITE_TEMP_STORE==2
104685  return ( db->temp_store!=1 );
104686#endif
104687#if SQLITE_TEMP_STORE==3
104688  return 1;
104689#endif
104690#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
104691  return 0;
104692#endif
104693}
104694
104695/*
104696** This routine is called to create a connection to a database BTree
104697** driver.  If zFilename is the name of a file, then that file is
104698** opened and used.  If zFilename is the magic name ":memory:" then
104699** the database is stored in memory (and is thus forgotten as soon as
104700** the connection is closed.)  If zFilename is NULL then the database
104701** is a "virtual" database for transient use only and is deleted as
104702** soon as the connection is closed.
104703**
104704** A virtual database can be either a disk file (that is automatically
104705** deleted when the file is closed) or it an be held entirely in memory.
104706** The sqlite3TempInMemory() function is used to determine which.
104707*/
104708SQLITE_PRIVATE int sqlite3BtreeFactory(
104709  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
104710  const char *zFilename,    /* Name of the file containing the BTree database */
104711  int omitJournal,          /* if TRUE then do not journal this file */
104712  int nCache,               /* How many pages in the page cache */
104713  int vfsFlags,             /* Flags passed through to vfsOpen */
104714  Btree **ppBtree           /* Pointer to new Btree object written here */
104715){
104716  int btFlags = 0;
104717  int rc;
104718
104719  assert( sqlite3_mutex_held(db->mutex) );
104720  assert( ppBtree != 0);
104721  if( omitJournal ){
104722    btFlags |= BTREE_OMIT_JOURNAL;
104723  }
104724  if( db->flags & SQLITE_NoReadlock ){
104725    btFlags |= BTREE_NO_READLOCK;
104726  }
104727#ifndef SQLITE_OMIT_MEMORYDB
104728  if( zFilename==0 && sqlite3TempInMemory(db) ){
104729    zFilename = ":memory:";
104730  }
104731#endif
104732
104733  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
104734    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
104735  }
104736  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
104737
104738  /* If the B-Tree was successfully opened, set the pager-cache size to the
104739  ** default value. Except, if the call to BtreeOpen() returned a handle
104740  ** open on an existing shared pager-cache, do not change the pager-cache
104741  ** size.
104742  */
104743  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
104744    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
104745  }
104746  return rc;
104747}
104748
104749/*
104750** Return UTF-8 encoded English language explanation of the most recent
104751** error.
104752*/
104753SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
104754  const char *z;
104755  if( !db ){
104756    return sqlite3ErrStr(SQLITE_NOMEM);
104757  }
104758  if( !sqlite3SafetyCheckSickOrOk(db) ){
104759    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
104760  }
104761  sqlite3_mutex_enter(db->mutex);
104762  if( db->mallocFailed ){
104763    z = sqlite3ErrStr(SQLITE_NOMEM);
104764  }else{
104765    z = (char*)sqlite3_value_text(db->pErr);
104766    assert( !db->mallocFailed );
104767    if( z==0 ){
104768      z = sqlite3ErrStr(db->errCode);
104769    }
104770  }
104771  sqlite3_mutex_leave(db->mutex);
104772  return z;
104773}
104774
104775#ifndef SQLITE_OMIT_UTF16
104776/*
104777** Return UTF-16 encoded English language explanation of the most recent
104778** error.
104779*/
104780SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
104781  static const u16 outOfMem[] = {
104782    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
104783  };
104784  static const u16 misuse[] = {
104785    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
104786    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
104787    'c', 'a', 'l', 'l', 'e', 'd', ' ',
104788    'o', 'u', 't', ' ',
104789    'o', 'f', ' ',
104790    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
104791  };
104792
104793  const void *z;
104794  if( !db ){
104795    return (void *)outOfMem;
104796  }
104797  if( !sqlite3SafetyCheckSickOrOk(db) ){
104798    return (void *)misuse;
104799  }
104800  sqlite3_mutex_enter(db->mutex);
104801  if( db->mallocFailed ){
104802    z = (void *)outOfMem;
104803  }else{
104804    z = sqlite3_value_text16(db->pErr);
104805    if( z==0 ){
104806      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
104807           SQLITE_UTF8, SQLITE_STATIC);
104808      z = sqlite3_value_text16(db->pErr);
104809    }
104810    /* A malloc() may have failed within the call to sqlite3_value_text16()
104811    ** above. If this is the case, then the db->mallocFailed flag needs to
104812    ** be cleared before returning. Do this directly, instead of via
104813    ** sqlite3ApiExit(), to avoid setting the database handle error message.
104814    */
104815    db->mallocFailed = 0;
104816  }
104817  sqlite3_mutex_leave(db->mutex);
104818  return z;
104819}
104820#endif /* SQLITE_OMIT_UTF16 */
104821
104822/*
104823** Return the most recent error code generated by an SQLite routine. If NULL is
104824** passed to this function, we assume a malloc() failed during sqlite3_open().
104825*/
104826SQLITE_API int sqlite3_errcode(sqlite3 *db){
104827  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
104828    return SQLITE_MISUSE_BKPT;
104829  }
104830  if( !db || db->mallocFailed ){
104831    return SQLITE_NOMEM;
104832  }
104833  return db->errCode & db->errMask;
104834}
104835SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
104836  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
104837    return SQLITE_MISUSE_BKPT;
104838  }
104839  if( !db || db->mallocFailed ){
104840    return SQLITE_NOMEM;
104841  }
104842  return db->errCode;
104843}
104844
104845/*
104846** Create a new collating function for database "db".  The name is zName
104847** and the encoding is enc.
104848*/
104849static int createCollation(
104850  sqlite3* db,
104851  const char *zName,
104852  u8 enc,
104853  u8 collType,
104854  void* pCtx,
104855  int(*xCompare)(void*,int,const void*,int,const void*),
104856  void(*xDel)(void*)
104857){
104858  CollSeq *pColl;
104859  int enc2;
104860  int nName = sqlite3Strlen30(zName);
104861
104862  assert( sqlite3_mutex_held(db->mutex) );
104863
104864  /* If SQLITE_UTF16 is specified as the encoding type, transform this
104865  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
104866  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
104867  */
104868  enc2 = enc;
104869  testcase( enc2==SQLITE_UTF16 );
104870  testcase( enc2==SQLITE_UTF16_ALIGNED );
104871  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
104872    enc2 = SQLITE_UTF16NATIVE;
104873  }
104874  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
104875    return SQLITE_MISUSE_BKPT;
104876  }
104877
104878  /* Check if this call is removing or replacing an existing collation
104879  ** sequence. If so, and there are active VMs, return busy. If there
104880  ** are no active VMs, invalidate any pre-compiled statements.
104881  */
104882  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
104883  if( pColl && pColl->xCmp ){
104884    if( db->activeVdbeCnt ){
104885      sqlite3Error(db, SQLITE_BUSY,
104886        "unable to delete/modify collation sequence due to active statements");
104887      return SQLITE_BUSY;
104888    }
104889    sqlite3ExpirePreparedStatements(db);
104890
104891    /* If collation sequence pColl was created directly by a call to
104892    ** sqlite3_create_collation, and not generated by synthCollSeq(),
104893    ** then any copies made by synthCollSeq() need to be invalidated.
104894    ** Also, collation destructor - CollSeq.xDel() - function may need
104895    ** to be called.
104896    */
104897    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
104898      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
104899      int j;
104900      for(j=0; j<3; j++){
104901        CollSeq *p = &aColl[j];
104902        if( p->enc==pColl->enc ){
104903          if( p->xDel ){
104904            p->xDel(p->pUser);
104905          }
104906          p->xCmp = 0;
104907        }
104908      }
104909    }
104910  }
104911
104912  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
104913  if( pColl ){
104914    pColl->xCmp = xCompare;
104915    pColl->pUser = pCtx;
104916    pColl->xDel = xDel;
104917    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
104918    pColl->type = collType;
104919  }
104920  sqlite3Error(db, SQLITE_OK, 0);
104921  return SQLITE_OK;
104922}
104923
104924
104925/*
104926** This array defines hard upper bounds on limit values.  The
104927** initializer must be kept in sync with the SQLITE_LIMIT_*
104928** #defines in sqlite3.h.
104929*/
104930static const int aHardLimit[] = {
104931  SQLITE_MAX_LENGTH,
104932  SQLITE_MAX_SQL_LENGTH,
104933  SQLITE_MAX_COLUMN,
104934  SQLITE_MAX_EXPR_DEPTH,
104935  SQLITE_MAX_COMPOUND_SELECT,
104936  SQLITE_MAX_VDBE_OP,
104937  SQLITE_MAX_FUNCTION_ARG,
104938  SQLITE_MAX_ATTACHED,
104939  SQLITE_MAX_LIKE_PATTERN_LENGTH,
104940  SQLITE_MAX_VARIABLE_NUMBER,
104941  SQLITE_MAX_TRIGGER_DEPTH,
104942};
104943
104944/*
104945** Make sure the hard limits are set to reasonable values
104946*/
104947#if SQLITE_MAX_LENGTH<100
104948# error SQLITE_MAX_LENGTH must be at least 100
104949#endif
104950#if SQLITE_MAX_SQL_LENGTH<100
104951# error SQLITE_MAX_SQL_LENGTH must be at least 100
104952#endif
104953#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
104954# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
104955#endif
104956#if SQLITE_MAX_COMPOUND_SELECT<2
104957# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
104958#endif
104959#if SQLITE_MAX_VDBE_OP<40
104960# error SQLITE_MAX_VDBE_OP must be at least 40
104961#endif
104962#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
104963# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
104964#endif
104965#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
104966# error SQLITE_MAX_ATTACHED must be between 0 and 30
104967#endif
104968#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
104969# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
104970#endif
104971#if SQLITE_MAX_COLUMN>32767
104972# error SQLITE_MAX_COLUMN must not exceed 32767
104973#endif
104974#if SQLITE_MAX_TRIGGER_DEPTH<1
104975# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
104976#endif
104977
104978
104979/*
104980** Change the value of a limit.  Report the old value.
104981** If an invalid limit index is supplied, report -1.
104982** Make no changes but still report the old value if the
104983** new limit is negative.
104984**
104985** A new lower limit does not shrink existing constructs.
104986** It merely prevents new constructs that exceed the limit
104987** from forming.
104988*/
104989SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
104990  int oldLimit;
104991  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
104992    return -1;
104993  }
104994  oldLimit = db->aLimit[limitId];
104995  if( newLimit>=0 ){
104996    if( newLimit>aHardLimit[limitId] ){
104997      newLimit = aHardLimit[limitId];
104998    }
104999    db->aLimit[limitId] = newLimit;
105000  }
105001  return oldLimit;
105002}
105003
105004/*
105005** This routine does the work of opening a database on behalf of
105006** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
105007** is UTF-8 encoded.
105008*/
105009static int openDatabase(
105010  const char *zFilename, /* Database filename UTF-8 encoded */
105011  sqlite3 **ppDb,        /* OUT: Returned database handle */
105012  unsigned flags,        /* Operational flags */
105013  const char *zVfs       /* Name of the VFS to use */
105014){
105015  sqlite3 *db;
105016  int rc;
105017  int isThreadsafe;
105018
105019  *ppDb = 0;
105020#ifndef SQLITE_OMIT_AUTOINIT
105021  rc = sqlite3_initialize();
105022  if( rc ) return rc;
105023#endif
105024
105025  if( sqlite3GlobalConfig.bCoreMutex==0 ){
105026    isThreadsafe = 0;
105027  }else if( flags & SQLITE_OPEN_NOMUTEX ){
105028    isThreadsafe = 0;
105029  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
105030    isThreadsafe = 1;
105031  }else{
105032    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
105033  }
105034  if( flags & SQLITE_OPEN_PRIVATECACHE ){
105035    flags &= ~SQLITE_OPEN_SHAREDCACHE;
105036  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
105037    flags |= SQLITE_OPEN_SHAREDCACHE;
105038  }
105039
105040  /* Remove harmful bits from the flags parameter
105041  **
105042  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
105043  ** dealt with in the previous code block.  Besides these, the only
105044  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
105045  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
105046  ** off all other flags.
105047  */
105048  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
105049               SQLITE_OPEN_EXCLUSIVE |
105050               SQLITE_OPEN_MAIN_DB |
105051               SQLITE_OPEN_TEMP_DB |
105052               SQLITE_OPEN_TRANSIENT_DB |
105053               SQLITE_OPEN_MAIN_JOURNAL |
105054               SQLITE_OPEN_TEMP_JOURNAL |
105055               SQLITE_OPEN_SUBJOURNAL |
105056               SQLITE_OPEN_MASTER_JOURNAL |
105057               SQLITE_OPEN_NOMUTEX |
105058               SQLITE_OPEN_FULLMUTEX
105059             );
105060
105061  /* Allocate the sqlite data structure */
105062  db = sqlite3MallocZero( sizeof(sqlite3) );
105063  if( db==0 ) goto opendb_out;
105064  if( isThreadsafe ){
105065    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
105066    if( db->mutex==0 ){
105067      sqlite3_free(db);
105068      db = 0;
105069      goto opendb_out;
105070    }
105071  }
105072  sqlite3_mutex_enter(db->mutex);
105073  db->errMask = 0xff;
105074  db->nDb = 2;
105075  db->magic = SQLITE_MAGIC_BUSY;
105076  db->aDb = db->aDbStatic;
105077
105078  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
105079  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
105080  db->autoCommit = 1;
105081  db->nextAutovac = -1;
105082  db->nextPagesize = 0;
105083  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
105084#if SQLITE_DEFAULT_FILE_FORMAT<4
105085                 | SQLITE_LegacyFileFmt
105086#endif
105087#ifdef SQLITE_ENABLE_LOAD_EXTENSION
105088                 | SQLITE_LoadExtension
105089#endif
105090#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
105091                 | SQLITE_RecTriggers
105092#endif
105093      ;
105094  sqlite3HashInit(&db->aCollSeq);
105095#ifndef SQLITE_OMIT_VIRTUALTABLE
105096  sqlite3HashInit(&db->aModule);
105097#endif
105098
105099  db->pVfs = sqlite3_vfs_find(zVfs);
105100  if( !db->pVfs ){
105101    rc = SQLITE_ERROR;
105102    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
105103    goto opendb_out;
105104  }
105105
105106  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
105107  ** and UTF-16, so add a version for each to avoid any unnecessary
105108  ** conversions. The only error that can occur here is a malloc() failure.
105109  */
105110  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
105111                  binCollFunc, 0);
105112  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
105113                  binCollFunc, 0);
105114  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
105115                  binCollFunc, 0);
105116  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
105117                  binCollFunc, 0);
105118  if( db->mallocFailed ){
105119    goto opendb_out;
105120  }
105121  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
105122  assert( db->pDfltColl!=0 );
105123
105124  /* Also add a UTF-8 case-insensitive collation sequence. */
105125  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
105126                  nocaseCollatingFunc, 0);
105127
105128  /* Open the backend database driver */
105129  db->openFlags = flags;
105130  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
105131                           flags | SQLITE_OPEN_MAIN_DB,
105132                           &db->aDb[0].pBt);
105133  if( rc!=SQLITE_OK ){
105134    if( rc==SQLITE_IOERR_NOMEM ){
105135      rc = SQLITE_NOMEM;
105136    }
105137    sqlite3Error(db, rc, 0);
105138    goto opendb_out;
105139  }
105140  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
105141  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
105142
105143
105144  /* The default safety_level for the main database is 'full'; for the temp
105145  ** database it is 'NONE'. This matches the pager layer defaults.
105146  */
105147  db->aDb[0].zName = "main";
105148  db->aDb[0].safety_level = 3;
105149  db->aDb[1].zName = "temp";
105150  db->aDb[1].safety_level = 1;
105151
105152  db->magic = SQLITE_MAGIC_OPEN;
105153  if( db->mallocFailed ){
105154    goto opendb_out;
105155  }
105156
105157  /* Register all built-in functions, but do not attempt to read the
105158  ** database schema yet. This is delayed until the first time the database
105159  ** is accessed.
105160  */
105161  sqlite3Error(db, SQLITE_OK, 0);
105162  sqlite3RegisterBuiltinFunctions(db);
105163
105164  /* Load automatic extensions - extensions that have been registered
105165  ** using the sqlite3_automatic_extension() API.
105166  */
105167  sqlite3AutoLoadExtensions(db);
105168  rc = sqlite3_errcode(db);
105169  if( rc!=SQLITE_OK ){
105170    goto opendb_out;
105171  }
105172
105173#ifdef SQLITE_ENABLE_FTS1
105174  if( !db->mallocFailed ){
105175    extern int sqlite3Fts1Init(sqlite3*);
105176    rc = sqlite3Fts1Init(db);
105177  }
105178#endif
105179
105180#ifdef SQLITE_ENABLE_FTS2
105181  if( !db->mallocFailed && rc==SQLITE_OK ){
105182    extern int sqlite3Fts2Init(sqlite3*);
105183    rc = sqlite3Fts2Init(db);
105184  }
105185#endif
105186
105187#ifdef SQLITE_ENABLE_FTS3
105188  if( !db->mallocFailed && rc==SQLITE_OK ){
105189    rc = sqlite3Fts3Init(db);
105190  }
105191#endif
105192
105193#ifdef SQLITE_ENABLE_ICU
105194  if( !db->mallocFailed && rc==SQLITE_OK ){
105195    rc = sqlite3IcuInit(db);
105196  }
105197#endif
105198
105199#ifdef SQLITE_ENABLE_RTREE
105200  if( !db->mallocFailed && rc==SQLITE_OK){
105201    rc = sqlite3RtreeInit(db);
105202  }
105203#endif
105204
105205  sqlite3Error(db, rc, 0);
105206
105207  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
105208  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
105209  ** mode.  Doing nothing at all also makes NORMAL the default.
105210  */
105211#ifdef SQLITE_DEFAULT_LOCKING_MODE
105212  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
105213  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
105214                          SQLITE_DEFAULT_LOCKING_MODE);
105215#endif
105216
105217  /* Enable the lookaside-malloc subsystem */
105218  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
105219                        sqlite3GlobalConfig.nLookaside);
105220
105221  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
105222
105223opendb_out:
105224  if( db ){
105225    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
105226    sqlite3_mutex_leave(db->mutex);
105227  }
105228  rc = sqlite3_errcode(db);
105229  if( rc==SQLITE_NOMEM ){
105230    sqlite3_close(db);
105231    db = 0;
105232  }else if( rc!=SQLITE_OK ){
105233    db->magic = SQLITE_MAGIC_SICK;
105234  }
105235  *ppDb = db;
105236  return sqlite3ApiExit(0, rc);
105237}
105238
105239/*
105240** Open a new database handle.
105241*/
105242SQLITE_API int sqlite3_open(
105243  const char *zFilename,
105244  sqlite3 **ppDb
105245){
105246  return openDatabase(zFilename, ppDb,
105247                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
105248}
105249SQLITE_API int sqlite3_open_v2(
105250  const char *filename,   /* Database filename (UTF-8) */
105251  sqlite3 **ppDb,         /* OUT: SQLite db handle */
105252  int flags,              /* Flags */
105253  const char *zVfs        /* Name of VFS module to use */
105254){
105255  return openDatabase(filename, ppDb, flags, zVfs);
105256}
105257
105258#ifndef SQLITE_OMIT_UTF16
105259/*
105260** Open a new database handle.
105261*/
105262SQLITE_API int sqlite3_open16(
105263  const void *zFilename,
105264  sqlite3 **ppDb
105265){
105266  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
105267  sqlite3_value *pVal;
105268  int rc;
105269
105270  assert( zFilename );
105271  assert( ppDb );
105272  *ppDb = 0;
105273#ifndef SQLITE_OMIT_AUTOINIT
105274  rc = sqlite3_initialize();
105275  if( rc ) return rc;
105276#endif
105277  pVal = sqlite3ValueNew(0);
105278  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
105279  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
105280  if( zFilename8 ){
105281    rc = openDatabase(zFilename8, ppDb,
105282                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
105283    assert( *ppDb || rc==SQLITE_NOMEM );
105284    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
105285      ENC(*ppDb) = SQLITE_UTF16NATIVE;
105286    }
105287  }else{
105288    rc = SQLITE_NOMEM;
105289  }
105290  sqlite3ValueFree(pVal);
105291
105292  return sqlite3ApiExit(0, rc);
105293}
105294#endif /* SQLITE_OMIT_UTF16 */
105295
105296/*
105297** Register a new collation sequence with the database handle db.
105298*/
105299SQLITE_API int sqlite3_create_collation(
105300  sqlite3* db,
105301  const char *zName,
105302  int enc,
105303  void* pCtx,
105304  int(*xCompare)(void*,int,const void*,int,const void*)
105305){
105306  int rc;
105307  sqlite3_mutex_enter(db->mutex);
105308  assert( !db->mallocFailed );
105309  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
105310  rc = sqlite3ApiExit(db, rc);
105311  sqlite3_mutex_leave(db->mutex);
105312  return rc;
105313}
105314
105315/*
105316** Register a new collation sequence with the database handle db.
105317*/
105318SQLITE_API int sqlite3_create_collation_v2(
105319  sqlite3* db,
105320  const char *zName,
105321  int enc,
105322  void* pCtx,
105323  int(*xCompare)(void*,int,const void*,int,const void*),
105324  void(*xDel)(void*)
105325){
105326  int rc;
105327  sqlite3_mutex_enter(db->mutex);
105328  assert( !db->mallocFailed );
105329  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
105330  rc = sqlite3ApiExit(db, rc);
105331  sqlite3_mutex_leave(db->mutex);
105332  return rc;
105333}
105334
105335#ifndef SQLITE_OMIT_UTF16
105336/*
105337** Register a new collation sequence with the database handle db.
105338*/
105339SQLITE_API int sqlite3_create_collation16(
105340  sqlite3* db,
105341  const void *zName,
105342  int enc,
105343  void* pCtx,
105344  int(*xCompare)(void*,int,const void*,int,const void*)
105345){
105346  int rc = SQLITE_OK;
105347  char *zName8;
105348  sqlite3_mutex_enter(db->mutex);
105349  assert( !db->mallocFailed );
105350  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
105351  if( zName8 ){
105352    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
105353    sqlite3DbFree(db, zName8);
105354  }
105355  rc = sqlite3ApiExit(db, rc);
105356  sqlite3_mutex_leave(db->mutex);
105357  return rc;
105358}
105359#endif /* SQLITE_OMIT_UTF16 */
105360
105361/*
105362** Register a collation sequence factory callback with the database handle
105363** db. Replace any previously installed collation sequence factory.
105364*/
105365SQLITE_API int sqlite3_collation_needed(
105366  sqlite3 *db,
105367  void *pCollNeededArg,
105368  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
105369){
105370  sqlite3_mutex_enter(db->mutex);
105371  db->xCollNeeded = xCollNeeded;
105372  db->xCollNeeded16 = 0;
105373  db->pCollNeededArg = pCollNeededArg;
105374  sqlite3_mutex_leave(db->mutex);
105375  return SQLITE_OK;
105376}
105377
105378#ifndef SQLITE_OMIT_UTF16
105379/*
105380** Register a collation sequence factory callback with the database handle
105381** db. Replace any previously installed collation sequence factory.
105382*/
105383SQLITE_API int sqlite3_collation_needed16(
105384  sqlite3 *db,
105385  void *pCollNeededArg,
105386  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
105387){
105388  sqlite3_mutex_enter(db->mutex);
105389  db->xCollNeeded = 0;
105390  db->xCollNeeded16 = xCollNeeded16;
105391  db->pCollNeededArg = pCollNeededArg;
105392  sqlite3_mutex_leave(db->mutex);
105393  return SQLITE_OK;
105394}
105395#endif /* SQLITE_OMIT_UTF16 */
105396
105397#ifndef SQLITE_OMIT_DEPRECATED
105398/*
105399** This function is now an anachronism. It used to be used to recover from a
105400** malloc() failure, but SQLite now does this automatically.
105401*/
105402SQLITE_API int sqlite3_global_recover(void){
105403  return SQLITE_OK;
105404}
105405#endif
105406
105407/*
105408** Test to see whether or not the database connection is in autocommit
105409** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
105410** by default.  Autocommit is disabled by a BEGIN statement and reenabled
105411** by the next COMMIT or ROLLBACK.
105412**
105413******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
105414*/
105415SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
105416  return db->autoCommit;
105417}
105418
105419/*
105420** The following routines are subtitutes for constants SQLITE_CORRUPT,
105421** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
105422** constants.  They server two purposes:
105423**
105424**   1.  Serve as a convenient place to set a breakpoint in a debugger
105425**       to detect when version error conditions occurs.
105426**
105427**   2.  Invoke sqlite3_log() to provide the source code location where
105428**       a low-level error is first detected.
105429*/
105430SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
105431  testcase( sqlite3GlobalConfig.xLog!=0 );
105432  sqlite3_log(SQLITE_CORRUPT,
105433              "database corruption at line %d of [%.10s]",
105434              lineno, 20+sqlite3_sourceid());
105435  return SQLITE_CORRUPT;
105436}
105437SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
105438  testcase( sqlite3GlobalConfig.xLog!=0 );
105439  sqlite3_log(SQLITE_MISUSE,
105440              "misuse at line %d of [%.10s]",
105441              lineno, 20+sqlite3_sourceid());
105442  return SQLITE_MISUSE;
105443}
105444SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
105445  testcase( sqlite3GlobalConfig.xLog!=0 );
105446  sqlite3_log(SQLITE_CANTOPEN,
105447              "cannot open file at line %d of [%.10s]",
105448              lineno, 20+sqlite3_sourceid());
105449  return SQLITE_CANTOPEN;
105450}
105451
105452
105453#ifndef SQLITE_OMIT_DEPRECATED
105454/*
105455** This is a convenience routine that makes sure that all thread-specific
105456** data for this thread has been deallocated.
105457**
105458** SQLite no longer uses thread-specific data so this routine is now a
105459** no-op.  It is retained for historical compatibility.
105460*/
105461SQLITE_API void sqlite3_thread_cleanup(void){
105462}
105463#endif
105464
105465/*
105466** Return meta information about a specific column of a database table.
105467** See comment in sqlite3.h (sqlite.h.in) for details.
105468*/
105469#ifdef SQLITE_ENABLE_COLUMN_METADATA
105470SQLITE_API int sqlite3_table_column_metadata(
105471  sqlite3 *db,                /* Connection handle */
105472  const char *zDbName,        /* Database name or NULL */
105473  const char *zTableName,     /* Table name */
105474  const char *zColumnName,    /* Column name */
105475  char const **pzDataType,    /* OUTPUT: Declared data type */
105476  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
105477  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
105478  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
105479  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
105480){
105481  int rc;
105482  char *zErrMsg = 0;
105483  Table *pTab = 0;
105484  Column *pCol = 0;
105485  int iCol;
105486
105487  char const *zDataType = 0;
105488  char const *zCollSeq = 0;
105489  int notnull = 0;
105490  int primarykey = 0;
105491  int autoinc = 0;
105492
105493  /* Ensure the database schema has been loaded */
105494  sqlite3_mutex_enter(db->mutex);
105495  sqlite3BtreeEnterAll(db);
105496  rc = sqlite3Init(db, &zErrMsg);
105497  if( SQLITE_OK!=rc ){
105498    goto error_out;
105499  }
105500
105501  /* Locate the table in question */
105502  pTab = sqlite3FindTable(db, zTableName, zDbName);
105503  if( !pTab || pTab->pSelect ){
105504    pTab = 0;
105505    goto error_out;
105506  }
105507
105508  /* Find the column for which info is requested */
105509  if( sqlite3IsRowid(zColumnName) ){
105510    iCol = pTab->iPKey;
105511    if( iCol>=0 ){
105512      pCol = &pTab->aCol[iCol];
105513    }
105514  }else{
105515    for(iCol=0; iCol<pTab->nCol; iCol++){
105516      pCol = &pTab->aCol[iCol];
105517      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
105518        break;
105519      }
105520    }
105521    if( iCol==pTab->nCol ){
105522      pTab = 0;
105523      goto error_out;
105524    }
105525  }
105526
105527  /* The following block stores the meta information that will be returned
105528  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
105529  ** and autoinc. At this point there are two possibilities:
105530  **
105531  **     1. The specified column name was rowid", "oid" or "_rowid_"
105532  **        and there is no explicitly declared IPK column.
105533  **
105534  **     2. The table is not a view and the column name identified an
105535  **        explicitly declared column. Copy meta information from *pCol.
105536  */
105537  if( pCol ){
105538    zDataType = pCol->zType;
105539    zCollSeq = pCol->zColl;
105540    notnull = pCol->notNull!=0;
105541    primarykey  = pCol->isPrimKey!=0;
105542    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
105543  }else{
105544    zDataType = "INTEGER";
105545    primarykey = 1;
105546  }
105547  if( !zCollSeq ){
105548    zCollSeq = "BINARY";
105549  }
105550
105551error_out:
105552  sqlite3BtreeLeaveAll(db);
105553
105554  /* Whether the function call succeeded or failed, set the output parameters
105555  ** to whatever their local counterparts contain. If an error did occur,
105556  ** this has the effect of zeroing all output parameters.
105557  */
105558  if( pzDataType ) *pzDataType = zDataType;
105559  if( pzCollSeq ) *pzCollSeq = zCollSeq;
105560  if( pNotNull ) *pNotNull = notnull;
105561  if( pPrimaryKey ) *pPrimaryKey = primarykey;
105562  if( pAutoinc ) *pAutoinc = autoinc;
105563
105564  if( SQLITE_OK==rc && !pTab ){
105565    sqlite3DbFree(db, zErrMsg);
105566    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
105567        zColumnName);
105568    rc = SQLITE_ERROR;
105569  }
105570  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
105571  sqlite3DbFree(db, zErrMsg);
105572  rc = sqlite3ApiExit(db, rc);
105573  sqlite3_mutex_leave(db->mutex);
105574  return rc;
105575}
105576#endif
105577
105578/*
105579** Sleep for a little while.  Return the amount of time slept.
105580*/
105581SQLITE_API int sqlite3_sleep(int ms){
105582  sqlite3_vfs *pVfs;
105583  int rc;
105584  pVfs = sqlite3_vfs_find(0);
105585  if( pVfs==0 ) return 0;
105586
105587  /* This function works in milliseconds, but the underlying OsSleep()
105588  ** API uses microseconds. Hence the 1000's.
105589  */
105590  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
105591  return rc;
105592}
105593
105594/*
105595** Enable or disable the extended result codes.
105596*/
105597SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
105598  sqlite3_mutex_enter(db->mutex);
105599  db->errMask = onoff ? 0xffffffff : 0xff;
105600  sqlite3_mutex_leave(db->mutex);
105601  return SQLITE_OK;
105602}
105603
105604/*
105605** Invoke the xFileControl method on a particular database.
105606*/
105607SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
105608  int rc = SQLITE_ERROR;
105609  int iDb;
105610  sqlite3_mutex_enter(db->mutex);
105611  if( zDbName==0 ){
105612    iDb = 0;
105613  }else{
105614    for(iDb=0; iDb<db->nDb; iDb++){
105615      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
105616    }
105617  }
105618  if( iDb<db->nDb ){
105619    Btree *pBtree = db->aDb[iDb].pBt;
105620    if( pBtree ){
105621      Pager *pPager;
105622      sqlite3_file *fd;
105623      sqlite3BtreeEnter(pBtree);
105624      pPager = sqlite3BtreePager(pBtree);
105625      assert( pPager!=0 );
105626      fd = sqlite3PagerFile(pPager);
105627      assert( fd!=0 );
105628      if( fd->pMethods ){
105629        rc = sqlite3OsFileControl(fd, op, pArg);
105630      }
105631      sqlite3BtreeLeave(pBtree);
105632    }
105633  }
105634  sqlite3_mutex_leave(db->mutex);
105635  return rc;
105636}
105637
105638/*
105639** Interface to the testing logic.
105640*/
105641SQLITE_API int sqlite3_test_control(int op, ...){
105642  int rc = 0;
105643#ifndef SQLITE_OMIT_BUILTIN_TEST
105644  va_list ap;
105645  va_start(ap, op);
105646  switch( op ){
105647
105648    /*
105649    ** Save the current state of the PRNG.
105650    */
105651    case SQLITE_TESTCTRL_PRNG_SAVE: {
105652      sqlite3PrngSaveState();
105653      break;
105654    }
105655
105656    /*
105657    ** Restore the state of the PRNG to the last state saved using
105658    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
105659    ** this verb acts like PRNG_RESET.
105660    */
105661    case SQLITE_TESTCTRL_PRNG_RESTORE: {
105662      sqlite3PrngRestoreState();
105663      break;
105664    }
105665
105666    /*
105667    ** Reset the PRNG back to its uninitialized state.  The next call
105668    ** to sqlite3_randomness() will reseed the PRNG using a single call
105669    ** to the xRandomness method of the default VFS.
105670    */
105671    case SQLITE_TESTCTRL_PRNG_RESET: {
105672      sqlite3PrngResetState();
105673      break;
105674    }
105675
105676    /*
105677    **  sqlite3_test_control(BITVEC_TEST, size, program)
105678    **
105679    ** Run a test against a Bitvec object of size.  The program argument
105680    ** is an array of integers that defines the test.  Return -1 on a
105681    ** memory allocation error, 0 on success, or non-zero for an error.
105682    ** See the sqlite3BitvecBuiltinTest() for additional information.
105683    */
105684    case SQLITE_TESTCTRL_BITVEC_TEST: {
105685      int sz = va_arg(ap, int);
105686      int *aProg = va_arg(ap, int*);
105687      rc = sqlite3BitvecBuiltinTest(sz, aProg);
105688      break;
105689    }
105690
105691    /*
105692    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
105693    **
105694    ** Register hooks to call to indicate which malloc() failures
105695    ** are benign.
105696    */
105697    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
105698      typedef void (*void_function)(void);
105699      void_function xBenignBegin;
105700      void_function xBenignEnd;
105701      xBenignBegin = va_arg(ap, void_function);
105702      xBenignEnd = va_arg(ap, void_function);
105703      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
105704      break;
105705    }
105706
105707    /*
105708    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
105709    **
105710    ** Set the PENDING byte to the value in the argument, if X>0.
105711    ** Make no changes if X==0.  Return the value of the pending byte
105712    ** as it existing before this routine was called.
105713    **
105714    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
105715    ** an incompatible database file format.  Changing the PENDING byte
105716    ** while any database connection is open results in undefined and
105717    ** dileterious behavior.
105718    */
105719    case SQLITE_TESTCTRL_PENDING_BYTE: {
105720      rc = PENDING_BYTE;
105721#ifndef SQLITE_OMIT_WSD
105722      {
105723        unsigned int newVal = va_arg(ap, unsigned int);
105724        if( newVal ) sqlite3PendingByte = newVal;
105725      }
105726#endif
105727      break;
105728    }
105729
105730    /*
105731    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
105732    **
105733    ** This action provides a run-time test to see whether or not
105734    ** assert() was enabled at compile-time.  If X is true and assert()
105735    ** is enabled, then the return value is true.  If X is true and
105736    ** assert() is disabled, then the return value is zero.  If X is
105737    ** false and assert() is enabled, then the assertion fires and the
105738    ** process aborts.  If X is false and assert() is disabled, then the
105739    ** return value is zero.
105740    */
105741    case SQLITE_TESTCTRL_ASSERT: {
105742      volatile int x = 0;
105743      assert( (x = va_arg(ap,int))!=0 );
105744      rc = x;
105745      break;
105746    }
105747
105748
105749    /*
105750    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
105751    **
105752    ** This action provides a run-time test to see how the ALWAYS and
105753    ** NEVER macros were defined at compile-time.
105754    **
105755    ** The return value is ALWAYS(X).
105756    **
105757    ** The recommended test is X==2.  If the return value is 2, that means
105758    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
105759    ** default setting.  If the return value is 1, then ALWAYS() is either
105760    ** hard-coded to true or else it asserts if its argument is false.
105761    ** The first behavior (hard-coded to true) is the case if
105762    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
105763    ** behavior (assert if the argument to ALWAYS() is false) is the case if
105764    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
105765    **
105766    ** The run-time test procedure might look something like this:
105767    **
105768    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
105769    **      // ALWAYS() and NEVER() are no-op pass-through macros
105770    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
105771    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
105772    **    }else{
105773    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
105774    **    }
105775    */
105776    case SQLITE_TESTCTRL_ALWAYS: {
105777      int x = va_arg(ap,int);
105778      rc = ALWAYS(x);
105779      break;
105780    }
105781
105782    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
105783    **
105784    ** Set the nReserve size to N for the main database on the database
105785    ** connection db.
105786    */
105787    case SQLITE_TESTCTRL_RESERVE: {
105788      sqlite3 *db = va_arg(ap, sqlite3*);
105789      int x = va_arg(ap,int);
105790      sqlite3_mutex_enter(db->mutex);
105791      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
105792      sqlite3_mutex_leave(db->mutex);
105793      break;
105794    }
105795
105796    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
105797    **
105798    ** Enable or disable various optimizations for testing purposes.  The
105799    ** argument N is a bitmask of optimizations to be disabled.  For normal
105800    ** operation N should be 0.  The idea is that a test program (like the
105801    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
105802    ** with various optimizations disabled to verify that the same answer
105803    ** is obtained in every case.
105804    */
105805    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
105806      sqlite3 *db = va_arg(ap, sqlite3*);
105807      int x = va_arg(ap,int);
105808      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
105809      break;
105810    }
105811
105812#ifdef SQLITE_N_KEYWORD
105813    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
105814    **
105815    ** If zWord is a keyword recognized by the parser, then return the
105816    ** number of keywords.  Or if zWord is not a keyword, return 0.
105817    **
105818    ** This test feature is only available in the amalgamation since
105819    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
105820    ** is built using separate source files.
105821    */
105822    case SQLITE_TESTCTRL_ISKEYWORD: {
105823      const char *zWord = va_arg(ap, const char*);
105824      int n = sqlite3Strlen30(zWord);
105825      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
105826      break;
105827    }
105828#endif
105829
105830    /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
105831    **
105832    ** Return the size of a pcache header in bytes.
105833    */
105834    case SQLITE_TESTCTRL_PGHDRSZ: {
105835      rc = sizeof(PgHdr);
105836      break;
105837    }
105838
105839  }
105840  va_end(ap);
105841#endif /* SQLITE_OMIT_BUILTIN_TEST */
105842  return rc;
105843}
105844
105845/************** End of main.c ************************************************/
105846/************** Begin file notify.c ******************************************/
105847/*
105848** 2009 March 3
105849**
105850** The author disclaims copyright to this source code.  In place of
105851** a legal notice, here is a blessing:
105852**
105853**    May you do good and not evil.
105854**    May you find forgiveness for yourself and forgive others.
105855**    May you share freely, never taking more than you give.
105856**
105857*************************************************************************
105858**
105859** This file contains the implementation of the sqlite3_unlock_notify()
105860** API method and its associated functionality.
105861*/
105862
105863/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
105864#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
105865
105866/*
105867** Public interfaces:
105868**
105869**   sqlite3ConnectionBlocked()
105870**   sqlite3ConnectionUnlocked()
105871**   sqlite3ConnectionClosed()
105872**   sqlite3_unlock_notify()
105873*/
105874
105875#define assertMutexHeld() \
105876  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
105877
105878/*
105879** Head of a linked list of all sqlite3 objects created by this process
105880** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
105881** is not NULL. This variable may only accessed while the STATIC_MASTER
105882** mutex is held.
105883*/
105884static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
105885
105886#ifndef NDEBUG
105887/*
105888** This function is a complex assert() that verifies the following
105889** properties of the blocked connections list:
105890**
105891**   1) Each entry in the list has a non-NULL value for either
105892**      pUnlockConnection or pBlockingConnection, or both.
105893**
105894**   2) All entries in the list that share a common value for
105895**      xUnlockNotify are grouped together.
105896**
105897**   3) If the argument db is not NULL, then none of the entries in the
105898**      blocked connections list have pUnlockConnection or pBlockingConnection
105899**      set to db. This is used when closing connection db.
105900*/
105901static void checkListProperties(sqlite3 *db){
105902  sqlite3 *p;
105903  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
105904    int seen = 0;
105905    sqlite3 *p2;
105906
105907    /* Verify property (1) */
105908    assert( p->pUnlockConnection || p->pBlockingConnection );
105909
105910    /* Verify property (2) */
105911    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
105912      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
105913      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
105914      assert( db==0 || p->pUnlockConnection!=db );
105915      assert( db==0 || p->pBlockingConnection!=db );
105916    }
105917  }
105918}
105919#else
105920# define checkListProperties(x)
105921#endif
105922
105923/*
105924** Remove connection db from the blocked connections list. If connection
105925** db is not currently a part of the list, this function is a no-op.
105926*/
105927static void removeFromBlockedList(sqlite3 *db){
105928  sqlite3 **pp;
105929  assertMutexHeld();
105930  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
105931    if( *pp==db ){
105932      *pp = (*pp)->pNextBlocked;
105933      break;
105934    }
105935  }
105936}
105937
105938/*
105939** Add connection db to the blocked connections list. It is assumed
105940** that it is not already a part of the list.
105941*/
105942static void addToBlockedList(sqlite3 *db){
105943  sqlite3 **pp;
105944  assertMutexHeld();
105945  for(
105946    pp=&sqlite3BlockedList;
105947    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
105948    pp=&(*pp)->pNextBlocked
105949  );
105950  db->pNextBlocked = *pp;
105951  *pp = db;
105952}
105953
105954/*
105955** Obtain the STATIC_MASTER mutex.
105956*/
105957static void enterMutex(void){
105958  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
105959  checkListProperties(0);
105960}
105961
105962/*
105963** Release the STATIC_MASTER mutex.
105964*/
105965static void leaveMutex(void){
105966  assertMutexHeld();
105967  checkListProperties(0);
105968  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
105969}
105970
105971/*
105972** Register an unlock-notify callback.
105973**
105974** This is called after connection "db" has attempted some operation
105975** but has received an SQLITE_LOCKED error because another connection
105976** (call it pOther) in the same process was busy using the same shared
105977** cache.  pOther is found by looking at db->pBlockingConnection.
105978**
105979** If there is no blocking connection, the callback is invoked immediately,
105980** before this routine returns.
105981**
105982** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
105983** a deadlock.
105984**
105985** Otherwise, make arrangements to invoke xNotify when pOther drops
105986** its locks.
105987**
105988** Each call to this routine overrides any prior callbacks registered
105989** on the same "db".  If xNotify==0 then any prior callbacks are immediately
105990** cancelled.
105991*/
105992SQLITE_API int sqlite3_unlock_notify(
105993  sqlite3 *db,
105994  void (*xNotify)(void **, int),
105995  void *pArg
105996){
105997  int rc = SQLITE_OK;
105998
105999  sqlite3_mutex_enter(db->mutex);
106000  enterMutex();
106001
106002  if( xNotify==0 ){
106003    removeFromBlockedList(db);
106004    db->pBlockingConnection = 0;
106005    db->pUnlockConnection = 0;
106006    db->xUnlockNotify = 0;
106007    db->pUnlockArg = 0;
106008  }else if( 0==db->pBlockingConnection ){
106009    /* The blocking transaction has been concluded. Or there never was a
106010    ** blocking transaction. In either case, invoke the notify callback
106011    ** immediately.
106012    */
106013    xNotify(&pArg, 1);
106014  }else{
106015    sqlite3 *p;
106016
106017    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
106018    if( p ){
106019      rc = SQLITE_LOCKED;              /* Deadlock detected. */
106020    }else{
106021      db->pUnlockConnection = db->pBlockingConnection;
106022      db->xUnlockNotify = xNotify;
106023      db->pUnlockArg = pArg;
106024      removeFromBlockedList(db);
106025      addToBlockedList(db);
106026    }
106027  }
106028
106029  leaveMutex();
106030  assert( !db->mallocFailed );
106031  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
106032  sqlite3_mutex_leave(db->mutex);
106033  return rc;
106034}
106035
106036/*
106037** This function is called while stepping or preparing a statement
106038** associated with connection db. The operation will return SQLITE_LOCKED
106039** to the user because it requires a lock that will not be available
106040** until connection pBlocker concludes its current transaction.
106041*/
106042SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
106043  enterMutex();
106044  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
106045    addToBlockedList(db);
106046  }
106047  db->pBlockingConnection = pBlocker;
106048  leaveMutex();
106049}
106050
106051/*
106052** This function is called when
106053** the transaction opened by database db has just finished. Locks held
106054** by database connection db have been released.
106055**
106056** This function loops through each entry in the blocked connections
106057** list and does the following:
106058**
106059**   1) If the sqlite3.pBlockingConnection member of a list entry is
106060**      set to db, then set pBlockingConnection=0.
106061**
106062**   2) If the sqlite3.pUnlockConnection member of a list entry is
106063**      set to db, then invoke the configured unlock-notify callback and
106064**      set pUnlockConnection=0.
106065**
106066**   3) If the two steps above mean that pBlockingConnection==0 and
106067**      pUnlockConnection==0, remove the entry from the blocked connections
106068**      list.
106069*/
106070SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
106071  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
106072  int nArg = 0;                            /* Number of entries in aArg[] */
106073  sqlite3 **pp;                            /* Iterator variable */
106074  void **aArg;               /* Arguments to the unlock callback */
106075  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
106076  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
106077
106078  aArg = aStatic;
106079  enterMutex();         /* Enter STATIC_MASTER mutex */
106080
106081  /* This loop runs once for each entry in the blocked-connections list. */
106082  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
106083    sqlite3 *p = *pp;
106084
106085    /* Step 1. */
106086    if( p->pBlockingConnection==db ){
106087      p->pBlockingConnection = 0;
106088    }
106089
106090    /* Step 2. */
106091    if( p->pUnlockConnection==db ){
106092      assert( p->xUnlockNotify );
106093      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
106094        xUnlockNotify(aArg, nArg);
106095        nArg = 0;
106096      }
106097
106098      sqlite3BeginBenignMalloc();
106099      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
106100      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
106101      if( (!aDyn && nArg==(int)ArraySize(aStatic))
106102       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
106103      ){
106104        /* The aArg[] array needs to grow. */
106105        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
106106        if( pNew ){
106107          memcpy(pNew, aArg, nArg*sizeof(void *));
106108          sqlite3_free(aDyn);
106109          aDyn = aArg = pNew;
106110        }else{
106111          /* This occurs when the array of context pointers that need to
106112          ** be passed to the unlock-notify callback is larger than the
106113          ** aStatic[] array allocated on the stack and the attempt to
106114          ** allocate a larger array from the heap has failed.
106115          **
106116          ** This is a difficult situation to handle. Returning an error
106117          ** code to the caller is insufficient, as even if an error code
106118          ** is returned the transaction on connection db will still be
106119          ** closed and the unlock-notify callbacks on blocked connections
106120          ** will go unissued. This might cause the application to wait
106121          ** indefinitely for an unlock-notify callback that will never
106122          ** arrive.
106123          **
106124          ** Instead, invoke the unlock-notify callback with the context
106125          ** array already accumulated. We can then clear the array and
106126          ** begin accumulating any further context pointers without
106127          ** requiring any dynamic allocation. This is sub-optimal because
106128          ** it means that instead of one callback with a large array of
106129          ** context pointers the application will receive two or more
106130          ** callbacks with smaller arrays of context pointers, which will
106131          ** reduce the applications ability to prioritize multiple
106132          ** connections. But it is the best that can be done under the
106133          ** circumstances.
106134          */
106135          xUnlockNotify(aArg, nArg);
106136          nArg = 0;
106137        }
106138      }
106139      sqlite3EndBenignMalloc();
106140
106141      aArg[nArg++] = p->pUnlockArg;
106142      xUnlockNotify = p->xUnlockNotify;
106143      p->pUnlockConnection = 0;
106144      p->xUnlockNotify = 0;
106145      p->pUnlockArg = 0;
106146    }
106147
106148    /* Step 3. */
106149    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
106150      /* Remove connection p from the blocked connections list. */
106151      *pp = p->pNextBlocked;
106152      p->pNextBlocked = 0;
106153    }else{
106154      pp = &p->pNextBlocked;
106155    }
106156  }
106157
106158  if( nArg!=0 ){
106159    xUnlockNotify(aArg, nArg);
106160  }
106161  sqlite3_free(aDyn);
106162  leaveMutex();         /* Leave STATIC_MASTER mutex */
106163}
106164
106165/*
106166** This is called when the database connection passed as an argument is
106167** being closed. The connection is removed from the blocked list.
106168*/
106169SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
106170  sqlite3ConnectionUnlocked(db);
106171  enterMutex();
106172  removeFromBlockedList(db);
106173  checkListProperties(db);
106174  leaveMutex();
106175}
106176#endif
106177
106178/************** End of notify.c **********************************************/
106179/************** Begin file fts3.c ********************************************/
106180/*
106181** 2006 Oct 10
106182**
106183** The author disclaims copyright to this source code.  In place of
106184** a legal notice, here is a blessing:
106185**
106186**    May you do good and not evil.
106187**    May you find forgiveness for yourself and forgive others.
106188**    May you share freely, never taking more than you give.
106189**
106190******************************************************************************
106191**
106192** This is an SQLite module implementing full-text search.
106193*/
106194
106195/*
106196** The code in this file is only compiled if:
106197**
106198**     * The FTS3 module is being built as an extension
106199**       (in which case SQLITE_CORE is not defined), or
106200**
106201**     * The FTS3 module is being built into the core of
106202**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
106203*/
106204
106205/* The full-text index is stored in a series of b+tree (-like)
106206** structures called segments which map terms to doclists.  The
106207** structures are like b+trees in layout, but are constructed from the
106208** bottom up in optimal fashion and are not updatable.  Since trees
106209** are built from the bottom up, things will be described from the
106210** bottom up.
106211**
106212**
106213**** Varints ****
106214** The basic unit of encoding is a variable-length integer called a
106215** varint.  We encode variable-length integers in little-endian order
106216** using seven bits * per byte as follows:
106217**
106218** KEY:
106219**         A = 0xxxxxxx    7 bits of data and one flag bit
106220**         B = 1xxxxxxx    7 bits of data and one flag bit
106221**
106222**  7 bits - A
106223** 14 bits - BA
106224** 21 bits - BBA
106225** and so on.
106226**
106227** This is similar in concept to how sqlite encodes "varints" but
106228** the encoding is not the same.  SQLite varints are big-endian
106229** are are limited to 9 bytes in length whereas FTS3 varints are
106230** little-endian and can be up to 10 bytes in length (in theory).
106231**
106232** Example encodings:
106233**
106234**     1:    0x01
106235**   127:    0x7f
106236**   128:    0x81 0x00
106237**
106238**
106239**** Document lists ****
106240** A doclist (document list) holds a docid-sorted list of hits for a
106241** given term.  Doclists hold docids and associated token positions.
106242** A docid is the unique integer identifier for a single document.
106243** A position is the index of a word within the document.  The first
106244** word of the document has a position of 0.
106245**
106246** FTS3 used to optionally store character offsets using a compile-time
106247** option.  But that functionality is no longer supported.
106248**
106249** A doclist is stored like this:
106250**
106251** array {
106252**   varint docid;
106253**   array {                (position list for column 0)
106254**     varint position;     (2 more than the delta from previous position)
106255**   }
106256**   array {
106257**     varint POS_COLUMN;   (marks start of position list for new column)
106258**     varint column;       (index of new column)
106259**     array {
106260**       varint position;   (2 more than the delta from previous position)
106261**     }
106262**   }
106263**   varint POS_END;        (marks end of positions for this document.
106264** }
106265**
106266** Here, array { X } means zero or more occurrences of X, adjacent in
106267** memory.  A "position" is an index of a token in the token stream
106268** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
106269** in the same logical place as the position element, and act as sentinals
106270** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
106271** The positions numbers are not stored literally but rather as two more
106272** than the difference from the prior position, or the just the position plus
106273** 2 for the first position.  Example:
106274**
106275**   label:       A B C D E  F  G H   I  J K
106276**   value:     123 5 9 1 1 14 35 0 234 72 0
106277**
106278** The 123 value is the first docid.  For column zero in this document
106279** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
106280** at D signals the start of a new column; the 1 at E indicates that the
106281** new column is column number 1.  There are two positions at 12 and 45
106282** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
106283** 234 at I is the next docid.  It has one position 72 (72-2) and then
106284** terminates with the 0 at K.
106285**
106286** A "position-list" is the list of positions for multiple columns for
106287** a single docid.  A "column-list" is the set of positions for a single
106288** column.  Hence, a position-list consists of one or more column-lists,
106289** a document record consists of a docid followed by a position-list and
106290** a doclist consists of one or more document records.
106291**
106292** A bare doclist omits the position information, becoming an
106293** array of varint-encoded docids.
106294**
106295**** Segment leaf nodes ****
106296** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
106297** nodes are written using LeafWriter, and read using LeafReader (to
106298** iterate through a single leaf node's data) and LeavesReader (to
106299** iterate through a segment's entire leaf layer).  Leaf nodes have
106300** the format:
106301**
106302** varint iHeight;             (height from leaf level, always 0)
106303** varint nTerm;               (length of first term)
106304** char pTerm[nTerm];          (content of first term)
106305** varint nDoclist;            (length of term's associated doclist)
106306** char pDoclist[nDoclist];    (content of doclist)
106307** array {
106308**                             (further terms are delta-encoded)
106309**   varint nPrefix;           (length of prefix shared with previous term)
106310**   varint nSuffix;           (length of unshared suffix)
106311**   char pTermSuffix[nSuffix];(unshared suffix of next term)
106312**   varint nDoclist;          (length of term's associated doclist)
106313**   char pDoclist[nDoclist];  (content of doclist)
106314** }
106315**
106316** Here, array { X } means zero or more occurrences of X, adjacent in
106317** memory.
106318**
106319** Leaf nodes are broken into blocks which are stored contiguously in
106320** the %_segments table in sorted order.  This means that when the end
106321** of a node is reached, the next term is in the node with the next
106322** greater node id.
106323**
106324** New data is spilled to a new leaf node when the current node
106325** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
106326** larger than STANDALONE_MIN (default 1024) is placed in a standalone
106327** node (a leaf node with a single term and doclist).  The goal of
106328** these settings is to pack together groups of small doclists while
106329** making it efficient to directly access large doclists.  The
106330** assumption is that large doclists represent terms which are more
106331** likely to be query targets.
106332**
106333** TODO(shess) It may be useful for blocking decisions to be more
106334** dynamic.  For instance, it may make more sense to have a 2.5k leaf
106335** node rather than splitting into 2k and .5k nodes.  My intuition is
106336** that this might extend through 2x or 4x the pagesize.
106337**
106338**
106339**** Segment interior nodes ****
106340** Segment interior nodes store blockids for subtree nodes and terms
106341** to describe what data is stored by the each subtree.  Interior
106342** nodes are written using InteriorWriter, and read using
106343** InteriorReader.  InteriorWriters are created as needed when
106344** SegmentWriter creates new leaf nodes, or when an interior node
106345** itself grows too big and must be split.  The format of interior
106346** nodes:
106347**
106348** varint iHeight;           (height from leaf level, always >0)
106349** varint iBlockid;          (block id of node's leftmost subtree)
106350** optional {
106351**   varint nTerm;           (length of first term)
106352**   char pTerm[nTerm];      (content of first term)
106353**   array {
106354**                                (further terms are delta-encoded)
106355**     varint nPrefix;            (length of shared prefix with previous term)
106356**     varint nSuffix;            (length of unshared suffix)
106357**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
106358**   }
106359** }
106360**
106361** Here, optional { X } means an optional element, while array { X }
106362** means zero or more occurrences of X, adjacent in memory.
106363**
106364** An interior node encodes n terms separating n+1 subtrees.  The
106365** subtree blocks are contiguous, so only the first subtree's blockid
106366** is encoded.  The subtree at iBlockid will contain all terms less
106367** than the first term encoded (or all terms if no term is encoded).
106368** Otherwise, for terms greater than or equal to pTerm[i] but less
106369** than pTerm[i+1], the subtree for that term will be rooted at
106370** iBlockid+i.  Interior nodes only store enough term data to
106371** distinguish adjacent children (if the rightmost term of the left
106372** child is "something", and the leftmost term of the right child is
106373** "wicked", only "w" is stored).
106374**
106375** New data is spilled to a new interior node at the same height when
106376** the current node exceeds INTERIOR_MAX bytes (default 2048).
106377** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
106378** interior nodes and making the tree too skinny.  The interior nodes
106379** at a given height are naturally tracked by interior nodes at
106380** height+1, and so on.
106381**
106382**
106383**** Segment directory ****
106384** The segment directory in table %_segdir stores meta-information for
106385** merging and deleting segments, and also the root node of the
106386** segment's tree.
106387**
106388** The root node is the top node of the segment's tree after encoding
106389** the entire segment, restricted to ROOT_MAX bytes (default 1024).
106390** This could be either a leaf node or an interior node.  If the top
106391** node requires more than ROOT_MAX bytes, it is flushed to %_segments
106392** and a new root interior node is generated (which should always fit
106393** within ROOT_MAX because it only needs space for 2 varints, the
106394** height and the blockid of the previous root).
106395**
106396** The meta-information in the segment directory is:
106397**   level               - segment level (see below)
106398**   idx                 - index within level
106399**                       - (level,idx uniquely identify a segment)
106400**   start_block         - first leaf node
106401**   leaves_end_block    - last leaf node
106402**   end_block           - last block (including interior nodes)
106403**   root                - contents of root node
106404**
106405** If the root node is a leaf node, then start_block,
106406** leaves_end_block, and end_block are all 0.
106407**
106408**
106409**** Segment merging ****
106410** To amortize update costs, segments are grouped into levels and
106411** merged in batches.  Each increase in level represents exponentially
106412** more documents.
106413**
106414** New documents (actually, document updates) are tokenized and
106415** written individually (using LeafWriter) to a level 0 segment, with
106416** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
106417** level 0 segments are merged into a single level 1 segment.  Level 1
106418** is populated like level 0, and eventually MERGE_COUNT level 1
106419** segments are merged to a single level 2 segment (representing
106420** MERGE_COUNT^2 updates), and so on.
106421**
106422** A segment merge traverses all segments at a given level in
106423** parallel, performing a straightforward sorted merge.  Since segment
106424** leaf nodes are written in to the %_segments table in order, this
106425** merge traverses the underlying sqlite disk structures efficiently.
106426** After the merge, all segment blocks from the merged level are
106427** deleted.
106428**
106429** MERGE_COUNT controls how often we merge segments.  16 seems to be
106430** somewhat of a sweet spot for insertion performance.  32 and 64 show
106431** very similar performance numbers to 16 on insertion, though they're
106432** a tiny bit slower (perhaps due to more overhead in merge-time
106433** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
106434** 16, 2 about 66% slower than 16.
106435**
106436** At query time, high MERGE_COUNT increases the number of segments
106437** which need to be scanned and merged.  For instance, with 100k docs
106438** inserted:
106439**
106440**    MERGE_COUNT   segments
106441**       16           25
106442**        8           12
106443**        4           10
106444**        2            6
106445**
106446** This appears to have only a moderate impact on queries for very
106447** frequent terms (which are somewhat dominated by segment merge
106448** costs), and infrequent and non-existent terms still seem to be fast
106449** even with many segments.
106450**
106451** TODO(shess) That said, it would be nice to have a better query-side
106452** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
106453** optimizations to things like doclist merging will swing the sweet
106454** spot around.
106455**
106456**
106457**
106458**** Handling of deletions and updates ****
106459** Since we're using a segmented structure, with no docid-oriented
106460** index into the term index, we clearly cannot simply update the term
106461** index when a document is deleted or updated.  For deletions, we
106462** write an empty doclist (varint(docid) varint(POS_END)), for updates
106463** we simply write the new doclist.  Segment merges overwrite older
106464** data for a particular docid with newer data, so deletes or updates
106465** will eventually overtake the earlier data and knock it out.  The
106466** query logic likewise merges doclists so that newer data knocks out
106467** older data.
106468**
106469** TODO(shess) Provide a VACUUM type operation to clear out all
106470** deletions and duplications.  This would basically be a forced merge
106471** into a single segment.
106472*/
106473
106474#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
106475
106476#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
106477# define SQLITE_CORE 1
106478#endif
106479
106480/************** Include fts3Int.h in the middle of fts3.c ********************/
106481/************** Begin file fts3Int.h *****************************************/
106482/*
106483** 2009 Nov 12
106484**
106485** The author disclaims copyright to this source code.  In place of
106486** a legal notice, here is a blessing:
106487**
106488**    May you do good and not evil.
106489**    May you find forgiveness for yourself and forgive others.
106490**    May you share freely, never taking more than you give.
106491**
106492******************************************************************************
106493**
106494*/
106495
106496#ifndef _FTSINT_H
106497#define _FTSINT_H
106498
106499#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
106500# define NDEBUG 1
106501#endif
106502
106503/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
106504/************** Begin file fts3_tokenizer.h **********************************/
106505/*
106506** 2006 July 10
106507**
106508** The author disclaims copyright to this source code.
106509**
106510*************************************************************************
106511** Defines the interface to tokenizers used by fulltext-search.  There
106512** are three basic components:
106513**
106514** sqlite3_tokenizer_module is a singleton defining the tokenizer
106515** interface functions.  This is essentially the class structure for
106516** tokenizers.
106517**
106518** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
106519** including customization information defined at creation time.
106520**
106521** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
106522** tokens from a particular input.
106523*/
106524#ifndef _FTS3_TOKENIZER_H_
106525#define _FTS3_TOKENIZER_H_
106526
106527/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
106528** If tokenizers are to be allowed to call sqlite3_*() functions, then
106529** we will need a way to register the API consistently.
106530*/
106531
106532/*
106533** Structures used by the tokenizer interface. When a new tokenizer
106534** implementation is registered, the caller provides a pointer to
106535** an sqlite3_tokenizer_module containing pointers to the callback
106536** functions that make up an implementation.
106537**
106538** When an fts3 table is created, it passes any arguments passed to
106539** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
106540** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
106541** implementation. The xCreate() function in turn returns an
106542** sqlite3_tokenizer structure representing the specific tokenizer to
106543** be used for the fts3 table (customized by the tokenizer clause arguments).
106544**
106545** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
106546** method is called. It returns an sqlite3_tokenizer_cursor object
106547** that may be used to tokenize a specific input buffer based on
106548** the tokenization rules supplied by a specific sqlite3_tokenizer
106549** object.
106550*/
106551typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
106552typedef struct sqlite3_tokenizer sqlite3_tokenizer;
106553typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
106554
106555struct sqlite3_tokenizer_module {
106556
106557  /*
106558  ** Structure version. Should always be set to 0.
106559  */
106560  int iVersion;
106561
106562  /*
106563  ** Create a new tokenizer. The values in the argv[] array are the
106564  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
106565  ** TABLE statement that created the fts3 table. For example, if
106566  ** the following SQL is executed:
106567  **
106568  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
106569  **
106570  ** then argc is set to 2, and the argv[] array contains pointers
106571  ** to the strings "arg1" and "arg2".
106572  **
106573  ** This method should return either SQLITE_OK (0), or an SQLite error
106574  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
106575  ** to point at the newly created tokenizer structure. The generic
106576  ** sqlite3_tokenizer.pModule variable should not be initialised by
106577  ** this callback. The caller will do so.
106578  */
106579  int (*xCreate)(
106580    int argc,                           /* Size of argv array */
106581    const char *const*argv,             /* Tokenizer argument strings */
106582    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
106583  );
106584
106585  /*
106586  ** Destroy an existing tokenizer. The fts3 module calls this method
106587  ** exactly once for each successful call to xCreate().
106588  */
106589  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
106590
106591  /*
106592  ** Create a tokenizer cursor to tokenize an input buffer. The caller
106593  ** is responsible for ensuring that the input buffer remains valid
106594  ** until the cursor is closed (using the xClose() method).
106595  */
106596  int (*xOpen)(
106597    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
106598    const char *pInput, int nBytes,      /* Input buffer */
106599    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
106600  );
106601
106602  /*
106603  ** Destroy an existing tokenizer cursor. The fts3 module calls this
106604  ** method exactly once for each successful call to xOpen().
106605  */
106606  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
106607
106608  /*
106609  ** Retrieve the next token from the tokenizer cursor pCursor. This
106610  ** method should either return SQLITE_OK and set the values of the
106611  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
106612  ** the end of the buffer has been reached, or an SQLite error code.
106613  **
106614  ** *ppToken should be set to point at a buffer containing the
106615  ** normalized version of the token (i.e. after any case-folding and/or
106616  ** stemming has been performed). *pnBytes should be set to the length
106617  ** of this buffer in bytes. The input text that generated the token is
106618  ** identified by the byte offsets returned in *piStartOffset and
106619  ** *piEndOffset. *piStartOffset should be set to the index of the first
106620  ** byte of the token in the input buffer. *piEndOffset should be set
106621  ** to the index of the first byte just past the end of the token in
106622  ** the input buffer.
106623  **
106624  ** The buffer *ppToken is set to point at is managed by the tokenizer
106625  ** implementation. It is only required to be valid until the next call
106626  ** to xNext() or xClose().
106627  */
106628  /* TODO(shess) current implementation requires pInput to be
106629  ** nul-terminated.  This should either be fixed, or pInput/nBytes
106630  ** should be converted to zInput.
106631  */
106632  int (*xNext)(
106633    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
106634    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
106635    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
106636    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
106637    int *piPosition      /* OUT: Number of tokens returned before this one */
106638  );
106639};
106640
106641struct sqlite3_tokenizer {
106642  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
106643  /* Tokenizer implementations will typically add additional fields */
106644};
106645
106646struct sqlite3_tokenizer_cursor {
106647  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
106648  /* Tokenizer implementations will typically add additional fields */
106649};
106650
106651int fts3_global_term_cnt(int iTerm, int iCol);
106652int fts3_term_cnt(int iTerm, int iCol);
106653
106654
106655#endif /* _FTS3_TOKENIZER_H_ */
106656
106657/************** End of fts3_tokenizer.h **************************************/
106658/************** Continuing where we left off in fts3Int.h ********************/
106659/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
106660/************** Begin file fts3_hash.h ***************************************/
106661/*
106662** 2001 September 22
106663**
106664** The author disclaims copyright to this source code.  In place of
106665** a legal notice, here is a blessing:
106666**
106667**    May you do good and not evil.
106668**    May you find forgiveness for yourself and forgive others.
106669**    May you share freely, never taking more than you give.
106670**
106671*************************************************************************
106672** This is the header file for the generic hash-table implemenation
106673** used in SQLite.  We've modified it slightly to serve as a standalone
106674** hash table implementation for the full-text indexing module.
106675**
106676*/
106677#ifndef _FTS3_HASH_H_
106678#define _FTS3_HASH_H_
106679
106680/* Forward declarations of structures. */
106681typedef struct Fts3Hash Fts3Hash;
106682typedef struct Fts3HashElem Fts3HashElem;
106683
106684/* A complete hash table is an instance of the following structure.
106685** The internals of this structure are intended to be opaque -- client
106686** code should not attempt to access or modify the fields of this structure
106687** directly.  Change this structure only by using the routines below.
106688** However, many of the "procedures" and "functions" for modifying and
106689** accessing this structure are really macros, so we can't really make
106690** this structure opaque.
106691*/
106692struct Fts3Hash {
106693  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
106694  char copyKey;           /* True if copy of key made on insert */
106695  int count;              /* Number of entries in this table */
106696  Fts3HashElem *first;    /* The first element of the array */
106697  int htsize;             /* Number of buckets in the hash table */
106698  struct _fts3ht {        /* the hash table */
106699    int count;               /* Number of entries with this hash */
106700    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
106701  } *ht;
106702};
106703
106704/* Each element in the hash table is an instance of the following
106705** structure.  All elements are stored on a single doubly-linked list.
106706**
106707** Again, this structure is intended to be opaque, but it can't really
106708** be opaque because it is used by macros.
106709*/
106710struct Fts3HashElem {
106711  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
106712  void *data;                /* Data associated with this element */
106713  void *pKey; int nKey;      /* Key associated with this element */
106714};
106715
106716/*
106717** There are 2 different modes of operation for a hash table:
106718**
106719**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
106720**                           (including the null-terminator, if any).  Case
106721**                           is respected in comparisons.
106722**
106723**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
106724**                           memcmp() is used to compare keys.
106725**
106726** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
106727*/
106728#define FTS3_HASH_STRING    1
106729#define FTS3_HASH_BINARY    2
106730
106731/*
106732** Access routines.  To delete, insert a NULL pointer.
106733*/
106734SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
106735SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
106736SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
106737SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
106738SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
106739
106740/*
106741** Shorthand for the functions above
106742*/
106743#define fts3HashInit     sqlite3Fts3HashInit
106744#define fts3HashInsert   sqlite3Fts3HashInsert
106745#define fts3HashFind     sqlite3Fts3HashFind
106746#define fts3HashClear    sqlite3Fts3HashClear
106747#define fts3HashFindElem sqlite3Fts3HashFindElem
106748
106749/*
106750** Macros for looping over all elements of a hash table.  The idiom is
106751** like this:
106752**
106753**   Fts3Hash h;
106754**   Fts3HashElem *p;
106755**   ...
106756**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
106757**     SomeStructure *pData = fts3HashData(p);
106758**     // do something with pData
106759**   }
106760*/
106761#define fts3HashFirst(H)  ((H)->first)
106762#define fts3HashNext(E)   ((E)->next)
106763#define fts3HashData(E)   ((E)->data)
106764#define fts3HashKey(E)    ((E)->pKey)
106765#define fts3HashKeysize(E) ((E)->nKey)
106766
106767/*
106768** Number of entries in a hash table
106769*/
106770#define fts3HashCount(H)  ((H)->count)
106771
106772#endif /* _FTS3_HASH_H_ */
106773
106774/************** End of fts3_hash.h *******************************************/
106775/************** Continuing where we left off in fts3Int.h ********************/
106776
106777/*
106778** This constant controls how often segments are merged. Once there are
106779** FTS3_MERGE_COUNT segments of level N, they are merged into a single
106780** segment of level N+1.
106781*/
106782#define FTS3_MERGE_COUNT 16
106783
106784/*
106785** This is the maximum amount of data (in bytes) to store in the
106786** Fts3Table.pendingTerms hash table. Normally, the hash table is
106787** populated as documents are inserted/updated/deleted in a transaction
106788** and used to create a new segment when the transaction is committed.
106789** However if this limit is reached midway through a transaction, a new
106790** segment is created and the hash table cleared immediately.
106791*/
106792#define FTS3_MAX_PENDING_DATA (1*1024*1024)
106793
106794/*
106795** Macro to return the number of elements in an array. SQLite has a
106796** similar macro called ArraySize(). Use a different name to avoid
106797** a collision when building an amalgamation with built-in FTS3.
106798*/
106799#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
106800
106801/*
106802** Maximum length of a varint encoded integer. The varint format is different
106803** from that used by SQLite, so the maximum length is 10, not 9.
106804*/
106805#define FTS3_VARINT_MAX 10
106806
106807/*
106808** The testcase() macro is only used by the amalgamation.  If undefined,
106809** make it a no-op.
106810*/
106811#ifndef testcase
106812# define testcase(X)
106813#endif
106814
106815/*
106816** Terminator values for position-lists and column-lists.
106817*/
106818#define POS_COLUMN  (1)     /* Column-list terminator */
106819#define POS_END     (0)     /* Position-list terminator */
106820
106821/*
106822** This section provides definitions to allow the
106823** FTS3 extension to be compiled outside of the
106824** amalgamation.
106825*/
106826#ifndef SQLITE_AMALGAMATION
106827/*
106828** Macros indicating that conditional expressions are always true or
106829** false.
106830*/
106831# define ALWAYS(x) (x)
106832# define NEVER(X)  (x)
106833/*
106834** Internal types used by SQLite.
106835*/
106836typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
106837typedef short int i16;            /* 2-byte (or larger) signed integer */
106838typedef unsigned int u32;         /* 4-byte unsigned integer */
106839typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
106840/*
106841** Macro used to suppress compiler warnings for unused parameters.
106842*/
106843#define UNUSED_PARAMETER(x) (void)(x)
106844#endif
106845
106846typedef struct Fts3Table Fts3Table;
106847typedef struct Fts3Cursor Fts3Cursor;
106848typedef struct Fts3Expr Fts3Expr;
106849typedef struct Fts3Phrase Fts3Phrase;
106850typedef struct Fts3SegReader Fts3SegReader;
106851typedef struct Fts3SegFilter Fts3SegFilter;
106852
106853/*
106854** A connection to a fulltext index is an instance of the following
106855** structure. The xCreate and xConnect methods create an instance
106856** of this structure and xDestroy and xDisconnect free that instance.
106857** All other methods receive a pointer to the structure as one of their
106858** arguments.
106859*/
106860struct Fts3Table {
106861  sqlite3_vtab base;              /* Base class used by SQLite core */
106862  sqlite3 *db;                    /* The database connection */
106863  const char *zDb;                /* logical database name */
106864  const char *zName;              /* virtual table name */
106865  int nColumn;                    /* number of named columns in virtual table */
106866  char **azColumn;                /* column names.  malloced */
106867  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
106868
106869  /* Precompiled statements used by the implementation. Each of these
106870  ** statements is run and reset within a single virtual table API call.
106871  */
106872  sqlite3_stmt *aStmt[25];
106873
106874  /* Pointer to string containing the SQL:
106875  **
106876  ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
106877  **    ORDER BY blockid"
106878  */
106879  char *zSelectLeaves;
106880  int nLeavesStmt;                /* Valid statements in aLeavesStmt */
106881  int nLeavesTotal;               /* Total number of prepared leaves stmts */
106882  int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
106883  sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
106884
106885  int nNodeSize;                  /* Soft limit for node size */
106886  u8 bHasContent;                 /* True if %_content table exists */
106887  u8 bHasDocsize;                 /* True if %_docsize table exists */
106888
106889  /* The following hash table is used to buffer pending index updates during
106890  ** transactions. Variable nPendingData estimates the memory size of the
106891  ** pending data, including hash table overhead, but not malloc overhead.
106892  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
106893  ** automatically. Variable iPrevDocid is the docid of the most recently
106894  ** inserted record.
106895  */
106896  int nMaxPendingData;
106897  int nPendingData;
106898  sqlite_int64 iPrevDocid;
106899  Fts3Hash pendingTerms;
106900};
106901
106902/*
106903** When the core wants to read from the virtual table, it creates a
106904** virtual table cursor (an instance of the following structure) using
106905** the xOpen method. Cursors are destroyed using the xClose method.
106906*/
106907struct Fts3Cursor {
106908  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
106909  i16 eSearch;                    /* Search strategy (see below) */
106910  u8 isEof;                       /* True if at End Of Results */
106911  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
106912  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
106913  Fts3Expr *pExpr;                /* Parsed MATCH query string */
106914  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
106915  char *pNextId;                  /* Pointer into the body of aDoclist */
106916  char *aDoclist;                 /* List of docids for full-text queries */
106917  int nDoclist;                   /* Size of buffer at aDoclist */
106918  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
106919  u32 *aMatchinfo;                /* Information about most recent match */
106920};
106921
106922/*
106923** The Fts3Cursor.eSearch member is always set to one of the following.
106924** Actualy, Fts3Cursor.eSearch can be greater than or equal to
106925** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
106926** of the column to be searched.  For example, in
106927**
106928**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
106929**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
106930**
106931** Because the LHS of the MATCH operator is 2nd column "b",
106932** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
106933** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
106934** indicating that all columns should be searched,
106935** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
106936*/
106937#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
106938#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
106939#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
106940
106941/*
106942** A "phrase" is a sequence of one or more tokens that must match in
106943** sequence.  A single token is the base case and the most common case.
106944** For a sequence of tokens contained in "...", nToken will be the number
106945** of tokens in the string.
106946*/
106947struct Fts3Phrase {
106948  int nToken;                /* Number of tokens in the phrase */
106949  int iColumn;               /* Index of column this phrase must match */
106950  int isNot;                 /* Phrase prefixed by unary not (-) operator */
106951  struct PhraseToken {
106952    char *z;                 /* Text of the token */
106953    int n;                   /* Number of bytes in buffer pointed to by z */
106954    int isPrefix;            /* True if token ends in with a "*" character */
106955  } aToken[1];               /* One entry for each token in the phrase */
106956};
106957
106958/*
106959** A tree of these objects forms the RHS of a MATCH operator.
106960**
106961** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
106962** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
106963** containing the results of the NEAR or phrase query in FTS3 doclist
106964** format. As usual, the initial "Length" field found in doclists stored
106965** on disk is omitted from this buffer.
106966**
106967** Variable pCurrent always points to the start of a docid field within
106968** aDoclist. Since the doclist is usually scanned in docid order, this can
106969** be used to accelerate seeking to the required docid within the doclist.
106970*/
106971struct Fts3Expr {
106972  int eType;                 /* One of the FTSQUERY_XXX values defined below */
106973  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
106974  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
106975  Fts3Expr *pLeft;           /* Left operand */
106976  Fts3Expr *pRight;          /* Right operand */
106977  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
106978
106979  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
106980  char *aDoclist;            /* Buffer containing doclist */
106981  int nDoclist;              /* Size of aDoclist in bytes */
106982
106983  sqlite3_int64 iCurrent;
106984  char *pCurrent;
106985};
106986
106987/*
106988** Candidate values for Fts3Query.eType. Note that the order of the first
106989** four values is in order of precedence when parsing expressions. For
106990** example, the following:
106991**
106992**   "a OR b AND c NOT d NEAR e"
106993**
106994** is equivalent to:
106995**
106996**   "a OR (b AND (c NOT (d NEAR e)))"
106997*/
106998#define FTSQUERY_NEAR   1
106999#define FTSQUERY_NOT    2
107000#define FTSQUERY_AND    3
107001#define FTSQUERY_OR     4
107002#define FTSQUERY_PHRASE 5
107003
107004
107005/* fts3_init.c */
107006SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
107007SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
107008                        sqlite3_vtab **, char **);
107009
107010/* fts3_write.c */
107011SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
107012SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
107013SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
107014SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
107015SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
107016  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
107017SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
107018SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
107019SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
107020  Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
107021  int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
107022);
107023SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
107024SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
107025SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
107026SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
107027
107028/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
107029#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
107030#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
107031#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
107032#define FTS3_SEGMENT_PREFIX        0x00000008
107033
107034/* Type passed as 4th argument to SegmentReaderIterate() */
107035struct Fts3SegFilter {
107036  const char *zTerm;
107037  int nTerm;
107038  int iCol;
107039  int flags;
107040};
107041
107042/* fts3.c */
107043SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
107044SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
107045SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
107046SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
107047SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
107048
107049SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
107050SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
107051SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
107052
107053/* fts3_tokenizer.c */
107054SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
107055SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
107056SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
107057  const char *, sqlite3_tokenizer **, const char **, char **
107058);
107059
107060/* fts3_snippet.c */
107061SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
107062SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
107063  const char *, const char *, int, int
107064);
107065SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
107066
107067/* fts3_expr.c */
107068SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
107069  char **, int, int, const char *, int, Fts3Expr **
107070);
107071SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
107072#ifdef SQLITE_TEST
107073SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
107074#endif
107075
107076#endif /* _FTSINT_H */
107077
107078/************** End of fts3Int.h *********************************************/
107079/************** Continuing where we left off in fts3.c ***********************/
107080
107081
107082#ifndef SQLITE_CORE
107083  SQLITE_EXTENSION_INIT1
107084#endif
107085
107086/*
107087** Write a 64-bit variable-length integer to memory starting at p[0].
107088** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
107089** The number of bytes written is returned.
107090*/
107091SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
107092  unsigned char *q = (unsigned char *) p;
107093  sqlite_uint64 vu = v;
107094  do{
107095    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
107096    vu >>= 7;
107097  }while( vu!=0 );
107098  q[-1] &= 0x7f;  /* turn off high bit in final byte */
107099  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
107100  return (int) (q - (unsigned char *)p);
107101}
107102
107103/*
107104** Read a 64-bit variable-length integer from memory starting at p[0].
107105** Return the number of bytes read, or 0 on error.
107106** The value is stored in *v.
107107*/
107108SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
107109  const unsigned char *q = (const unsigned char *) p;
107110  sqlite_uint64 x = 0, y = 1;
107111  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
107112    x += y * (*q++ & 0x7f);
107113    y <<= 7;
107114  }
107115  x += y * (*q++);
107116  *v = (sqlite_int64) x;
107117  return (int) (q - (unsigned char *)p);
107118}
107119
107120/*
107121** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
107122** 32-bit integer before it is returned.
107123*/
107124SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
107125 sqlite_int64 i;
107126 int ret = sqlite3Fts3GetVarint(p, &i);
107127 *pi = (int) i;
107128 return ret;
107129}
107130
107131/*
107132** Return the number of bytes required to encode v as a varint
107133*/
107134SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
107135  int i = 0;
107136  do{
107137    i++;
107138    v >>= 7;
107139  }while( v!=0 );
107140  return i;
107141}
107142
107143/*
107144** Convert an SQL-style quoted string into a normal string by removing
107145** the quote characters.  The conversion is done in-place.  If the
107146** input does not begin with a quote character, then this routine
107147** is a no-op.
107148**
107149** Examples:
107150**
107151**     "abc"   becomes   abc
107152**     'xyz'   becomes   xyz
107153**     [pqr]   becomes   pqr
107154**     `mno`   becomes   mno
107155**
107156*/
107157SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
107158  char quote;                     /* Quote character (if any ) */
107159
107160  quote = z[0];
107161  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
107162    int iIn = 1;                  /* Index of next byte to read from input */
107163    int iOut = 0;                 /* Index of next byte to write to output */
107164
107165    /* If the first byte was a '[', then the close-quote character is a ']' */
107166    if( quote=='[' ) quote = ']';
107167
107168    while( ALWAYS(z[iIn]) ){
107169      if( z[iIn]==quote ){
107170        if( z[iIn+1]!=quote ) break;
107171        z[iOut++] = quote;
107172        iIn += 2;
107173      }else{
107174        z[iOut++] = z[iIn++];
107175      }
107176    }
107177    z[iOut] = '\0';
107178  }
107179}
107180
107181/*
107182** Read a single varint from the doclist at *pp and advance *pp to point
107183** to the first byte past the end of the varint.  Add the value of the varint
107184** to *pVal.
107185*/
107186static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
107187  sqlite3_int64 iVal;
107188  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
107189  *pVal += iVal;
107190}
107191
107192/*
107193** As long as *pp has not reached its end (pEnd), then do the same
107194** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
107195** But if we have reached the end of the varint, just set *pp=0 and
107196** leave *pVal unchanged.
107197*/
107198static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
107199  if( *pp>=pEnd ){
107200    *pp = 0;
107201  }else{
107202    fts3GetDeltaVarint(pp, pVal);
107203  }
107204}
107205
107206/*
107207** The xDisconnect() virtual table method.
107208*/
107209static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
107210  Fts3Table *p = (Fts3Table *)pVtab;
107211  int i;
107212
107213  assert( p->nPendingData==0 );
107214
107215  /* Free any prepared statements held */
107216  for(i=0; i<SizeofArray(p->aStmt); i++){
107217    sqlite3_finalize(p->aStmt[i]);
107218  }
107219  for(i=0; i<p->nLeavesStmt; i++){
107220    sqlite3_finalize(p->aLeavesStmt[i]);
107221  }
107222  sqlite3_free(p->zSelectLeaves);
107223  sqlite3_free(p->aLeavesStmt);
107224
107225  /* Invoke the tokenizer destructor to free the tokenizer. */
107226  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
107227
107228  sqlite3_free(p);
107229  return SQLITE_OK;
107230}
107231
107232/*
107233** Construct one or more SQL statements from the format string given
107234** and then evaluate those statements.  The success code is writting
107235** into *pRc.
107236**
107237** If *pRc is initially non-zero then this routine is a no-op.
107238*/
107239static void fts3DbExec(
107240  int *pRc,              /* Success code */
107241  sqlite3 *db,           /* Database in which to run SQL */
107242  const char *zFormat,   /* Format string for SQL */
107243  ...                    /* Arguments to the format string */
107244){
107245  va_list ap;
107246  char *zSql;
107247  if( *pRc ) return;
107248  va_start(ap, zFormat);
107249  zSql = sqlite3_vmprintf(zFormat, ap);
107250  va_end(ap);
107251  if( zSql==0 ){
107252    *pRc = SQLITE_NOMEM;
107253  }else{
107254    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
107255    sqlite3_free(zSql);
107256  }
107257}
107258
107259/*
107260** The xDestroy() virtual table method.
107261*/
107262static int fts3DestroyMethod(sqlite3_vtab *pVtab){
107263  int rc = SQLITE_OK;              /* Return code */
107264  Fts3Table *p = (Fts3Table *)pVtab;
107265  sqlite3 *db = p->db;
107266
107267  /* Drop the shadow tables */
107268  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
107269  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
107270  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
107271  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
107272  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
107273
107274  /* If everything has worked, invoke fts3DisconnectMethod() to free the
107275  ** memory associated with the Fts3Table structure and return SQLITE_OK.
107276  ** Otherwise, return an SQLite error code.
107277  */
107278  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
107279}
107280
107281
107282/*
107283** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
107284** passed as the first argument. This is done as part of the xConnect()
107285** and xCreate() methods.
107286*/
107287static int fts3DeclareVtab(Fts3Table *p){
107288  int i;                          /* Iterator variable */
107289  int rc;                         /* Return code */
107290  char *zSql;                     /* SQL statement passed to declare_vtab() */
107291  char *zCols;                    /* List of user defined columns */
107292
107293  /* Create a list of user columns for the virtual table */
107294  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
107295  for(i=1; zCols && i<p->nColumn; i++){
107296    zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
107297  }
107298
107299  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
107300  zSql = sqlite3_mprintf(
107301      "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
107302  );
107303
107304  if( !zCols || !zSql ){
107305    rc = SQLITE_NOMEM;
107306  }else{
107307    rc = sqlite3_declare_vtab(p->db, zSql);
107308  }
107309
107310  sqlite3_free(zSql);
107311  sqlite3_free(zCols);
107312  return rc;
107313}
107314
107315/*
107316** Create the backing store tables (%_content, %_segments and %_segdir)
107317** required by the FTS3 table passed as the only argument. This is done
107318** as part of the vtab xCreate() method.
107319**
107320** If the p->bHasDocsize boolean is true (indicating that this is an
107321** FTS4 table, not an FTS3 table) then also create the %_docsize and
107322** %_stat tables required by FTS4.
107323*/
107324static int fts3CreateTables(Fts3Table *p){
107325  int rc = SQLITE_OK;             /* Return code */
107326  int i;                          /* Iterator variable */
107327  char *zContentCols;             /* Columns of %_content table */
107328  sqlite3 *db = p->db;            /* The database connection */
107329
107330  /* Create a list of user columns for the content table */
107331  if( p->bHasContent ){
107332    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
107333    for(i=0; zContentCols && i<p->nColumn; i++){
107334      char *z = p->azColumn[i];
107335      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
107336    }
107337    if( zContentCols==0 ) rc = SQLITE_NOMEM;
107338
107339    /* Create the content table */
107340    fts3DbExec(&rc, db,
107341       "CREATE TABLE %Q.'%q_content'(%s)",
107342       p->zDb, p->zName, zContentCols
107343    );
107344    sqlite3_free(zContentCols);
107345  }
107346  /* Create other tables */
107347  fts3DbExec(&rc, db,
107348      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
107349      p->zDb, p->zName
107350  );
107351  fts3DbExec(&rc, db,
107352      "CREATE TABLE %Q.'%q_segdir'("
107353        "level INTEGER,"
107354        "idx INTEGER,"
107355        "start_block INTEGER,"
107356        "leaves_end_block INTEGER,"
107357        "end_block INTEGER,"
107358        "root BLOB,"
107359        "PRIMARY KEY(level, idx)"
107360      ");",
107361      p->zDb, p->zName
107362  );
107363  if( p->bHasDocsize ){
107364    fts3DbExec(&rc, db,
107365        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
107366        p->zDb, p->zName
107367    );
107368    fts3DbExec(&rc, db,
107369        "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
107370        p->zDb, p->zName
107371    );
107372  }
107373  return rc;
107374}
107375
107376/*
107377** An sqlite3_exec() callback for fts3TableExists.
107378*/
107379static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
107380  UNUSED_PARAMETER(n);
107381  UNUSED_PARAMETER(pp1);
107382  UNUSED_PARAMETER(pp2);
107383  *(int*)pArg = 1;
107384  return 1;
107385}
107386
107387/*
107388** Determine if a table currently exists in the database.
107389*/
107390static void fts3TableExists(
107391  int *pRc,             /* Success code */
107392  sqlite3 *db,          /* The database connection to test */
107393  const char *zDb,      /* ATTACHed database within the connection */
107394  const char *zName,    /* Name of the FTS3 table */
107395  const char *zSuffix,  /* Shadow table extension */
107396  u8 *pResult           /* Write results here */
107397){
107398  int rc = SQLITE_OK;
107399  int res = 0;
107400  char *zSql;
107401  if( *pRc ) return;
107402  zSql = sqlite3_mprintf(
107403    "SELECT 1 FROM %Q.sqlite_master WHERE name='%q%s'",
107404    zDb, zName, zSuffix
107405  );
107406  rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
107407  sqlite3_free(zSql);
107408  *pResult = (u8)(res & 0xff);
107409  if( rc!=SQLITE_ABORT ) *pRc = rc;
107410}
107411
107412/*
107413** This function is the implementation of both the xConnect and xCreate
107414** methods of the FTS3 virtual table.
107415**
107416** The argv[] array contains the following:
107417**
107418**   argv[0]   -> module name  ("fts3" or "fts4")
107419**   argv[1]   -> database name
107420**   argv[2]   -> table name
107421**   argv[...] -> "column name" and other module argument fields.
107422*/
107423static int fts3InitVtab(
107424  int isCreate,                   /* True for xCreate, false for xConnect */
107425  sqlite3 *db,                    /* The SQLite database connection */
107426  void *pAux,                     /* Hash table containing tokenizers */
107427  int argc,                       /* Number of elements in argv array */
107428  const char * const *argv,       /* xCreate/xConnect argument array */
107429  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
107430  char **pzErr                    /* Write any error message here */
107431){
107432  Fts3Hash *pHash = (Fts3Hash *)pAux;
107433  Fts3Table *p;                   /* Pointer to allocated vtab */
107434  int rc;                         /* Return code */
107435  int i;                          /* Iterator variable */
107436  int nByte;                      /* Size of allocation used for *p */
107437  int iCol;                       /* Column index */
107438  int nString = 0;                /* Bytes required to hold all column names */
107439  int nCol = 0;                   /* Number of columns in the FTS table */
107440  char *zCsr;                     /* Space for holding column names */
107441  int nDb;                        /* Bytes required to hold database name */
107442  int nName;                      /* Bytes required to hold table name */
107443
107444  const char *zTokenizer = 0;               /* Name of tokenizer to use */
107445  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
107446
107447  nDb = (int)strlen(argv[1]) + 1;
107448  nName = (int)strlen(argv[2]) + 1;
107449  for(i=3; i<argc; i++){
107450    char const *z = argv[i];
107451    rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
107452    if( rc!=SQLITE_OK ){
107453      return rc;
107454    }
107455    if( z!=zTokenizer ){
107456      nString += (int)(strlen(z) + 1);
107457    }
107458  }
107459  nCol = argc - 3 - (zTokenizer!=0);
107460  if( zTokenizer==0 ){
107461    rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
107462    if( rc!=SQLITE_OK ){
107463      return rc;
107464    }
107465    assert( pTokenizer );
107466  }
107467
107468  if( nCol==0 ){
107469    nCol = 1;
107470  }
107471
107472  /* Allocate and populate the Fts3Table structure. */
107473  nByte = sizeof(Fts3Table) +              /* Fts3Table */
107474          nCol * sizeof(char *) +              /* azColumn */
107475          nName +                              /* zName */
107476          nDb +                                /* zDb */
107477          nString;                             /* Space for azColumn strings */
107478  p = (Fts3Table*)sqlite3_malloc(nByte);
107479  if( p==0 ){
107480    rc = SQLITE_NOMEM;
107481    goto fts3_init_out;
107482  }
107483  memset(p, 0, nByte);
107484
107485  p->db = db;
107486  p->nColumn = nCol;
107487  p->nPendingData = 0;
107488  p->azColumn = (char **)&p[1];
107489  p->pTokenizer = pTokenizer;
107490  p->nNodeSize = 1000;
107491  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
107492  zCsr = (char *)&p->azColumn[nCol];
107493
107494  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
107495
107496  /* Fill in the zName and zDb fields of the vtab structure. */
107497  p->zName = zCsr;
107498  memcpy(zCsr, argv[2], nName);
107499  zCsr += nName;
107500  p->zDb = zCsr;
107501  memcpy(zCsr, argv[1], nDb);
107502  zCsr += nDb;
107503
107504  /* Fill in the azColumn array */
107505  iCol = 0;
107506  for(i=3; i<argc; i++){
107507    if( argv[i]!=zTokenizer ){
107508      char *z;
107509      int n;
107510      z = (char *)sqlite3Fts3NextToken(argv[i], &n);
107511      memcpy(zCsr, z, n);
107512      zCsr[n] = '\0';
107513      sqlite3Fts3Dequote(zCsr);
107514      p->azColumn[iCol++] = zCsr;
107515      zCsr += n+1;
107516      assert( zCsr <= &((char *)p)[nByte] );
107517    }
107518  }
107519  if( iCol==0 ){
107520    assert( nCol==1 );
107521    p->azColumn[0] = "content";
107522  }
107523
107524  /* If this is an xCreate call, create the underlying tables in the
107525  ** database. TODO: For xConnect(), it could verify that said tables exist.
107526  */
107527  if( isCreate ){
107528    p->bHasContent = 1;
107529    p->bHasDocsize = argv[0][3]=='4';
107530    rc = fts3CreateTables(p);
107531  }else{
107532    rc = SQLITE_OK;
107533    fts3TableExists(&rc, db, argv[1], argv[2], "_content", &p->bHasContent);
107534    fts3TableExists(&rc, db, argv[1], argv[2], "_docsize", &p->bHasDocsize);
107535  }
107536  if( rc!=SQLITE_OK ) goto fts3_init_out;
107537
107538  rc = fts3DeclareVtab(p);
107539  if( rc!=SQLITE_OK ) goto fts3_init_out;
107540
107541  *ppVTab = &p->base;
107542
107543fts3_init_out:
107544  assert( p || (pTokenizer && rc!=SQLITE_OK) );
107545  if( rc!=SQLITE_OK ){
107546    if( p ){
107547      fts3DisconnectMethod((sqlite3_vtab *)p);
107548    }else{
107549      pTokenizer->pModule->xDestroy(pTokenizer);
107550    }
107551  }
107552  return rc;
107553}
107554
107555/*
107556** The xConnect() and xCreate() methods for the virtual table. All the
107557** work is done in function fts3InitVtab().
107558*/
107559static int fts3ConnectMethod(
107560  sqlite3 *db,                    /* Database connection */
107561  void *pAux,                     /* Pointer to tokenizer hash table */
107562  int argc,                       /* Number of elements in argv array */
107563  const char * const *argv,       /* xCreate/xConnect argument array */
107564  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
107565  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
107566){
107567  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
107568}
107569static int fts3CreateMethod(
107570  sqlite3 *db,                    /* Database connection */
107571  void *pAux,                     /* Pointer to tokenizer hash table */
107572  int argc,                       /* Number of elements in argv array */
107573  const char * const *argv,       /* xCreate/xConnect argument array */
107574  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
107575  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
107576){
107577  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
107578}
107579
107580/*
107581** Implementation of the xBestIndex method for FTS3 tables. There
107582** are three possible strategies, in order of preference:
107583**
107584**   1. Direct lookup by rowid or docid.
107585**   2. Full-text search using a MATCH operator on a non-docid column.
107586**   3. Linear scan of %_content table.
107587*/
107588static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
107589  Fts3Table *p = (Fts3Table *)pVTab;
107590  int i;                          /* Iterator variable */
107591  int iCons = -1;                 /* Index of constraint to use */
107592
107593  /* By default use a full table scan. This is an expensive option,
107594  ** so search through the constraints to see if a more efficient
107595  ** strategy is possible.
107596  */
107597  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
107598  pInfo->estimatedCost = 500000;
107599  for(i=0; i<pInfo->nConstraint; i++){
107600    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
107601    if( pCons->usable==0 ) continue;
107602
107603    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
107604    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
107605     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
107606    ){
107607      pInfo->idxNum = FTS3_DOCID_SEARCH;
107608      pInfo->estimatedCost = 1.0;
107609      iCons = i;
107610    }
107611
107612    /* A MATCH constraint. Use a full-text search.
107613    **
107614    ** If there is more than one MATCH constraint available, use the first
107615    ** one encountered. If there is both a MATCH constraint and a direct
107616    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
107617    ** though the rowid/docid lookup is faster than a MATCH query, selecting
107618    ** it would lead to an "unable to use function MATCH in the requested
107619    ** context" error.
107620    */
107621    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
107622     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
107623    ){
107624      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
107625      pInfo->estimatedCost = 2.0;
107626      iCons = i;
107627      break;
107628    }
107629  }
107630
107631  if( iCons>=0 ){
107632    pInfo->aConstraintUsage[iCons].argvIndex = 1;
107633    pInfo->aConstraintUsage[iCons].omit = 1;
107634  }
107635  return SQLITE_OK;
107636}
107637
107638/*
107639** Implementation of xOpen method.
107640*/
107641static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
107642  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
107643
107644  UNUSED_PARAMETER(pVTab);
107645
107646  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
107647  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
107648  ** if the allocation fails, return SQLITE_NOMEM.
107649  */
107650  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
107651  if( !pCsr ){
107652    return SQLITE_NOMEM;
107653  }
107654  memset(pCsr, 0, sizeof(Fts3Cursor));
107655  return SQLITE_OK;
107656}
107657
107658/*
107659** Close the cursor.  For additional information see the documentation
107660** on the xClose method of the virtual table interface.
107661*/
107662static int fulltextClose(sqlite3_vtab_cursor *pCursor){
107663  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
107664  sqlite3_finalize(pCsr->pStmt);
107665  sqlite3Fts3ExprFree(pCsr->pExpr);
107666  sqlite3_free(pCsr->aDoclist);
107667  sqlite3_free(pCsr->aMatchinfo);
107668  sqlite3_free(pCsr);
107669  return SQLITE_OK;
107670}
107671
107672/*
107673** Position the pCsr->pStmt statement so that it is on the row
107674** of the %_content table that contains the last match.  Return
107675** SQLITE_OK on success.
107676*/
107677static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
107678  if( pCsr->isRequireSeek ){
107679    pCsr->isRequireSeek = 0;
107680    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
107681    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
107682      return SQLITE_OK;
107683    }else{
107684      int rc = sqlite3_reset(pCsr->pStmt);
107685      if( rc==SQLITE_OK ){
107686        /* If no row was found and no error has occured, then the %_content
107687        ** table is missing a row that is present in the full-text index.
107688        ** The data structures are corrupt.
107689        */
107690        rc = SQLITE_CORRUPT;
107691      }
107692      pCsr->isEof = 1;
107693      if( pContext ){
107694        sqlite3_result_error_code(pContext, rc);
107695      }
107696      return rc;
107697    }
107698  }else{
107699    return SQLITE_OK;
107700  }
107701}
107702
107703/*
107704** Advance the cursor to the next row in the %_content table that
107705** matches the search criteria.  For a MATCH search, this will be
107706** the next row that matches.  For a full-table scan, this will be
107707** simply the next row in the %_content table.  For a docid lookup,
107708** this routine simply sets the EOF flag.
107709**
107710** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
107711** even if we reach end-of-file.  The fts3EofMethod() will be called
107712** subsequently to determine whether or not an EOF was hit.
107713*/
107714static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
107715  int rc = SQLITE_OK;             /* Return code */
107716  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
107717
107718  if( pCsr->aDoclist==0 ){
107719    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
107720      pCsr->isEof = 1;
107721      rc = sqlite3_reset(pCsr->pStmt);
107722    }
107723  }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
107724    pCsr->isEof = 1;
107725  }else{
107726    sqlite3_reset(pCsr->pStmt);
107727    fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
107728    pCsr->isRequireSeek = 1;
107729    pCsr->isMatchinfoNeeded = 1;
107730  }
107731  return rc;
107732}
107733
107734
107735/*
107736** The buffer pointed to by argument zNode (size nNode bytes) contains the
107737** root node of a b-tree segment. The segment is guaranteed to be at least
107738** one level high (i.e. the root node is not also a leaf). If successful,
107739** this function locates the leaf node of the segment that may contain the
107740** term specified by arguments zTerm and nTerm and writes its block number
107741** to *piLeaf.
107742**
107743** It is possible that the returned leaf node does not contain the specified
107744** term. However, if the segment does contain said term, it is stored on
107745** the identified leaf node. Because this function only inspects interior
107746** segment nodes (and never loads leaf nodes into memory), it is not possible
107747** to be sure.
107748**
107749** If an error occurs, an error code other than SQLITE_OK is returned.
107750*/
107751static int fts3SelectLeaf(
107752  Fts3Table *p,                   /* Virtual table handle */
107753  const char *zTerm,              /* Term to select leaves for */
107754  int nTerm,                      /* Size of term zTerm in bytes */
107755  const char *zNode,              /* Buffer containing segment interior node */
107756  int nNode,                      /* Size of buffer at zNode */
107757  sqlite3_int64 *piLeaf           /* Selected leaf node */
107758){
107759  int rc = SQLITE_OK;             /* Return code */
107760  const char *zCsr = zNode;       /* Cursor to iterate through node */
107761  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
107762  char *zBuffer = 0;              /* Buffer to load terms into */
107763  int nAlloc = 0;                 /* Size of allocated buffer */
107764
107765  while( 1 ){
107766    int isFirstTerm = 1;          /* True when processing first term on page */
107767    int iHeight;                  /* Height of this node in tree */
107768    sqlite3_int64 iChild;         /* Block id of child node to descend to */
107769    int nBlock;                   /* Size of child node in bytes */
107770
107771    zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
107772    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
107773
107774    while( zCsr<zEnd ){
107775      int cmp;                    /* memcmp() result */
107776      int nSuffix;                /* Size of term suffix */
107777      int nPrefix = 0;            /* Size of term prefix */
107778      int nBuffer;                /* Total term size */
107779
107780      /* Load the next term on the node into zBuffer */
107781      if( !isFirstTerm ){
107782        zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
107783      }
107784      isFirstTerm = 0;
107785      zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
107786      if( nPrefix+nSuffix>nAlloc ){
107787        char *zNew;
107788        nAlloc = (nPrefix+nSuffix) * 2;
107789        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
107790        if( !zNew ){
107791          sqlite3_free(zBuffer);
107792          return SQLITE_NOMEM;
107793        }
107794        zBuffer = zNew;
107795      }
107796      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
107797      nBuffer = nPrefix + nSuffix;
107798      zCsr += nSuffix;
107799
107800      /* Compare the term we are searching for with the term just loaded from
107801      ** the interior node. If the specified term is greater than or equal
107802      ** to the term from the interior node, then all terms on the sub-tree
107803      ** headed by node iChild are smaller than zTerm. No need to search
107804      ** iChild.
107805      **
107806      ** If the interior node term is larger than the specified term, then
107807      ** the tree headed by iChild may contain the specified term.
107808      */
107809      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
107810      if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
107811      iChild++;
107812    };
107813
107814    /* If (iHeight==1), the children of this interior node are leaves. The
107815    ** specified term may be present on leaf node iChild.
107816    */
107817    if( iHeight==1 ){
107818      *piLeaf = iChild;
107819      break;
107820    }
107821
107822    /* Descend to interior node iChild. */
107823    rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
107824    if( rc!=SQLITE_OK ) break;
107825    zEnd = &zCsr[nBlock];
107826  }
107827  sqlite3_free(zBuffer);
107828  return rc;
107829}
107830
107831/*
107832** This function is used to create delta-encoded serialized lists of FTS3
107833** varints. Each call to this function appends a single varint to a list.
107834*/
107835static void fts3PutDeltaVarint(
107836  char **pp,                      /* IN/OUT: Output pointer */
107837  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
107838  sqlite3_int64 iVal              /* Write this value to the list */
107839){
107840  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
107841  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
107842  *piPrev = iVal;
107843}
107844
107845/*
107846** When this function is called, *ppPoslist is assumed to point to the
107847** start of a position-list. After it returns, *ppPoslist points to the
107848** first byte after the position-list.
107849**
107850** A position list is list of positions (delta encoded) and columns for
107851** a single document record of a doclist.  So, in other words, this
107852** routine advances *ppPoslist so that it points to the next docid in
107853** the doclist, or to the first byte past the end of the doclist.
107854**
107855** If pp is not NULL, then the contents of the position list are copied
107856** to *pp. *pp is set to point to the first byte past the last byte copied
107857** before this function returns.
107858*/
107859static void fts3PoslistCopy(char **pp, char **ppPoslist){
107860  char *pEnd = *ppPoslist;
107861  char c = 0;
107862
107863  /* The end of a position list is marked by a zero encoded as an FTS3
107864  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
107865  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
107866  ** of some other, multi-byte, value.
107867  **
107868  ** The following while-loop moves pEnd to point to the first byte that is not
107869  ** immediately preceded by a byte with the 0x80 bit set. Then increments
107870  ** pEnd once more so that it points to the byte immediately following the
107871  ** last byte in the position-list.
107872  */
107873  while( *pEnd | c ){
107874    c = *pEnd++ & 0x80;
107875    testcase( c!=0 && (*pEnd)==0 );
107876  }
107877  pEnd++;  /* Advance past the POS_END terminator byte */
107878
107879  if( pp ){
107880    int n = (int)(pEnd - *ppPoslist);
107881    char *p = *pp;
107882    memcpy(p, *ppPoslist, n);
107883    p += n;
107884    *pp = p;
107885  }
107886  *ppPoslist = pEnd;
107887}
107888
107889/*
107890** When this function is called, *ppPoslist is assumed to point to the
107891** start of a column-list. After it returns, *ppPoslist points to the
107892** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
107893**
107894** A column-list is list of delta-encoded positions for a single column
107895** within a single document within a doclist.
107896**
107897** The column-list is terminated either by a POS_COLUMN varint (1) or
107898** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
107899** the POS_COLUMN or POS_END that terminates the column-list.
107900**
107901** If pp is not NULL, then the contents of the column-list are copied
107902** to *pp. *pp is set to point to the first byte past the last byte copied
107903** before this function returns.  The POS_COLUMN or POS_END terminator
107904** is not copied into *pp.
107905*/
107906static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
107907  char *pEnd = *ppPoslist;
107908  char c = 0;
107909
107910  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
107911  ** not part of a multi-byte varint.
107912  */
107913  while( 0xFE & (*pEnd | c) ){
107914    c = *pEnd++ & 0x80;
107915    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
107916  }
107917  if( pp ){
107918    int n = (int)(pEnd - *ppPoslist);
107919    char *p = *pp;
107920    memcpy(p, *ppPoslist, n);
107921    p += n;
107922    *pp = p;
107923  }
107924  *ppPoslist = pEnd;
107925}
107926
107927/*
107928** Value used to signify the end of an position-list. This is safe because
107929** it is not possible to have a document with 2^31 terms.
107930*/
107931#define POSITION_LIST_END 0x7fffffff
107932
107933/*
107934** This function is used to help parse position-lists. When this function is
107935** called, *pp may point to the start of the next varint in the position-list
107936** being parsed, or it may point to 1 byte past the end of the position-list
107937** (in which case **pp will be a terminator bytes POS_END (0) or
107938** (1)).
107939**
107940** If *pp points past the end of the current position-list, set *pi to
107941** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
107942** increment the current value of *pi by the value read, and set *pp to
107943** point to the next value before returning.
107944**
107945** Before calling this routine *pi must be initialized to the value of
107946** the previous position, or zero if we are reading the first position
107947** in the position-list.  Because positions are delta-encoded, the value
107948** of the previous position is needed in order to compute the value of
107949** the next position.
107950*/
107951static void fts3ReadNextPos(
107952  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
107953  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
107954){
107955  if( (**pp)&0xFE ){
107956    fts3GetDeltaVarint(pp, pi);
107957    *pi -= 2;
107958  }else{
107959    *pi = POSITION_LIST_END;
107960  }
107961}
107962
107963/*
107964** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
107965** the value of iCol encoded as a varint to *pp.   This will start a new
107966** column list.
107967**
107968** Set *pp to point to the byte just after the last byte written before
107969** returning (do not modify it if iCol==0). Return the total number of bytes
107970** written (0 if iCol==0).
107971*/
107972static int fts3PutColNumber(char **pp, int iCol){
107973  int n = 0;                      /* Number of bytes written */
107974  if( iCol ){
107975    char *p = *pp;                /* Output pointer */
107976    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
107977    *p = 0x01;
107978    *pp = &p[n];
107979  }
107980  return n;
107981}
107982
107983/*
107984** Compute the union of two position lists.  The output written
107985** into *pp contains all positions of both *pp1 and *pp2 in sorted
107986** order and with any duplicates removed.  All pointers are
107987** updated appropriately.   The caller is responsible for insuring
107988** that there is enough space in *pp to hold the complete output.
107989*/
107990static void fts3PoslistMerge(
107991  char **pp,                      /* Output buffer */
107992  char **pp1,                     /* Left input list */
107993  char **pp2                      /* Right input list */
107994){
107995  char *p = *pp;
107996  char *p1 = *pp1;
107997  char *p2 = *pp2;
107998
107999  while( *p1 || *p2 ){
108000    int iCol1;         /* The current column index in pp1 */
108001    int iCol2;         /* The current column index in pp2 */
108002
108003    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
108004    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
108005    else iCol1 = 0;
108006
108007    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
108008    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
108009    else iCol2 = 0;
108010
108011    if( iCol1==iCol2 ){
108012      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
108013      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
108014      sqlite3_int64 iPrev = 0;
108015      int n = fts3PutColNumber(&p, iCol1);
108016      p1 += n;
108017      p2 += n;
108018
108019      /* At this point, both p1 and p2 point to the start of column-lists
108020      ** for the same column (the column with index iCol1 and iCol2).
108021      ** A column-list is a list of non-negative delta-encoded varints, each
108022      ** incremented by 2 before being stored. Each list is terminated by a
108023      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
108024      ** and writes the results to buffer p. p is left pointing to the byte
108025      ** after the list written. No terminator (POS_END or POS_COLUMN) is
108026      ** written to the output.
108027      */
108028      fts3GetDeltaVarint(&p1, &i1);
108029      fts3GetDeltaVarint(&p2, &i2);
108030      do {
108031        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
108032        iPrev -= 2;
108033        if( i1==i2 ){
108034          fts3ReadNextPos(&p1, &i1);
108035          fts3ReadNextPos(&p2, &i2);
108036        }else if( i1<i2 ){
108037          fts3ReadNextPos(&p1, &i1);
108038        }else{
108039          fts3ReadNextPos(&p2, &i2);
108040        }
108041      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
108042    }else if( iCol1<iCol2 ){
108043      p1 += fts3PutColNumber(&p, iCol1);
108044      fts3ColumnlistCopy(&p, &p1);
108045    }else{
108046      p2 += fts3PutColNumber(&p, iCol2);
108047      fts3ColumnlistCopy(&p, &p2);
108048    }
108049  }
108050
108051  *p++ = POS_END;
108052  *pp = p;
108053  *pp1 = p1 + 1;
108054  *pp2 = p2 + 1;
108055}
108056
108057/*
108058** nToken==1 searches for adjacent positions.
108059*/
108060static int fts3PoslistPhraseMerge(
108061  char **pp,                      /* Output buffer */
108062  int nToken,                     /* Maximum difference in token positions */
108063  int isSaveLeft,                 /* Save the left position */
108064  char **pp1,                     /* Left input list */
108065  char **pp2                      /* Right input list */
108066){
108067  char *p = (pp ? *pp : 0);
108068  char *p1 = *pp1;
108069  char *p2 = *pp2;
108070
108071  int iCol1 = 0;
108072  int iCol2 = 0;
108073  assert( *p1!=0 && *p2!=0 );
108074  if( *p1==POS_COLUMN ){
108075    p1++;
108076    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108077  }
108078  if( *p2==POS_COLUMN ){
108079    p2++;
108080    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108081  }
108082
108083  while( 1 ){
108084    if( iCol1==iCol2 ){
108085      char *pSave = p;
108086      sqlite3_int64 iPrev = 0;
108087      sqlite3_int64 iPos1 = 0;
108088      sqlite3_int64 iPos2 = 0;
108089
108090      if( pp && iCol1 ){
108091        *p++ = POS_COLUMN;
108092        p += sqlite3Fts3PutVarint(p, iCol1);
108093      }
108094
108095      assert( *p1!=POS_END && *p1!=POS_COLUMN );
108096      assert( *p2!=POS_END && *p2!=POS_COLUMN );
108097      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
108098      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
108099
108100      while( 1 ){
108101        if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
108102          sqlite3_int64 iSave;
108103          if( !pp ){
108104            fts3PoslistCopy(0, &p2);
108105            fts3PoslistCopy(0, &p1);
108106            *pp1 = p1;
108107            *pp2 = p2;
108108            return 1;
108109          }
108110          iSave = isSaveLeft ? iPos1 : iPos2;
108111          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
108112          pSave = 0;
108113        }
108114        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
108115          if( (*p2&0xFE)==0 ) break;
108116          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
108117        }else{
108118          if( (*p1&0xFE)==0 ) break;
108119          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
108120        }
108121      }
108122
108123      if( pSave ){
108124        assert( pp && p );
108125        p = pSave;
108126      }
108127
108128      fts3ColumnlistCopy(0, &p1);
108129      fts3ColumnlistCopy(0, &p2);
108130      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
108131      if( 0==*p1 || 0==*p2 ) break;
108132
108133      p1++;
108134      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108135      p2++;
108136      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108137    }
108138
108139    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
108140    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
108141    ** end of the position list, or the 0x01 that precedes the next
108142    ** column-number in the position list.
108143    */
108144    else if( iCol1<iCol2 ){
108145      fts3ColumnlistCopy(0, &p1);
108146      if( 0==*p1 ) break;
108147      p1++;
108148      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
108149    }else{
108150      fts3ColumnlistCopy(0, &p2);
108151      if( 0==*p2 ) break;
108152      p2++;
108153      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
108154    }
108155  }
108156
108157  fts3PoslistCopy(0, &p2);
108158  fts3PoslistCopy(0, &p1);
108159  *pp1 = p1;
108160  *pp2 = p2;
108161  if( !pp || *pp==p ){
108162    return 0;
108163  }
108164  *p++ = 0x00;
108165  *pp = p;
108166  return 1;
108167}
108168
108169/*
108170** Merge two position-lists as required by the NEAR operator.
108171*/
108172static int fts3PoslistNearMerge(
108173  char **pp,                      /* Output buffer */
108174  char *aTmp,                     /* Temporary buffer space */
108175  int nRight,                     /* Maximum difference in token positions */
108176  int nLeft,                      /* Maximum difference in token positions */
108177  char **pp1,                     /* IN/OUT: Left input list */
108178  char **pp2                      /* IN/OUT: Right input list */
108179){
108180  char *p1 = *pp1;
108181  char *p2 = *pp2;
108182
108183  if( !pp ){
108184    if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
108185    *pp1 = p1;
108186    *pp2 = p2;
108187    return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
108188  }else{
108189    char *pTmp1 = aTmp;
108190    char *pTmp2;
108191    char *aTmp2;
108192    int res = 1;
108193
108194    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
108195    aTmp2 = pTmp2 = pTmp1;
108196    *pp1 = p1;
108197    *pp2 = p2;
108198    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
108199    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
108200      fts3PoslistMerge(pp, &aTmp, &aTmp2);
108201    }else if( pTmp1!=aTmp ){
108202      fts3PoslistCopy(pp, &aTmp);
108203    }else if( pTmp2!=aTmp2 ){
108204      fts3PoslistCopy(pp, &aTmp2);
108205    }else{
108206      res = 0;
108207    }
108208
108209    return res;
108210  }
108211}
108212
108213/*
108214** Values that may be used as the first parameter to fts3DoclistMerge().
108215*/
108216#define MERGE_NOT        2        /* D + D -> D */
108217#define MERGE_AND        3        /* D + D -> D */
108218#define MERGE_OR         4        /* D + D -> D */
108219#define MERGE_POS_OR     5        /* P + P -> P */
108220#define MERGE_PHRASE     6        /* P + P -> D */
108221#define MERGE_POS_PHRASE 7        /* P + P -> P */
108222#define MERGE_NEAR       8        /* P + P -> D */
108223#define MERGE_POS_NEAR   9        /* P + P -> P */
108224
108225/*
108226** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
108227** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
108228** which is guaranteed to be large enough to hold the results. The number
108229** of bytes written to aBuffer is stored in *pnBuffer before returning.
108230**
108231** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
108232** occurs while allocating a temporary buffer as part of the merge operation,
108233** SQLITE_NOMEM is returned.
108234*/
108235static int fts3DoclistMerge(
108236  int mergetype,                  /* One of the MERGE_XXX constants */
108237  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
108238  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
108239  char *aBuffer,                  /* Pre-allocated output buffer */
108240  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
108241  char *a1,                       /* Buffer containing first doclist */
108242  int n1,                         /* Size of buffer a1 */
108243  char *a2,                       /* Buffer containing second doclist */
108244  int n2                          /* Size of buffer a2 */
108245){
108246  sqlite3_int64 i1 = 0;
108247  sqlite3_int64 i2 = 0;
108248  sqlite3_int64 iPrev = 0;
108249
108250  char *p = aBuffer;
108251  char *p1 = a1;
108252  char *p2 = a2;
108253  char *pEnd1 = &a1[n1];
108254  char *pEnd2 = &a2[n2];
108255
108256  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
108257       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
108258       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
108259       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
108260  );
108261
108262  if( !aBuffer ){
108263    *pnBuffer = 0;
108264    return SQLITE_NOMEM;
108265  }
108266
108267  /* Read the first docid from each doclist */
108268  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108269  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108270
108271  switch( mergetype ){
108272    case MERGE_OR:
108273    case MERGE_POS_OR:
108274      while( p1 || p2 ){
108275        if( p2 && p1 && i1==i2 ){
108276          fts3PutDeltaVarint(&p, &iPrev, i1);
108277          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
108278          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108279          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108280        }else if( !p2 || (p1 && i1<i2) ){
108281          fts3PutDeltaVarint(&p, &iPrev, i1);
108282          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
108283          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108284        }else{
108285          fts3PutDeltaVarint(&p, &iPrev, i2);
108286          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
108287          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108288        }
108289      }
108290      break;
108291
108292    case MERGE_AND:
108293      while( p1 && p2 ){
108294        if( i1==i2 ){
108295          fts3PutDeltaVarint(&p, &iPrev, i1);
108296          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108297          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108298        }else if( i1<i2 ){
108299          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108300        }else{
108301          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108302        }
108303      }
108304      break;
108305
108306    case MERGE_NOT:
108307      while( p1 ){
108308        if( p2 && i1==i2 ){
108309          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108310          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108311        }else if( !p2 || i1<i2 ){
108312          fts3PutDeltaVarint(&p, &iPrev, i1);
108313          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108314        }else{
108315          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108316        }
108317      }
108318      break;
108319
108320    case MERGE_POS_PHRASE:
108321    case MERGE_PHRASE: {
108322      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
108323      while( p1 && p2 ){
108324        if( i1==i2 ){
108325          char *pSave = p;
108326          sqlite3_int64 iPrevSave = iPrev;
108327          fts3PutDeltaVarint(&p, &iPrev, i1);
108328          if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
108329            p = pSave;
108330            iPrev = iPrevSave;
108331          }
108332          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108333          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108334        }else if( i1<i2 ){
108335          fts3PoslistCopy(0, &p1);
108336          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108337        }else{
108338          fts3PoslistCopy(0, &p2);
108339          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108340        }
108341      }
108342      break;
108343    }
108344
108345    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
108346      char *aTmp = 0;
108347      char **ppPos = 0;
108348
108349      if( mergetype==MERGE_POS_NEAR ){
108350        ppPos = &p;
108351        aTmp = sqlite3_malloc(2*(n1+n2+1));
108352        if( !aTmp ){
108353          return SQLITE_NOMEM;
108354        }
108355      }
108356
108357      while( p1 && p2 ){
108358        if( i1==i2 ){
108359          char *pSave = p;
108360          sqlite3_int64 iPrevSave = iPrev;
108361          fts3PutDeltaVarint(&p, &iPrev, i1);
108362
108363          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
108364            iPrev = iPrevSave;
108365            p = pSave;
108366          }
108367
108368          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108369          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108370        }else if( i1<i2 ){
108371          fts3PoslistCopy(0, &p1);
108372          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
108373        }else{
108374          fts3PoslistCopy(0, &p2);
108375          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
108376        }
108377      }
108378      sqlite3_free(aTmp);
108379      break;
108380    }
108381  }
108382
108383  *pnBuffer = (int)(p-aBuffer);
108384  return SQLITE_OK;
108385}
108386
108387/*
108388** A pointer to an instance of this structure is used as the context
108389** argument to sqlite3Fts3SegReaderIterate()
108390*/
108391typedef struct TermSelect TermSelect;
108392struct TermSelect {
108393  int isReqPos;
108394  char *aaOutput[16];             /* Malloc'd output buffer */
108395  int anOutput[16];               /* Size of output in bytes */
108396};
108397
108398/*
108399** Merge all doclists in the TermSelect.aaOutput[] array into a single
108400** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
108401** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
108402**
108403** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
108404** the responsibility of the caller to free any doclists left in the
108405** TermSelect.aaOutput[] array.
108406*/
108407static int fts3TermSelectMerge(TermSelect *pTS){
108408  int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
108409  char *aOut = 0;
108410  int nOut = 0;
108411  int i;
108412
108413  /* Loop through the doclists in the aaOutput[] array. Merge them all
108414  ** into a single doclist.
108415  */
108416  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
108417    if( pTS->aaOutput[i] ){
108418      if( !aOut ){
108419        aOut = pTS->aaOutput[i];
108420        nOut = pTS->anOutput[i];
108421        pTS->aaOutput[0] = 0;
108422      }else{
108423        int nNew = nOut + pTS->anOutput[i];
108424        char *aNew = sqlite3_malloc(nNew);
108425        if( !aNew ){
108426          sqlite3_free(aOut);
108427          return SQLITE_NOMEM;
108428        }
108429        fts3DoclistMerge(mergetype, 0, 0,
108430            aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut
108431        );
108432        sqlite3_free(pTS->aaOutput[i]);
108433        sqlite3_free(aOut);
108434        pTS->aaOutput[i] = 0;
108435        aOut = aNew;
108436        nOut = nNew;
108437      }
108438    }
108439  }
108440
108441  pTS->aaOutput[0] = aOut;
108442  pTS->anOutput[0] = nOut;
108443  return SQLITE_OK;
108444}
108445
108446/*
108447** This function is used as the sqlite3Fts3SegReaderIterate() callback when
108448** querying the full-text index for a doclist associated with a term or
108449** term-prefix.
108450*/
108451static int fts3TermSelectCb(
108452  Fts3Table *p,                   /* Virtual table object */
108453  void *pContext,                 /* Pointer to TermSelect structure */
108454  char *zTerm,
108455  int nTerm,
108456  char *aDoclist,
108457  int nDoclist
108458){
108459  TermSelect *pTS = (TermSelect *)pContext;
108460
108461  UNUSED_PARAMETER(p);
108462  UNUSED_PARAMETER(zTerm);
108463  UNUSED_PARAMETER(nTerm);
108464
108465  if( pTS->aaOutput[0]==0 ){
108466    /* If this is the first term selected, copy the doclist to the output
108467    ** buffer using memcpy(). TODO: Add a way to transfer control of the
108468    ** aDoclist buffer from the caller so as to avoid the memcpy().
108469    */
108470    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
108471    pTS->anOutput[0] = nDoclist;
108472    if( pTS->aaOutput[0] ){
108473      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
108474    }else{
108475      return SQLITE_NOMEM;
108476    }
108477  }else{
108478    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
108479    char *aMerge = aDoclist;
108480    int nMerge = nDoclist;
108481    int iOut;
108482
108483    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
108484      char *aNew;
108485      int nNew;
108486      if( pTS->aaOutput[iOut]==0 ){
108487        assert( iOut>0 );
108488        pTS->aaOutput[iOut] = aMerge;
108489        pTS->anOutput[iOut] = nMerge;
108490        break;
108491      }
108492
108493      nNew = nMerge + pTS->anOutput[iOut];
108494      aNew = sqlite3_malloc(nNew);
108495      if( !aNew ){
108496        if( aMerge!=aDoclist ){
108497          sqlite3_free(aMerge);
108498        }
108499        return SQLITE_NOMEM;
108500      }
108501      fts3DoclistMerge(mergetype, 0, 0,
108502          aNew, &nNew, pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge
108503      );
108504
108505      if( iOut>0 ) sqlite3_free(aMerge);
108506      sqlite3_free(pTS->aaOutput[iOut]);
108507      pTS->aaOutput[iOut] = 0;
108508
108509      aMerge = aNew;
108510      nMerge = nNew;
108511      if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
108512        pTS->aaOutput[iOut] = aMerge;
108513        pTS->anOutput[iOut] = nMerge;
108514      }
108515    }
108516  }
108517  return SQLITE_OK;
108518}
108519
108520/*
108521** This function retreives the doclist for the specified term (or term
108522** prefix) from the database.
108523**
108524** The returned doclist may be in one of two formats, depending on the
108525** value of parameter isReqPos. If isReqPos is zero, then the doclist is
108526** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
108527** is non-zero, then the returned list is in the same format as is stored
108528** in the database without the found length specifier at the start of on-disk
108529** doclists.
108530*/
108531static int fts3TermSelect(
108532  Fts3Table *p,                   /* Virtual table handle */
108533  int iColumn,                    /* Column to query (or -ve for all columns) */
108534  const char *zTerm,              /* Term to query for */
108535  int nTerm,                      /* Size of zTerm in bytes */
108536  int isPrefix,                   /* True for a prefix search */
108537  int isReqPos,                   /* True to include position lists in output */
108538  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
108539  char **ppOut                    /* OUT: Malloced result buffer */
108540){
108541  int i;
108542  TermSelect tsc;
108543  Fts3SegFilter filter;           /* Segment term filter configuration */
108544  Fts3SegReader **apSegment;      /* Array of segments to read data from */
108545  int nSegment = 0;               /* Size of apSegment array */
108546  int nAlloc = 16;                /* Allocated size of segment array */
108547  int rc;                         /* Return code */
108548  sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
108549  int iAge = 0;                   /* Used to assign ages to segments */
108550
108551  apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
108552  if( !apSegment ) return SQLITE_NOMEM;
108553  rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
108554  if( rc!=SQLITE_OK ) goto finished;
108555  if( apSegment[0] ){
108556    nSegment = 1;
108557  }
108558
108559  /* Loop through the entire %_segdir table. For each segment, create a
108560  ** Fts3SegReader to iterate through the subset of the segment leaves
108561  ** that may contain a term that matches zTerm/nTerm. For non-prefix
108562  ** searches, this is always a single leaf. For prefix searches, this
108563  ** may be a contiguous block of leaves.
108564  **
108565  ** The code in this loop does not actually load any leaves into memory
108566  ** (unless the root node happens to be a leaf). It simply examines the
108567  ** b-tree structure to determine which leaves need to be inspected.
108568  */
108569  rc = sqlite3Fts3AllSegdirs(p, &pStmt);
108570  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
108571    Fts3SegReader *pNew = 0;
108572    int nRoot = sqlite3_column_bytes(pStmt, 4);
108573    char const *zRoot = sqlite3_column_blob(pStmt, 4);
108574    if( sqlite3_column_int64(pStmt, 1)==0 ){
108575      /* The entire segment is stored on the root node (which must be a
108576      ** leaf). Do not bother inspecting any data in this case, just
108577      ** create a Fts3SegReader to scan the single leaf.
108578      */
108579      rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
108580    }else{
108581      int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
108582      sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
108583      rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
108584      if( rc==SQLITE_OK ){
108585        sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
108586        rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
108587      }
108588
108589      /* The following call to ReadBlock() serves to reset the SQL statement
108590      ** used to retrieve blocks of data from the %_segments table. If it is
108591      ** not reset here, then it may remain classified as an active statement
108592      ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
108593      ** failing.
108594      */
108595      rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
108596      if( rc==SQLITE_OK ){
108597        rc = rc2;
108598      }
108599    }
108600    iAge++;
108601
108602    /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
108603    assert( pNew!=0 || rc!=SQLITE_OK );
108604    if( pNew ){
108605      if( nSegment==nAlloc ){
108606        Fts3SegReader **pArray;
108607        nAlloc += 16;
108608        pArray = (Fts3SegReader **)sqlite3_realloc(
108609            apSegment, nAlloc*sizeof(Fts3SegReader *)
108610        );
108611        if( !pArray ){
108612          sqlite3Fts3SegReaderFree(p, pNew);
108613          rc = SQLITE_NOMEM;
108614          goto finished;
108615        }
108616        apSegment = pArray;
108617      }
108618      apSegment[nSegment++] = pNew;
108619    }
108620  }
108621  if( rc!=SQLITE_DONE ){
108622    assert( rc!=SQLITE_OK );
108623    goto finished;
108624  }
108625
108626  memset(&tsc, 0, sizeof(TermSelect));
108627  tsc.isReqPos = isReqPos;
108628
108629  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
108630        | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
108631        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
108632        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
108633  filter.iCol = iColumn;
108634  filter.zTerm = zTerm;
108635  filter.nTerm = nTerm;
108636
108637  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
108638      fts3TermSelectCb, (void *)&tsc
108639  );
108640  if( rc==SQLITE_OK ){
108641    rc = fts3TermSelectMerge(&tsc);
108642  }
108643
108644  if( rc==SQLITE_OK ){
108645    *ppOut = tsc.aaOutput[0];
108646    *pnOut = tsc.anOutput[0];
108647  }else{
108648    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
108649      sqlite3_free(tsc.aaOutput[i]);
108650    }
108651  }
108652
108653finished:
108654  sqlite3_reset(pStmt);
108655  for(i=0; i<nSegment; i++){
108656    sqlite3Fts3SegReaderFree(p, apSegment[i]);
108657  }
108658  sqlite3_free(apSegment);
108659  return rc;
108660}
108661
108662
108663/*
108664** Return a DocList corresponding to the phrase *pPhrase.
108665*/
108666static int fts3PhraseSelect(
108667  Fts3Table *p,                   /* Virtual table handle */
108668  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
108669  int isReqPos,                   /* True if output should contain positions */
108670  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
108671  int *pnOut                      /* OUT: Size of buffer at *paOut */
108672){
108673  char *pOut = 0;
108674  int nOut = 0;
108675  int rc = SQLITE_OK;
108676  int ii;
108677  int iCol = pPhrase->iColumn;
108678  int isTermPos = (pPhrase->nToken>1 || isReqPos);
108679
108680  for(ii=0; ii<pPhrase->nToken; ii++){
108681    struct PhraseToken *pTok = &pPhrase->aToken[ii];
108682    char *z = pTok->z;            /* Next token of the phrase */
108683    int n = pTok->n;              /* Size of z in bytes */
108684    int isPrefix = pTok->isPrefix;/* True if token is a prefix */
108685    char *pList;                  /* Pointer to token doclist */
108686    int nList;                    /* Size of buffer at pList */
108687
108688    rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
108689    if( rc!=SQLITE_OK ) break;
108690
108691    if( ii==0 ){
108692      pOut = pList;
108693      nOut = nList;
108694    }else{
108695      /* Merge the new term list and the current output. If this is the
108696      ** last term in the phrase, and positions are not required in the
108697      ** output of this function, the positions can be dropped as part
108698      ** of this merge. Either way, the result of this merge will be
108699      ** smaller than nList bytes. The code in fts3DoclistMerge() is written
108700      ** so that it is safe to use pList as the output as well as an input
108701      ** in this case.
108702      */
108703      int mergetype = MERGE_POS_PHRASE;
108704      if( ii==pPhrase->nToken-1 && !isReqPos ){
108705        mergetype = MERGE_PHRASE;
108706      }
108707      fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
108708      sqlite3_free(pOut);
108709      pOut = pList;
108710    }
108711    assert( nOut==0 || pOut!=0 );
108712  }
108713
108714  if( rc==SQLITE_OK ){
108715    *paOut = pOut;
108716    *pnOut = nOut;
108717  }else{
108718    sqlite3_free(pOut);
108719  }
108720  return rc;
108721}
108722
108723static int fts3NearMerge(
108724  int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
108725  int nNear,                      /* Parameter to NEAR operator */
108726  int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
108727  char *aLeft,                    /* Doclist for LHS (incl. positions) */
108728  int nLeft,                      /* Size of LHS doclist in bytes */
108729  int nTokenRight,                /* As nTokenLeft */
108730  char *aRight,                   /* As aLeft */
108731  int nRight,                     /* As nRight */
108732  char **paOut,                   /* OUT: Results of merge (malloced) */
108733  int *pnOut                      /* OUT: Sized of output buffer */
108734){
108735  char *aOut;
108736  int rc;
108737
108738  assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
108739
108740  aOut = sqlite3_malloc(nLeft+nRight+1);
108741  if( aOut==0 ){
108742    rc = SQLITE_NOMEM;
108743  }else{
108744    rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
108745      aOut, pnOut, aLeft, nLeft, aRight, nRight
108746    );
108747    if( rc!=SQLITE_OK ){
108748      sqlite3_free(aOut);
108749      aOut = 0;
108750    }
108751  }
108752
108753  *paOut = aOut;
108754  return rc;
108755}
108756
108757SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
108758  int rc;
108759  if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
108760    sqlite3_free(pLeft->aDoclist);
108761    sqlite3_free(pRight->aDoclist);
108762    pRight->aDoclist = 0;
108763    pLeft->aDoclist = 0;
108764    rc = SQLITE_OK;
108765  }else{
108766    char *aOut;
108767    int nOut;
108768
108769    rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
108770        pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
108771        pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
108772        &aOut, &nOut
108773    );
108774    if( rc!=SQLITE_OK ) return rc;
108775    sqlite3_free(pRight->aDoclist);
108776    pRight->aDoclist = aOut;
108777    pRight->nDoclist = nOut;
108778
108779    rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
108780        pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
108781        pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
108782        &aOut, &nOut
108783    );
108784    sqlite3_free(pLeft->aDoclist);
108785    pLeft->aDoclist = aOut;
108786    pLeft->nDoclist = nOut;
108787  }
108788  return rc;
108789}
108790
108791/*
108792** Evaluate the full-text expression pExpr against fts3 table pTab. Store
108793** the resulting doclist in *paOut and *pnOut.  This routine mallocs for
108794** the space needed to store the output.  The caller is responsible for
108795** freeing the space when it has finished.
108796*/
108797static int evalFts3Expr(
108798  Fts3Table *p,                   /* Virtual table handle */
108799  Fts3Expr *pExpr,                /* Parsed fts3 expression */
108800  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
108801  int *pnOut,                     /* OUT: Size of buffer at *paOut */
108802  int isReqPos                    /* Require positions in output buffer */
108803){
108804  int rc = SQLITE_OK;             /* Return code */
108805
108806  /* Zero the output parameters. */
108807  *paOut = 0;
108808  *pnOut = 0;
108809
108810  if( pExpr ){
108811    assert( pExpr->eType==FTSQUERY_PHRASE
108812         || pExpr->eType==FTSQUERY_NEAR
108813         || isReqPos==0
108814    );
108815    if( pExpr->eType==FTSQUERY_PHRASE ){
108816      rc = fts3PhraseSelect(p, pExpr->pPhrase,
108817          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
108818          paOut, pnOut
108819      );
108820    }else{
108821      char *aLeft;
108822      char *aRight;
108823      int nLeft;
108824      int nRight;
108825
108826      if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
108827       && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
108828      ){
108829        assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
108830            || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
108831        );
108832        switch( pExpr->eType ){
108833          case FTSQUERY_NEAR: {
108834            Fts3Expr *pLeft;
108835            Fts3Expr *pRight;
108836            int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
108837
108838            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
108839              mergetype = MERGE_POS_NEAR;
108840            }
108841            pLeft = pExpr->pLeft;
108842            while( pLeft->eType==FTSQUERY_NEAR ){
108843              pLeft=pLeft->pRight;
108844            }
108845            pRight = pExpr->pRight;
108846            assert( pRight->eType==FTSQUERY_PHRASE );
108847            assert( pLeft->eType==FTSQUERY_PHRASE );
108848
108849            rc = fts3NearMerge(mergetype, pExpr->nNear,
108850                pLeft->pPhrase->nToken, aLeft, nLeft,
108851                pRight->pPhrase->nToken, aRight, nRight,
108852                paOut, pnOut
108853            );
108854            sqlite3_free(aLeft);
108855            break;
108856          }
108857
108858          case FTSQUERY_OR: {
108859            /* Allocate a buffer for the output. The maximum size is the
108860            ** sum of the sizes of the two input buffers. The +1 term is
108861            ** so that a buffer of zero bytes is never allocated - this can
108862            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
108863            */
108864            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
108865            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
108866                aLeft, nLeft, aRight, nRight
108867            );
108868            *paOut = aBuffer;
108869            sqlite3_free(aLeft);
108870            break;
108871          }
108872
108873          default: {
108874            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
108875            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
108876                aLeft, nLeft, aRight, nRight
108877            );
108878            *paOut = aLeft;
108879            break;
108880          }
108881        }
108882      }
108883      sqlite3_free(aRight);
108884    }
108885  }
108886
108887  return rc;
108888}
108889
108890/*
108891** This is the xFilter interface for the virtual table.  See
108892** the virtual table xFilter method documentation for additional
108893** information.
108894**
108895** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
108896** the %_content table.
108897**
108898** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
108899** in the %_content table.
108900**
108901** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
108902** column on the left-hand side of the MATCH operator is column
108903** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
108904** side of the MATCH operator.
108905*/
108906/* TODO(shess) Upgrade the cursor initialization and destruction to
108907** account for fts3FilterMethod() being called multiple times on the
108908** same cursor. The current solution is very fragile. Apply fix to
108909** fts3 as appropriate.
108910*/
108911static int fts3FilterMethod(
108912  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
108913  int idxNum,                     /* Strategy index */
108914  const char *idxStr,             /* Unused */
108915  int nVal,                       /* Number of elements in apVal */
108916  sqlite3_value **apVal           /* Arguments for the indexing scheme */
108917){
108918  const char *azSql[] = {
108919    "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
108920    "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
108921  };
108922  int rc;                         /* Return code */
108923  char *zSql;                     /* SQL statement used to access %_content */
108924  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
108925  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
108926
108927  UNUSED_PARAMETER(idxStr);
108928  UNUSED_PARAMETER(nVal);
108929
108930  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
108931  assert( nVal==0 || nVal==1 );
108932  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
108933
108934  /* In case the cursor has been used before, clear it now. */
108935  sqlite3_finalize(pCsr->pStmt);
108936  sqlite3_free(pCsr->aDoclist);
108937  sqlite3Fts3ExprFree(pCsr->pExpr);
108938  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
108939
108940  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
108941  ** statement loops through all rows of the %_content table. For a
108942  ** full-text query or docid lookup, the statement retrieves a single
108943  ** row by docid.
108944  */
108945  zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
108946  if( !zSql ){
108947    rc = SQLITE_NOMEM;
108948  }else{
108949    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
108950    sqlite3_free(zSql);
108951  }
108952  if( rc!=SQLITE_OK ) return rc;
108953  pCsr->eSearch = (i16)idxNum;
108954
108955  if( idxNum==FTS3_DOCID_SEARCH ){
108956    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
108957  }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
108958    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
108959    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
108960
108961    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
108962      return SQLITE_NOMEM;
108963    }
108964
108965    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
108966        iCol, zQuery, -1, &pCsr->pExpr
108967    );
108968    if( rc!=SQLITE_OK ){
108969      if( rc==SQLITE_ERROR ){
108970        p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
108971                                          zQuery);
108972      }
108973      return rc;
108974    }
108975
108976    rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
108977    pCsr->pNextId = pCsr->aDoclist;
108978    pCsr->iPrevId = 0;
108979  }
108980
108981  if( rc!=SQLITE_OK ) return rc;
108982  return fts3NextMethod(pCursor);
108983}
108984
108985/*
108986** This is the xEof method of the virtual table. SQLite calls this
108987** routine to find out if it has reached the end of a result set.
108988*/
108989static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
108990  return ((Fts3Cursor *)pCursor)->isEof;
108991}
108992
108993/*
108994** This is the xRowid method. The SQLite core calls this routine to
108995** retrieve the rowid for the current row of the result set. fts3
108996** exposes %_content.docid as the rowid for the virtual table. The
108997** rowid should be written to *pRowid.
108998*/
108999static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
109000  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
109001  if( pCsr->aDoclist ){
109002    *pRowid = pCsr->iPrevId;
109003  }else{
109004    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
109005  }
109006  return SQLITE_OK;
109007}
109008
109009/*
109010** This is the xColumn method, called by SQLite to request a value from
109011** the row that the supplied cursor currently points to.
109012*/
109013static int fts3ColumnMethod(
109014  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
109015  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
109016  int iCol                        /* Index of column to read value from */
109017){
109018  int rc;                         /* Return Code */
109019  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
109020  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
109021
109022  /* The column value supplied by SQLite must be in range. */
109023  assert( iCol>=0 && iCol<=p->nColumn+1 );
109024
109025  if( iCol==p->nColumn+1 ){
109026    /* This call is a request for the "docid" column. Since "docid" is an
109027    ** alias for "rowid", use the xRowid() method to obtain the value.
109028    */
109029    sqlite3_int64 iRowid;
109030    rc = fts3RowidMethod(pCursor, &iRowid);
109031    sqlite3_result_int64(pContext, iRowid);
109032  }else if( iCol==p->nColumn ){
109033    /* The extra column whose name is the same as the table.
109034    ** Return a blob which is a pointer to the cursor.
109035    */
109036    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
109037    rc = SQLITE_OK;
109038  }else{
109039    rc = fts3CursorSeek(0, pCsr);
109040    if( rc==SQLITE_OK ){
109041      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
109042    }
109043  }
109044  return rc;
109045}
109046
109047/*
109048** This function is the implementation of the xUpdate callback used by
109049** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
109050** inserted, updated or deleted.
109051*/
109052static int fts3UpdateMethod(
109053  sqlite3_vtab *pVtab,            /* Virtual table handle */
109054  int nArg,                       /* Size of argument array */
109055  sqlite3_value **apVal,          /* Array of arguments */
109056  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
109057){
109058  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
109059}
109060
109061/*
109062** Implementation of xSync() method. Flush the contents of the pending-terms
109063** hash-table to the database.
109064*/
109065static int fts3SyncMethod(sqlite3_vtab *pVtab){
109066  return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
109067}
109068
109069/*
109070** Implementation of xBegin() method. This is a no-op.
109071*/
109072static int fts3BeginMethod(sqlite3_vtab *pVtab){
109073  UNUSED_PARAMETER(pVtab);
109074  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
109075  return SQLITE_OK;
109076}
109077
109078/*
109079** Implementation of xCommit() method. This is a no-op. The contents of
109080** the pending-terms hash-table have already been flushed into the database
109081** by fts3SyncMethod().
109082*/
109083static int fts3CommitMethod(sqlite3_vtab *pVtab){
109084  UNUSED_PARAMETER(pVtab);
109085  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
109086  return SQLITE_OK;
109087}
109088
109089/*
109090** Implementation of xRollback(). Discard the contents of the pending-terms
109091** hash-table. Any changes made to the database are reverted by SQLite.
109092*/
109093static int fts3RollbackMethod(sqlite3_vtab *pVtab){
109094  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
109095  return SQLITE_OK;
109096}
109097
109098/*
109099** Load the doclist associated with expression pExpr to pExpr->aDoclist.
109100** The loaded doclist contains positions as well as the document ids.
109101** This is used by the matchinfo(), snippet() and offsets() auxillary
109102** functions.
109103*/
109104SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
109105  return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
109106}
109107
109108/*
109109** After ExprLoadDoclist() (see above) has been called, this function is
109110** used to iterate/search through the position lists that make up the doclist
109111** stored in pExpr->aDoclist.
109112*/
109113SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
109114  Fts3Expr *pExpr,                /* Access this expressions doclist */
109115  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
109116  int iCol                        /* Column of requested pos-list */
109117){
109118  assert( pExpr->isLoaded );
109119  if( pExpr->aDoclist ){
109120    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
109121    char *pCsr = pExpr->pCurrent;
109122
109123    assert( pCsr );
109124    while( pCsr<pEnd ){
109125      if( pExpr->iCurrent<iDocid ){
109126        fts3PoslistCopy(0, &pCsr);
109127        if( pCsr<pEnd ){
109128          fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
109129        }
109130        pExpr->pCurrent = pCsr;
109131      }else{
109132        if( pExpr->iCurrent==iDocid ){
109133          int iThis = 0;
109134          if( iCol<0 ){
109135            /* If iCol is negative, return a pointer to the start of the
109136            ** position-list (instead of a pointer to the start of a list
109137            ** of offsets associated with a specific column).
109138            */
109139            return pCsr;
109140          }
109141          while( iThis<iCol ){
109142            fts3ColumnlistCopy(0, &pCsr);
109143            if( *pCsr==0x00 ) return 0;
109144            pCsr++;
109145            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
109146          }
109147          if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
109148        }
109149        return 0;
109150      }
109151    }
109152  }
109153
109154  return 0;
109155}
109156
109157/*
109158** Helper function used by the implementation of the overloaded snippet(),
109159** offsets() and optimize() SQL functions.
109160**
109161** If the value passed as the third argument is a blob of size
109162** sizeof(Fts3Cursor*), then the blob contents are copied to the
109163** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
109164** message is written to context pContext and SQLITE_ERROR returned. The
109165** string passed via zFunc is used as part of the error message.
109166*/
109167static int fts3FunctionArg(
109168  sqlite3_context *pContext,      /* SQL function call context */
109169  const char *zFunc,              /* Function name */
109170  sqlite3_value *pVal,            /* argv[0] passed to function */
109171  Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
109172){
109173  Fts3Cursor *pRet;
109174  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
109175   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
109176  ){
109177    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
109178    sqlite3_result_error(pContext, zErr, -1);
109179    sqlite3_free(zErr);
109180    return SQLITE_ERROR;
109181  }
109182  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
109183  *ppCsr = pRet;
109184  return SQLITE_OK;
109185}
109186
109187/*
109188** Implementation of the snippet() function for FTS3
109189*/
109190static void fts3SnippetFunc(
109191  sqlite3_context *pContext,      /* SQLite function call context */
109192  int nVal,                       /* Size of apVal[] array */
109193  sqlite3_value **apVal           /* Array of arguments */
109194){
109195  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
109196  const char *zStart = "<b>";
109197  const char *zEnd = "</b>";
109198  const char *zEllipsis = "<b>...</b>";
109199  int iCol = -1;
109200  int nToken = 15;                /* Default number of tokens in snippet */
109201
109202  /* There must be at least one argument passed to this function (otherwise
109203  ** the non-overloaded version would have been called instead of this one).
109204  */
109205  assert( nVal>=1 );
109206
109207  if( nVal>6 ){
109208    sqlite3_result_error(pContext,
109209        "wrong number of arguments to function snippet()", -1);
109210    return;
109211  }
109212  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
109213
109214  switch( nVal ){
109215    case 6: nToken = sqlite3_value_int(apVal[5]);
109216    case 5: iCol = sqlite3_value_int(apVal[4]);
109217    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
109218    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
109219    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
109220  }
109221  if( !zEllipsis || !zEnd || !zStart ){
109222    sqlite3_result_error_nomem(pContext);
109223  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
109224    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
109225  }
109226}
109227
109228/*
109229** Implementation of the offsets() function for FTS3
109230*/
109231static void fts3OffsetsFunc(
109232  sqlite3_context *pContext,      /* SQLite function call context */
109233  int nVal,                       /* Size of argument array */
109234  sqlite3_value **apVal           /* Array of arguments */
109235){
109236  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
109237
109238  UNUSED_PARAMETER(nVal);
109239
109240  assert( nVal==1 );
109241  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
109242  assert( pCsr );
109243  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
109244    sqlite3Fts3Offsets(pContext, pCsr);
109245  }
109246}
109247
109248/*
109249** Implementation of the special optimize() function for FTS3. This
109250** function merges all segments in the database to a single segment.
109251** Example usage is:
109252**
109253**   SELECT optimize(t) FROM t LIMIT 1;
109254**
109255** where 't' is the name of an FTS3 table.
109256*/
109257static void fts3OptimizeFunc(
109258  sqlite3_context *pContext,      /* SQLite function call context */
109259  int nVal,                       /* Size of argument array */
109260  sqlite3_value **apVal           /* Array of arguments */
109261){
109262  int rc;                         /* Return code */
109263  Fts3Table *p;                   /* Virtual table handle */
109264  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
109265
109266  UNUSED_PARAMETER(nVal);
109267
109268  assert( nVal==1 );
109269  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
109270  p = (Fts3Table *)pCursor->base.pVtab;
109271  assert( p );
109272
109273  rc = sqlite3Fts3Optimize(p);
109274
109275  switch( rc ){
109276    case SQLITE_OK:
109277      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
109278      break;
109279    case SQLITE_DONE:
109280      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
109281      break;
109282    default:
109283      sqlite3_result_error_code(pContext, rc);
109284      break;
109285  }
109286}
109287
109288/*
109289** Implementation of the matchinfo() function for FTS3
109290*/
109291static void fts3MatchinfoFunc(
109292  sqlite3_context *pContext,      /* SQLite function call context */
109293  int nVal,                       /* Size of argument array */
109294  sqlite3_value **apVal           /* Array of arguments */
109295){
109296  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
109297
109298  if( nVal!=1 ){
109299    sqlite3_result_error(pContext,
109300        "wrong number of arguments to function matchinfo()", -1);
109301    return;
109302  }
109303
109304  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
109305    sqlite3Fts3Matchinfo(pContext, pCsr);
109306  }
109307}
109308
109309/*
109310** This routine implements the xFindFunction method for the FTS3
109311** virtual table.
109312*/
109313static int fts3FindFunctionMethod(
109314  sqlite3_vtab *pVtab,            /* Virtual table handle */
109315  int nArg,                       /* Number of SQL function arguments */
109316  const char *zName,              /* Name of SQL function */
109317  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
109318  void **ppArg                    /* Unused */
109319){
109320  struct Overloaded {
109321    const char *zName;
109322    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
109323  } aOverload[] = {
109324    { "snippet", fts3SnippetFunc },
109325    { "offsets", fts3OffsetsFunc },
109326    { "optimize", fts3OptimizeFunc },
109327    { "matchinfo", fts3MatchinfoFunc },
109328  };
109329  int i;                          /* Iterator variable */
109330
109331  UNUSED_PARAMETER(pVtab);
109332  UNUSED_PARAMETER(nArg);
109333  UNUSED_PARAMETER(ppArg);
109334
109335  for(i=0; i<SizeofArray(aOverload); i++){
109336    if( strcmp(zName, aOverload[i].zName)==0 ){
109337      *pxFunc = aOverload[i].xFunc;
109338      return 1;
109339    }
109340  }
109341
109342  /* No function of the specified name was found. Return 0. */
109343  return 0;
109344}
109345
109346/*
109347** Implementation of FTS3 xRename method. Rename an fts3 table.
109348*/
109349static int fts3RenameMethod(
109350  sqlite3_vtab *pVtab,            /* Virtual table handle */
109351  const char *zName               /* New name of table */
109352){
109353  Fts3Table *p = (Fts3Table *)pVtab;
109354  sqlite3 *db;                    /* Database connection */
109355  int rc;                         /* Return Code */
109356
109357  db = p->db;
109358  rc = SQLITE_OK;
109359  fts3DbExec(&rc, db,
109360    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
109361    p->zDb, p->zName, zName
109362  );
109363  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
109364  if( p->bHasDocsize ){
109365    fts3DbExec(&rc, db,
109366      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
109367      p->zDb, p->zName, zName
109368    );
109369    fts3DbExec(&rc, db,
109370      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
109371      p->zDb, p->zName, zName
109372    );
109373  }
109374  fts3DbExec(&rc, db,
109375    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
109376    p->zDb, p->zName, zName
109377  );
109378  fts3DbExec(&rc, db,
109379    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
109380    p->zDb, p->zName, zName
109381  );
109382  return rc;
109383}
109384
109385static const sqlite3_module fts3Module = {
109386  /* iVersion      */ 0,
109387  /* xCreate       */ fts3CreateMethod,
109388  /* xConnect      */ fts3ConnectMethod,
109389  /* xBestIndex    */ fts3BestIndexMethod,
109390  /* xDisconnect   */ fts3DisconnectMethod,
109391  /* xDestroy      */ fts3DestroyMethod,
109392  /* xOpen         */ fts3OpenMethod,
109393  /* xClose        */ fulltextClose,
109394  /* xFilter       */ fts3FilterMethod,
109395  /* xNext         */ fts3NextMethod,
109396  /* xEof          */ fts3EofMethod,
109397  /* xColumn       */ fts3ColumnMethod,
109398  /* xRowid        */ fts3RowidMethod,
109399  /* xUpdate       */ fts3UpdateMethod,
109400  /* xBegin        */ fts3BeginMethod,
109401  /* xSync         */ fts3SyncMethod,
109402  /* xCommit       */ fts3CommitMethod,
109403  /* xRollback     */ fts3RollbackMethod,
109404  /* xFindFunction */ fts3FindFunctionMethod,
109405  /* xRename */       fts3RenameMethod,
109406};
109407
109408/*
109409** This function is registered as the module destructor (called when an
109410** FTS3 enabled database connection is closed). It frees the memory
109411** allocated for the tokenizer hash table.
109412*/
109413static void hashDestroy(void *p){
109414  Fts3Hash *pHash = (Fts3Hash *)p;
109415  sqlite3Fts3HashClear(pHash);
109416  sqlite3_free(pHash);
109417}
109418
109419/*
109420** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
109421** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
109422** two forward declarations are for functions declared in these files
109423** used to retrieve the respective implementations.
109424**
109425** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
109426** to by the argument to point to the "simple" tokenizer implementation.
109427** Function ...PorterTokenizerModule() sets *pModule to point to the
109428** porter tokenizer/stemmer implementation.
109429*/
109430SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
109431SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
109432SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
109433
109434/*
109435** Initialise the fts3 extension. If this extension is built as part
109436** of the sqlite library, then this function is called directly by
109437** SQLite. If fts3 is built as a dynamically loadable extension, this
109438** function is called by the sqlite3_extension_init() entry point.
109439*/
109440SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
109441  int rc = SQLITE_OK;
109442  Fts3Hash *pHash = 0;
109443  const sqlite3_tokenizer_module *pSimple = 0;
109444  const sqlite3_tokenizer_module *pPorter = 0;
109445
109446#ifdef SQLITE_ENABLE_ICU
109447  const sqlite3_tokenizer_module *pIcu = 0;
109448  sqlite3Fts3IcuTokenizerModule(&pIcu);
109449#endif
109450
109451  sqlite3Fts3SimpleTokenizerModule(&pSimple);
109452  sqlite3Fts3PorterTokenizerModule(&pPorter);
109453
109454  /* Allocate and initialise the hash-table used to store tokenizers. */
109455  pHash = sqlite3_malloc(sizeof(Fts3Hash));
109456  if( !pHash ){
109457    rc = SQLITE_NOMEM;
109458  }else{
109459    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
109460  }
109461
109462  /* Load the built-in tokenizers into the hash table */
109463  if( rc==SQLITE_OK ){
109464    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
109465     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
109466#ifdef SQLITE_ENABLE_ICU
109467     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
109468#endif
109469    ){
109470      rc = SQLITE_NOMEM;
109471    }
109472  }
109473
109474#ifdef SQLITE_TEST
109475  if( rc==SQLITE_OK ){
109476    rc = sqlite3Fts3ExprInitTestInterface(db);
109477  }
109478#endif
109479
109480  /* Create the virtual table wrapper around the hash-table and overload
109481  ** the two scalar functions. If this is successful, register the
109482  ** module with sqlite.
109483  */
109484  if( SQLITE_OK==rc
109485   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
109486   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
109487   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
109488   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
109489   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
109490  ){
109491    rc = sqlite3_create_module_v2(
109492        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
109493    );
109494    if( rc==SQLITE_OK ){
109495      rc = sqlite3_create_module_v2(
109496          db, "fts4", &fts3Module, (void *)pHash, 0
109497      );
109498    }
109499    return rc;
109500  }
109501
109502  /* An error has occurred. Delete the hash table and return the error code. */
109503  assert( rc!=SQLITE_OK );
109504  if( pHash ){
109505    sqlite3Fts3HashClear(pHash);
109506    sqlite3_free(pHash);
109507  }
109508  return rc;
109509}
109510
109511#if !SQLITE_CORE
109512SQLITE_API int sqlite3_extension_init(
109513  sqlite3 *db,
109514  char **pzErrMsg,
109515  const sqlite3_api_routines *pApi
109516){
109517  SQLITE_EXTENSION_INIT2(pApi)
109518  return sqlite3Fts3Init(db);
109519}
109520#endif
109521
109522#endif
109523
109524/************** End of fts3.c ************************************************/
109525/************** Begin file fts3_expr.c ***************************************/
109526/*
109527** 2008 Nov 28
109528**
109529** The author disclaims copyright to this source code.  In place of
109530** a legal notice, here is a blessing:
109531**
109532**    May you do good and not evil.
109533**    May you find forgiveness for yourself and forgive others.
109534**    May you share freely, never taking more than you give.
109535**
109536******************************************************************************
109537**
109538** This module contains code that implements a parser for fts3 query strings
109539** (the right-hand argument to the MATCH operator). Because the supported
109540** syntax is relatively simple, the whole tokenizer/parser system is
109541** hand-coded.
109542*/
109543#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
109544
109545/*
109546** By default, this module parses the legacy syntax that has been
109547** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
109548** is defined, then it uses the new syntax. The differences between
109549** the new and the old syntaxes are:
109550**
109551**  a) The new syntax supports parenthesis. The old does not.
109552**
109553**  b) The new syntax supports the AND and NOT operators. The old does not.
109554**
109555**  c) The old syntax supports the "-" token qualifier. This is not
109556**     supported by the new syntax (it is replaced by the NOT operator).
109557**
109558**  d) When using the old syntax, the OR operator has a greater precedence
109559**     than an implicit AND. When using the new, both implicity and explicit
109560**     AND operators have a higher precedence than OR.
109561**
109562** If compiled with SQLITE_TEST defined, then this module exports the
109563** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
109564** to zero causes the module to use the old syntax. If it is set to
109565** non-zero the new syntax is activated. This is so both syntaxes can
109566** be tested using a single build of testfixture.
109567**
109568** The following describes the syntax supported by the fts3 MATCH
109569** operator in a similar format to that used by the lemon parser
109570** generator. This module does not use actually lemon, it uses a
109571** custom parser.
109572**
109573**   query ::= andexpr (OR andexpr)*.
109574**
109575**   andexpr ::= notexpr (AND? notexpr)*.
109576**
109577**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
109578**   notexpr ::= LP query RP.
109579**
109580**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
109581**
109582**   distance_opt ::= .
109583**   distance_opt ::= / INTEGER.
109584**
109585**   phrase ::= TOKEN.
109586**   phrase ::= COLUMN:TOKEN.
109587**   phrase ::= "TOKEN TOKEN TOKEN...".
109588*/
109589
109590#ifdef SQLITE_TEST
109591SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
109592#else
109593# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
109594#  define sqlite3_fts3_enable_parentheses 1
109595# else
109596#  define sqlite3_fts3_enable_parentheses 0
109597# endif
109598#endif
109599
109600/*
109601** Default span for NEAR operators.
109602*/
109603#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
109604
109605
109606typedef struct ParseContext ParseContext;
109607struct ParseContext {
109608  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
109609  const char **azCol;                 /* Array of column names for fts3 table */
109610  int nCol;                           /* Number of entries in azCol[] */
109611  int iDefaultCol;                    /* Default column to query */
109612  sqlite3_context *pCtx;              /* Write error message here */
109613  int nNest;                          /* Number of nested brackets */
109614};
109615
109616/*
109617** This function is equivalent to the standard isspace() function.
109618**
109619** The standard isspace() can be awkward to use safely, because although it
109620** is defined to accept an argument of type int, its behaviour when passed
109621** an integer that falls outside of the range of the unsigned char type
109622** is undefined (and sometimes, "undefined" means segfault). This wrapper
109623** is defined to accept an argument of type char, and always returns 0 for
109624** any values that fall outside of the range of the unsigned char type (i.e.
109625** negative values).
109626*/
109627static int fts3isspace(char c){
109628  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
109629}
109630
109631/*
109632** Extract the next token from buffer z (length n) using the tokenizer
109633** and other information (column names etc.) in pParse. Create an Fts3Expr
109634** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
109635** single token and set *ppExpr to point to it. If the end of the buffer is
109636** reached before a token is found, set *ppExpr to zero. It is the
109637** responsibility of the caller to eventually deallocate the allocated
109638** Fts3Expr structure (if any) by passing it to sqlite3_free().
109639**
109640** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
109641** fails.
109642*/
109643static int getNextToken(
109644  ParseContext *pParse,                   /* fts3 query parse context */
109645  int iCol,                               /* Value for Fts3Phrase.iColumn */
109646  const char *z, int n,                   /* Input string */
109647  Fts3Expr **ppExpr,                      /* OUT: expression */
109648  int *pnConsumed                         /* OUT: Number of bytes consumed */
109649){
109650  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
109651  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
109652  int rc;
109653  sqlite3_tokenizer_cursor *pCursor;
109654  Fts3Expr *pRet = 0;
109655  int nConsumed = 0;
109656
109657  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
109658  if( rc==SQLITE_OK ){
109659    const char *zToken;
109660    int nToken, iStart, iEnd, iPosition;
109661    int nByte;                               /* total space to allocate */
109662
109663    pCursor->pTokenizer = pTokenizer;
109664    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
109665
109666    if( rc==SQLITE_OK ){
109667      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
109668      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
109669      if( !pRet ){
109670        rc = SQLITE_NOMEM;
109671      }else{
109672        memset(pRet, 0, nByte);
109673        pRet->eType = FTSQUERY_PHRASE;
109674        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
109675        pRet->pPhrase->nToken = 1;
109676        pRet->pPhrase->iColumn = iCol;
109677        pRet->pPhrase->aToken[0].n = nToken;
109678        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
109679        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
109680
109681        if( iEnd<n && z[iEnd]=='*' ){
109682          pRet->pPhrase->aToken[0].isPrefix = 1;
109683          iEnd++;
109684        }
109685        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
109686          pRet->pPhrase->isNot = 1;
109687        }
109688      }
109689      nConsumed = iEnd;
109690    }
109691
109692    pModule->xClose(pCursor);
109693  }
109694
109695  *pnConsumed = nConsumed;
109696  *ppExpr = pRet;
109697  return rc;
109698}
109699
109700
109701/*
109702** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
109703** then free the old allocation.
109704*/
109705static void *fts3ReallocOrFree(void *pOrig, int nNew){
109706  void *pRet = sqlite3_realloc(pOrig, nNew);
109707  if( !pRet ){
109708    sqlite3_free(pOrig);
109709  }
109710  return pRet;
109711}
109712
109713/*
109714** Buffer zInput, length nInput, contains the contents of a quoted string
109715** that appeared as part of an fts3 query expression. Neither quote character
109716** is included in the buffer. This function attempts to tokenize the entire
109717** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
109718** containing the results.
109719**
109720** If successful, SQLITE_OK is returned and *ppExpr set to point at the
109721** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
109722** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
109723** to 0.
109724*/
109725static int getNextString(
109726  ParseContext *pParse,                   /* fts3 query parse context */
109727  const char *zInput, int nInput,         /* Input string */
109728  Fts3Expr **ppExpr                       /* OUT: expression */
109729){
109730  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
109731  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
109732  int rc;
109733  Fts3Expr *p = 0;
109734  sqlite3_tokenizer_cursor *pCursor = 0;
109735  char *zTemp = 0;
109736  int nTemp = 0;
109737
109738  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
109739  if( rc==SQLITE_OK ){
109740    int ii;
109741    pCursor->pTokenizer = pTokenizer;
109742    for(ii=0; rc==SQLITE_OK; ii++){
109743      const char *zToken;
109744      int nToken, iBegin, iEnd, iPos;
109745      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
109746      if( rc==SQLITE_OK ){
109747        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
109748        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
109749        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
109750        if( !p || !zTemp ){
109751          goto no_mem;
109752        }
109753        if( ii==0 ){
109754          memset(p, 0, nByte);
109755          p->pPhrase = (Fts3Phrase *)&p[1];
109756        }
109757        p->pPhrase = (Fts3Phrase *)&p[1];
109758        p->pPhrase->nToken = ii+1;
109759        p->pPhrase->aToken[ii].n = nToken;
109760        memcpy(&zTemp[nTemp], zToken, nToken);
109761        nTemp += nToken;
109762        if( iEnd<nInput && zInput[iEnd]=='*' ){
109763          p->pPhrase->aToken[ii].isPrefix = 1;
109764        }else{
109765          p->pPhrase->aToken[ii].isPrefix = 0;
109766        }
109767      }
109768    }
109769
109770    pModule->xClose(pCursor);
109771    pCursor = 0;
109772  }
109773
109774  if( rc==SQLITE_DONE ){
109775    int jj;
109776    char *zNew = NULL;
109777    int nNew = 0;
109778    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
109779    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
109780    p = fts3ReallocOrFree(p, nByte + nTemp);
109781    if( !p ){
109782      goto no_mem;
109783    }
109784    if( zTemp ){
109785      zNew = &(((char *)p)[nByte]);
109786      memcpy(zNew, zTemp, nTemp);
109787    }else{
109788      memset(p, 0, nByte+nTemp);
109789    }
109790    p->pPhrase = (Fts3Phrase *)&p[1];
109791    for(jj=0; jj<p->pPhrase->nToken; jj++){
109792      p->pPhrase->aToken[jj].z = &zNew[nNew];
109793      nNew += p->pPhrase->aToken[jj].n;
109794    }
109795    sqlite3_free(zTemp);
109796    p->eType = FTSQUERY_PHRASE;
109797    p->pPhrase->iColumn = pParse->iDefaultCol;
109798    rc = SQLITE_OK;
109799  }
109800
109801  *ppExpr = p;
109802  return rc;
109803no_mem:
109804
109805  if( pCursor ){
109806    pModule->xClose(pCursor);
109807  }
109808  sqlite3_free(zTemp);
109809  sqlite3_free(p);
109810  *ppExpr = 0;
109811  return SQLITE_NOMEM;
109812}
109813
109814/*
109815** Function getNextNode(), which is called by fts3ExprParse(), may itself
109816** call fts3ExprParse(). So this forward declaration is required.
109817*/
109818static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
109819
109820/*
109821** The output variable *ppExpr is populated with an allocated Fts3Expr
109822** structure, or set to 0 if the end of the input buffer is reached.
109823**
109824** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
109825** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
109826** If SQLITE_ERROR is returned, pContext is populated with an error message.
109827*/
109828static int getNextNode(
109829  ParseContext *pParse,                   /* fts3 query parse context */
109830  const char *z, int n,                   /* Input string */
109831  Fts3Expr **ppExpr,                      /* OUT: expression */
109832  int *pnConsumed                         /* OUT: Number of bytes consumed */
109833){
109834  static const struct Fts3Keyword {
109835    char *z;                              /* Keyword text */
109836    unsigned char n;                      /* Length of the keyword */
109837    unsigned char parenOnly;              /* Only valid in paren mode */
109838    unsigned char eType;                  /* Keyword code */
109839  } aKeyword[] = {
109840    { "OR" ,  2, 0, FTSQUERY_OR   },
109841    { "AND",  3, 1, FTSQUERY_AND  },
109842    { "NOT",  3, 1, FTSQUERY_NOT  },
109843    { "NEAR", 4, 0, FTSQUERY_NEAR }
109844  };
109845  int ii;
109846  int iCol;
109847  int iColLen;
109848  int rc;
109849  Fts3Expr *pRet = 0;
109850
109851  const char *zInput = z;
109852  int nInput = n;
109853
109854  /* Skip over any whitespace before checking for a keyword, an open or
109855  ** close bracket, or a quoted string.
109856  */
109857  while( nInput>0 && fts3isspace(*zInput) ){
109858    nInput--;
109859    zInput++;
109860  }
109861  if( nInput==0 ){
109862    return SQLITE_DONE;
109863  }
109864
109865  /* See if we are dealing with a keyword. */
109866  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
109867    const struct Fts3Keyword *pKey = &aKeyword[ii];
109868
109869    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
109870      continue;
109871    }
109872
109873    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
109874      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
109875      int nKey = pKey->n;
109876      char cNext;
109877
109878      /* If this is a "NEAR" keyword, check for an explicit nearness. */
109879      if( pKey->eType==FTSQUERY_NEAR ){
109880        assert( nKey==4 );
109881        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
109882          nNear = 0;
109883          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
109884            nNear = nNear * 10 + (zInput[nKey] - '0');
109885          }
109886        }
109887      }
109888
109889      /* At this point this is probably a keyword. But for that to be true,
109890      ** the next byte must contain either whitespace, an open or close
109891      ** parenthesis, a quote character, or EOF.
109892      */
109893      cNext = zInput[nKey];
109894      if( fts3isspace(cNext)
109895       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
109896      ){
109897        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
109898        if( !pRet ){
109899          return SQLITE_NOMEM;
109900        }
109901        memset(pRet, 0, sizeof(Fts3Expr));
109902        pRet->eType = pKey->eType;
109903        pRet->nNear = nNear;
109904        *ppExpr = pRet;
109905        *pnConsumed = (int)((zInput - z) + nKey);
109906        return SQLITE_OK;
109907      }
109908
109909      /* Turns out that wasn't a keyword after all. This happens if the
109910      ** user has supplied a token such as "ORacle". Continue.
109911      */
109912    }
109913  }
109914
109915  /* Check for an open bracket. */
109916  if( sqlite3_fts3_enable_parentheses ){
109917    if( *zInput=='(' ){
109918      int nConsumed;
109919      int rc;
109920      pParse->nNest++;
109921      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
109922      if( rc==SQLITE_OK && !*ppExpr ){
109923        rc = SQLITE_DONE;
109924      }
109925      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
109926      return rc;
109927    }
109928
109929    /* Check for a close bracket. */
109930    if( *zInput==')' ){
109931      pParse->nNest--;
109932      *pnConsumed = (int)((zInput - z) + 1);
109933      return SQLITE_DONE;
109934    }
109935  }
109936
109937  /* See if we are dealing with a quoted phrase. If this is the case, then
109938  ** search for the closing quote and pass the whole string to getNextString()
109939  ** for processing. This is easy to do, as fts3 has no syntax for escaping
109940  ** a quote character embedded in a string.
109941  */
109942  if( *zInput=='"' ){
109943    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
109944    *pnConsumed = (int)((zInput - z) + ii + 1);
109945    if( ii==nInput ){
109946      return SQLITE_ERROR;
109947    }
109948    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
109949  }
109950
109951
109952  /* If control flows to this point, this must be a regular token, or
109953  ** the end of the input. Read a regular token using the sqlite3_tokenizer
109954  ** interface. Before doing so, figure out if there is an explicit
109955  ** column specifier for the token.
109956  **
109957  ** TODO: Strangely, it is not possible to associate a column specifier
109958  ** with a quoted phrase, only with a single token. Not sure if this was
109959  ** an implementation artifact or an intentional decision when fts3 was
109960  ** first implemented. Whichever it was, this module duplicates the
109961  ** limitation.
109962  */
109963  iCol = pParse->iDefaultCol;
109964  iColLen = 0;
109965  for(ii=0; ii<pParse->nCol; ii++){
109966    const char *zStr = pParse->azCol[ii];
109967    int nStr = (int)strlen(zStr);
109968    if( nInput>nStr && zInput[nStr]==':'
109969     && sqlite3_strnicmp(zStr, zInput, nStr)==0
109970    ){
109971      iCol = ii;
109972      iColLen = (int)((zInput - z) + nStr + 1);
109973      break;
109974    }
109975  }
109976  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
109977  *pnConsumed += iColLen;
109978  return rc;
109979}
109980
109981/*
109982** The argument is an Fts3Expr structure for a binary operator (any type
109983** except an FTSQUERY_PHRASE). Return an integer value representing the
109984** precedence of the operator. Lower values have a higher precedence (i.e.
109985** group more tightly). For example, in the C language, the == operator
109986** groups more tightly than ||, and would therefore have a higher precedence.
109987**
109988** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
109989** is defined), the order of the operators in precedence from highest to
109990** lowest is:
109991**
109992**   NEAR
109993**   NOT
109994**   AND (including implicit ANDs)
109995**   OR
109996**
109997** Note that when using the old query syntax, the OR operator has a higher
109998** precedence than the AND operator.
109999*/
110000static int opPrecedence(Fts3Expr *p){
110001  assert( p->eType!=FTSQUERY_PHRASE );
110002  if( sqlite3_fts3_enable_parentheses ){
110003    return p->eType;
110004  }else if( p->eType==FTSQUERY_NEAR ){
110005    return 1;
110006  }else if( p->eType==FTSQUERY_OR ){
110007    return 2;
110008  }
110009  assert( p->eType==FTSQUERY_AND );
110010  return 3;
110011}
110012
110013/*
110014** Argument ppHead contains a pointer to the current head of a query
110015** expression tree being parsed. pPrev is the expression node most recently
110016** inserted into the tree. This function adds pNew, which is always a binary
110017** operator node, into the expression tree based on the relative precedence
110018** of pNew and the existing nodes of the tree. This may result in the head
110019** of the tree changing, in which case *ppHead is set to the new root node.
110020*/
110021static void insertBinaryOperator(
110022  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
110023  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
110024  Fts3Expr *pNew           /* New binary node to insert into expression tree */
110025){
110026  Fts3Expr *pSplit = pPrev;
110027  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
110028    pSplit = pSplit->pParent;
110029  }
110030
110031  if( pSplit->pParent ){
110032    assert( pSplit->pParent->pRight==pSplit );
110033    pSplit->pParent->pRight = pNew;
110034    pNew->pParent = pSplit->pParent;
110035  }else{
110036    *ppHead = pNew;
110037  }
110038  pNew->pLeft = pSplit;
110039  pSplit->pParent = pNew;
110040}
110041
110042/*
110043** Parse the fts3 query expression found in buffer z, length n. This function
110044** returns either when the end of the buffer is reached or an unmatched
110045** closing bracket - ')' - is encountered.
110046**
110047** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
110048** parsed form of the expression and *pnConsumed is set to the number of
110049** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
110050** (out of memory error) or SQLITE_ERROR (parse error) is returned.
110051*/
110052static int fts3ExprParse(
110053  ParseContext *pParse,                   /* fts3 query parse context */
110054  const char *z, int n,                   /* Text of MATCH query */
110055  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
110056  int *pnConsumed                         /* OUT: Number of bytes consumed */
110057){
110058  Fts3Expr *pRet = 0;
110059  Fts3Expr *pPrev = 0;
110060  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
110061  int nIn = n;
110062  const char *zIn = z;
110063  int rc = SQLITE_OK;
110064  int isRequirePhrase = 1;
110065
110066  while( rc==SQLITE_OK ){
110067    Fts3Expr *p = 0;
110068    int nByte = 0;
110069    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
110070    if( rc==SQLITE_OK ){
110071      int isPhrase;
110072
110073      if( !sqlite3_fts3_enable_parentheses
110074       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
110075      ){
110076        /* Create an implicit NOT operator. */
110077        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
110078        if( !pNot ){
110079          sqlite3Fts3ExprFree(p);
110080          rc = SQLITE_NOMEM;
110081          goto exprparse_out;
110082        }
110083        memset(pNot, 0, sizeof(Fts3Expr));
110084        pNot->eType = FTSQUERY_NOT;
110085        pNot->pRight = p;
110086        if( pNotBranch ){
110087          pNot->pLeft = pNotBranch;
110088        }
110089        pNotBranch = pNot;
110090        p = pPrev;
110091      }else{
110092        int eType = p->eType;
110093        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
110094        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
110095
110096        /* The isRequirePhrase variable is set to true if a phrase or
110097        ** an expression contained in parenthesis is required. If a
110098        ** binary operator (AND, OR, NOT or NEAR) is encounted when
110099        ** isRequirePhrase is set, this is a syntax error.
110100        */
110101        if( !isPhrase && isRequirePhrase ){
110102          sqlite3Fts3ExprFree(p);
110103          rc = SQLITE_ERROR;
110104          goto exprparse_out;
110105        }
110106
110107        if( isPhrase && !isRequirePhrase ){
110108          /* Insert an implicit AND operator. */
110109          Fts3Expr *pAnd;
110110          assert( pRet && pPrev );
110111          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
110112          if( !pAnd ){
110113            sqlite3Fts3ExprFree(p);
110114            rc = SQLITE_NOMEM;
110115            goto exprparse_out;
110116          }
110117          memset(pAnd, 0, sizeof(Fts3Expr));
110118          pAnd->eType = FTSQUERY_AND;
110119          insertBinaryOperator(&pRet, pPrev, pAnd);
110120          pPrev = pAnd;
110121        }
110122
110123        /* This test catches attempts to make either operand of a NEAR
110124        ** operator something other than a phrase. For example, either of
110125        ** the following:
110126        **
110127        **    (bracketed expression) NEAR phrase
110128        **    phrase NEAR (bracketed expression)
110129        **
110130        ** Return an error in either case.
110131        */
110132        if( pPrev && (
110133            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
110134         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
110135        )){
110136          sqlite3Fts3ExprFree(p);
110137          rc = SQLITE_ERROR;
110138          goto exprparse_out;
110139        }
110140
110141        if( isPhrase ){
110142          if( pRet ){
110143            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
110144            pPrev->pRight = p;
110145            p->pParent = pPrev;
110146          }else{
110147            pRet = p;
110148          }
110149        }else{
110150          insertBinaryOperator(&pRet, pPrev, p);
110151        }
110152        isRequirePhrase = !isPhrase;
110153      }
110154      assert( nByte>0 );
110155    }
110156    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
110157    nIn -= nByte;
110158    zIn += nByte;
110159    pPrev = p;
110160  }
110161
110162  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
110163    rc = SQLITE_ERROR;
110164  }
110165
110166  if( rc==SQLITE_DONE ){
110167    rc = SQLITE_OK;
110168    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
110169      if( !pRet ){
110170        rc = SQLITE_ERROR;
110171      }else{
110172        Fts3Expr *pIter = pNotBranch;
110173        while( pIter->pLeft ){
110174          pIter = pIter->pLeft;
110175        }
110176        pIter->pLeft = pRet;
110177        pRet = pNotBranch;
110178      }
110179    }
110180  }
110181  *pnConsumed = n - nIn;
110182
110183exprparse_out:
110184  if( rc!=SQLITE_OK ){
110185    sqlite3Fts3ExprFree(pRet);
110186    sqlite3Fts3ExprFree(pNotBranch);
110187    pRet = 0;
110188  }
110189  *ppExpr = pRet;
110190  return rc;
110191}
110192
110193/*
110194** Parameters z and n contain a pointer to and length of a buffer containing
110195** an fts3 query expression, respectively. This function attempts to parse the
110196** query expression and create a tree of Fts3Expr structures representing the
110197** parsed expression. If successful, *ppExpr is set to point to the head
110198** of the parsed expression tree and SQLITE_OK is returned. If an error
110199** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
110200** error) is returned and *ppExpr is set to 0.
110201**
110202** If parameter n is a negative number, then z is assumed to point to a
110203** nul-terminated string and the length is determined using strlen().
110204**
110205** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
110206** use to normalize query tokens while parsing the expression. The azCol[]
110207** array, which is assumed to contain nCol entries, should contain the names
110208** of each column in the target fts3 table, in order from left to right.
110209** Column names must be nul-terminated strings.
110210**
110211** The iDefaultCol parameter should be passed the index of the table column
110212** that appears on the left-hand-side of the MATCH operator (the default
110213** column to match against for tokens for which a column name is not explicitly
110214** specified as part of the query string), or -1 if tokens may by default
110215** match any table column.
110216*/
110217SQLITE_PRIVATE int sqlite3Fts3ExprParse(
110218  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
110219  char **azCol,                       /* Array of column names for fts3 table */
110220  int nCol,                           /* Number of entries in azCol[] */
110221  int iDefaultCol,                    /* Default column to query */
110222  const char *z, int n,               /* Text of MATCH query */
110223  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
110224){
110225  int nParsed;
110226  int rc;
110227  ParseContext sParse;
110228  sParse.pTokenizer = pTokenizer;
110229  sParse.azCol = (const char **)azCol;
110230  sParse.nCol = nCol;
110231  sParse.iDefaultCol = iDefaultCol;
110232  sParse.nNest = 0;
110233  if( z==0 ){
110234    *ppExpr = 0;
110235    return SQLITE_OK;
110236  }
110237  if( n<0 ){
110238    n = (int)strlen(z);
110239  }
110240  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
110241
110242  /* Check for mismatched parenthesis */
110243  if( rc==SQLITE_OK && sParse.nNest ){
110244    rc = SQLITE_ERROR;
110245    sqlite3Fts3ExprFree(*ppExpr);
110246    *ppExpr = 0;
110247  }
110248
110249  return rc;
110250}
110251
110252/*
110253** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
110254*/
110255SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
110256  if( p ){
110257    sqlite3Fts3ExprFree(p->pLeft);
110258    sqlite3Fts3ExprFree(p->pRight);
110259    sqlite3_free(p->aDoclist);
110260    sqlite3_free(p);
110261  }
110262}
110263
110264/****************************************************************************
110265*****************************************************************************
110266** Everything after this point is just test code.
110267*/
110268
110269#ifdef SQLITE_TEST
110270
110271
110272/*
110273** Function to query the hash-table of tokenizers (see README.tokenizers).
110274*/
110275static int queryTestTokenizer(
110276  sqlite3 *db,
110277  const char *zName,
110278  const sqlite3_tokenizer_module **pp
110279){
110280  int rc;
110281  sqlite3_stmt *pStmt;
110282  const char zSql[] = "SELECT fts3_tokenizer(?)";
110283
110284  *pp = 0;
110285  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110286  if( rc!=SQLITE_OK ){
110287    return rc;
110288  }
110289
110290  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
110291  if( SQLITE_ROW==sqlite3_step(pStmt) ){
110292    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
110293      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
110294    }
110295  }
110296
110297  return sqlite3_finalize(pStmt);
110298}
110299
110300/*
110301** This function is part of the test interface for the query parser. It
110302** writes a text representation of the query expression pExpr into the
110303** buffer pointed to by argument zBuf. It is assumed that zBuf is large
110304** enough to store the required text representation.
110305*/
110306static void exprToString(Fts3Expr *pExpr, char *zBuf){
110307  switch( pExpr->eType ){
110308    case FTSQUERY_PHRASE: {
110309      Fts3Phrase *pPhrase = pExpr->pPhrase;
110310      int i;
110311      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
110312      for(i=0; i<pPhrase->nToken; i++){
110313        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
110314        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
110315      }
110316      return;
110317    }
110318
110319    case FTSQUERY_NEAR:
110320      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
110321      break;
110322    case FTSQUERY_NOT:
110323      zBuf += sprintf(zBuf, "NOT ");
110324      break;
110325    case FTSQUERY_AND:
110326      zBuf += sprintf(zBuf, "AND ");
110327      break;
110328    case FTSQUERY_OR:
110329      zBuf += sprintf(zBuf, "OR ");
110330      break;
110331  }
110332
110333  zBuf += sprintf(zBuf, "{");
110334  exprToString(pExpr->pLeft, zBuf);
110335  zBuf += strlen(zBuf);
110336  zBuf += sprintf(zBuf, "} ");
110337
110338  zBuf += sprintf(zBuf, "{");
110339  exprToString(pExpr->pRight, zBuf);
110340  zBuf += strlen(zBuf);
110341  zBuf += sprintf(zBuf, "}");
110342}
110343
110344/*
110345** This is the implementation of a scalar SQL function used to test the
110346** expression parser. It should be called as follows:
110347**
110348**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
110349**
110350** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
110351** to parse the query expression (see README.tokenizers). The second argument
110352** is the query expression to parse. Each subsequent argument is the name
110353** of a column of the fts3 table that the query expression may refer to.
110354** For example:
110355**
110356**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
110357*/
110358static void fts3ExprTest(
110359  sqlite3_context *context,
110360  int argc,
110361  sqlite3_value **argv
110362){
110363  sqlite3_tokenizer_module const *pModule = 0;
110364  sqlite3_tokenizer *pTokenizer = 0;
110365  int rc;
110366  char **azCol = 0;
110367  const char *zExpr;
110368  int nExpr;
110369  int nCol;
110370  int ii;
110371  Fts3Expr *pExpr;
110372  sqlite3 *db = sqlite3_context_db_handle(context);
110373
110374  if( argc<3 ){
110375    sqlite3_result_error(context,
110376        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
110377    );
110378    return;
110379  }
110380
110381  rc = queryTestTokenizer(db,
110382                          (const char *)sqlite3_value_text(argv[0]), &pModule);
110383  if( rc==SQLITE_NOMEM ){
110384    sqlite3_result_error_nomem(context);
110385    goto exprtest_out;
110386  }else if( !pModule ){
110387    sqlite3_result_error(context, "No such tokenizer module", -1);
110388    goto exprtest_out;
110389  }
110390
110391  rc = pModule->xCreate(0, 0, &pTokenizer);
110392  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
110393  if( rc==SQLITE_NOMEM ){
110394    sqlite3_result_error_nomem(context);
110395    goto exprtest_out;
110396  }
110397  pTokenizer->pModule = pModule;
110398
110399  zExpr = (const char *)sqlite3_value_text(argv[1]);
110400  nExpr = sqlite3_value_bytes(argv[1]);
110401  nCol = argc-2;
110402  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
110403  if( !azCol ){
110404    sqlite3_result_error_nomem(context);
110405    goto exprtest_out;
110406  }
110407  for(ii=0; ii<nCol; ii++){
110408    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
110409  }
110410
110411  rc = sqlite3Fts3ExprParse(
110412      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
110413  );
110414  if( rc==SQLITE_NOMEM ){
110415    sqlite3_result_error_nomem(context);
110416    goto exprtest_out;
110417  }else if( rc==SQLITE_OK ){
110418    char zBuf[4096];
110419    exprToString(pExpr, zBuf);
110420    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
110421    sqlite3Fts3ExprFree(pExpr);
110422  }else{
110423    sqlite3_result_error(context, "Error parsing expression", -1);
110424  }
110425
110426exprtest_out:
110427  if( pModule && pTokenizer ){
110428    rc = pModule->xDestroy(pTokenizer);
110429  }
110430  sqlite3_free(azCol);
110431}
110432
110433/*
110434** Register the query expression parser test function fts3_exprtest()
110435** with database connection db.
110436*/
110437SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
110438  return sqlite3_create_function(
110439      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
110440  );
110441}
110442
110443#endif
110444#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110445
110446/************** End of fts3_expr.c *******************************************/
110447/************** Begin file fts3_hash.c ***************************************/
110448/*
110449** 2001 September 22
110450**
110451** The author disclaims copyright to this source code.  In place of
110452** a legal notice, here is a blessing:
110453**
110454**    May you do good and not evil.
110455**    May you find forgiveness for yourself and forgive others.
110456**    May you share freely, never taking more than you give.
110457**
110458*************************************************************************
110459** This is the implementation of generic hash-tables used in SQLite.
110460** We've modified it slightly to serve as a standalone hash table
110461** implementation for the full-text indexing module.
110462*/
110463
110464/*
110465** The code in this file is only compiled if:
110466**
110467**     * The FTS3 module is being built as an extension
110468**       (in which case SQLITE_CORE is not defined), or
110469**
110470**     * The FTS3 module is being built into the core of
110471**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110472*/
110473#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110474
110475
110476
110477/*
110478** Malloc and Free functions
110479*/
110480static void *fts3HashMalloc(int n){
110481  void *p = sqlite3_malloc(n);
110482  if( p ){
110483    memset(p, 0, n);
110484  }
110485  return p;
110486}
110487static void fts3HashFree(void *p){
110488  sqlite3_free(p);
110489}
110490
110491/* Turn bulk memory into a hash table object by initializing the
110492** fields of the Hash structure.
110493**
110494** "pNew" is a pointer to the hash table that is to be initialized.
110495** keyClass is one of the constants
110496** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
110497** determines what kind of key the hash table will use.  "copyKey" is
110498** true if the hash table should make its own private copy of keys and
110499** false if it should just use the supplied pointer.
110500*/
110501SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
110502  assert( pNew!=0 );
110503  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
110504  pNew->keyClass = keyClass;
110505  pNew->copyKey = copyKey;
110506  pNew->first = 0;
110507  pNew->count = 0;
110508  pNew->htsize = 0;
110509  pNew->ht = 0;
110510}
110511
110512/* Remove all entries from a hash table.  Reclaim all memory.
110513** Call this routine to delete a hash table or to reset a hash table
110514** to the empty state.
110515*/
110516SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
110517  Fts3HashElem *elem;         /* For looping over all elements of the table */
110518
110519  assert( pH!=0 );
110520  elem = pH->first;
110521  pH->first = 0;
110522  fts3HashFree(pH->ht);
110523  pH->ht = 0;
110524  pH->htsize = 0;
110525  while( elem ){
110526    Fts3HashElem *next_elem = elem->next;
110527    if( pH->copyKey && elem->pKey ){
110528      fts3HashFree(elem->pKey);
110529    }
110530    fts3HashFree(elem);
110531    elem = next_elem;
110532  }
110533  pH->count = 0;
110534}
110535
110536/*
110537** Hash and comparison functions when the mode is FTS3_HASH_STRING
110538*/
110539static int fts3StrHash(const void *pKey, int nKey){
110540  const char *z = (const char *)pKey;
110541  int h = 0;
110542  if( nKey<=0 ) nKey = (int) strlen(z);
110543  while( nKey > 0  ){
110544    h = (h<<3) ^ h ^ *z++;
110545    nKey--;
110546  }
110547  return h & 0x7fffffff;
110548}
110549static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
110550  if( n1!=n2 ) return 1;
110551  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
110552}
110553
110554/*
110555** Hash and comparison functions when the mode is FTS3_HASH_BINARY
110556*/
110557static int fts3BinHash(const void *pKey, int nKey){
110558  int h = 0;
110559  const char *z = (const char *)pKey;
110560  while( nKey-- > 0 ){
110561    h = (h<<3) ^ h ^ *(z++);
110562  }
110563  return h & 0x7fffffff;
110564}
110565static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
110566  if( n1!=n2 ) return 1;
110567  return memcmp(pKey1,pKey2,n1);
110568}
110569
110570/*
110571** Return a pointer to the appropriate hash function given the key class.
110572**
110573** The C syntax in this function definition may be unfamilar to some
110574** programmers, so we provide the following additional explanation:
110575**
110576** The name of the function is "ftsHashFunction".  The function takes a
110577** single parameter "keyClass".  The return value of ftsHashFunction()
110578** is a pointer to another function.  Specifically, the return value
110579** of ftsHashFunction() is a pointer to a function that takes two parameters
110580** with types "const void*" and "int" and returns an "int".
110581*/
110582static int (*ftsHashFunction(int keyClass))(const void*,int){
110583  if( keyClass==FTS3_HASH_STRING ){
110584    return &fts3StrHash;
110585  }else{
110586    assert( keyClass==FTS3_HASH_BINARY );
110587    return &fts3BinHash;
110588  }
110589}
110590
110591/*
110592** Return a pointer to the appropriate hash function given the key class.
110593**
110594** For help in interpreted the obscure C code in the function definition,
110595** see the header comment on the previous function.
110596*/
110597static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
110598  if( keyClass==FTS3_HASH_STRING ){
110599    return &fts3StrCompare;
110600  }else{
110601    assert( keyClass==FTS3_HASH_BINARY );
110602    return &fts3BinCompare;
110603  }
110604}
110605
110606/* Link an element into the hash table
110607*/
110608static void fts3HashInsertElement(
110609  Fts3Hash *pH,            /* The complete hash table */
110610  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
110611  Fts3HashElem *pNew       /* The element to be inserted */
110612){
110613  Fts3HashElem *pHead;     /* First element already in pEntry */
110614  pHead = pEntry->chain;
110615  if( pHead ){
110616    pNew->next = pHead;
110617    pNew->prev = pHead->prev;
110618    if( pHead->prev ){ pHead->prev->next = pNew; }
110619    else             { pH->first = pNew; }
110620    pHead->prev = pNew;
110621  }else{
110622    pNew->next = pH->first;
110623    if( pH->first ){ pH->first->prev = pNew; }
110624    pNew->prev = 0;
110625    pH->first = pNew;
110626  }
110627  pEntry->count++;
110628  pEntry->chain = pNew;
110629}
110630
110631
110632/* Resize the hash table so that it cantains "new_size" buckets.
110633** "new_size" must be a power of 2.  The hash table might fail
110634** to resize if sqliteMalloc() fails.
110635**
110636** Return non-zero if a memory allocation error occurs.
110637*/
110638static int fts3Rehash(Fts3Hash *pH, int new_size){
110639  struct _fts3ht *new_ht;          /* The new hash table */
110640  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
110641  int (*xHash)(const void*,int);   /* The hash function */
110642
110643  assert( (new_size & (new_size-1))==0 );
110644  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
110645  if( new_ht==0 ) return 1;
110646  fts3HashFree(pH->ht);
110647  pH->ht = new_ht;
110648  pH->htsize = new_size;
110649  xHash = ftsHashFunction(pH->keyClass);
110650  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
110651    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
110652    next_elem = elem->next;
110653    fts3HashInsertElement(pH, &new_ht[h], elem);
110654  }
110655  return 0;
110656}
110657
110658/* This function (for internal use only) locates an element in an
110659** hash table that matches the given key.  The hash for this key has
110660** already been computed and is passed as the 4th parameter.
110661*/
110662static Fts3HashElem *fts3FindElementByHash(
110663  const Fts3Hash *pH, /* The pH to be searched */
110664  const void *pKey,   /* The key we are searching for */
110665  int nKey,
110666  int h               /* The hash for this key. */
110667){
110668  Fts3HashElem *elem;            /* Used to loop thru the element list */
110669  int count;                     /* Number of elements left to test */
110670  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
110671
110672  if( pH->ht ){
110673    struct _fts3ht *pEntry = &pH->ht[h];
110674    elem = pEntry->chain;
110675    count = pEntry->count;
110676    xCompare = ftsCompareFunction(pH->keyClass);
110677    while( count-- && elem ){
110678      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
110679        return elem;
110680      }
110681      elem = elem->next;
110682    }
110683  }
110684  return 0;
110685}
110686
110687/* Remove a single entry from the hash table given a pointer to that
110688** element and a hash on the element's key.
110689*/
110690static void fts3RemoveElementByHash(
110691  Fts3Hash *pH,         /* The pH containing "elem" */
110692  Fts3HashElem* elem,   /* The element to be removed from the pH */
110693  int h                 /* Hash value for the element */
110694){
110695  struct _fts3ht *pEntry;
110696  if( elem->prev ){
110697    elem->prev->next = elem->next;
110698  }else{
110699    pH->first = elem->next;
110700  }
110701  if( elem->next ){
110702    elem->next->prev = elem->prev;
110703  }
110704  pEntry = &pH->ht[h];
110705  if( pEntry->chain==elem ){
110706    pEntry->chain = elem->next;
110707  }
110708  pEntry->count--;
110709  if( pEntry->count<=0 ){
110710    pEntry->chain = 0;
110711  }
110712  if( pH->copyKey && elem->pKey ){
110713    fts3HashFree(elem->pKey);
110714  }
110715  fts3HashFree( elem );
110716  pH->count--;
110717  if( pH->count<=0 ){
110718    assert( pH->first==0 );
110719    assert( pH->count==0 );
110720    fts3HashClear(pH);
110721  }
110722}
110723
110724SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
110725  const Fts3Hash *pH,
110726  const void *pKey,
110727  int nKey
110728){
110729  int h;                          /* A hash on key */
110730  int (*xHash)(const void*,int);  /* The hash function */
110731
110732  if( pH==0 || pH->ht==0 ) return 0;
110733  xHash = ftsHashFunction(pH->keyClass);
110734  assert( xHash!=0 );
110735  h = (*xHash)(pKey,nKey);
110736  assert( (pH->htsize & (pH->htsize-1))==0 );
110737  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
110738}
110739
110740/*
110741** Attempt to locate an element of the hash table pH with a key
110742** that matches pKey,nKey.  Return the data for this element if it is
110743** found, or NULL if there is no match.
110744*/
110745SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
110746  Fts3HashElem *pElem;            /* The element that matches key (if any) */
110747
110748  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
110749  return pElem ? pElem->data : 0;
110750}
110751
110752/* Insert an element into the hash table pH.  The key is pKey,nKey
110753** and the data is "data".
110754**
110755** If no element exists with a matching key, then a new
110756** element is created.  A copy of the key is made if the copyKey
110757** flag is set.  NULL is returned.
110758**
110759** If another element already exists with the same key, then the
110760** new data replaces the old data and the old data is returned.
110761** The key is not copied in this instance.  If a malloc fails, then
110762** the new data is returned and the hash table is unchanged.
110763**
110764** If the "data" parameter to this function is NULL, then the
110765** element corresponding to "key" is removed from the hash table.
110766*/
110767SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
110768  Fts3Hash *pH,        /* The hash table to insert into */
110769  const void *pKey,    /* The key */
110770  int nKey,            /* Number of bytes in the key */
110771  void *data           /* The data */
110772){
110773  int hraw;                 /* Raw hash value of the key */
110774  int h;                    /* the hash of the key modulo hash table size */
110775  Fts3HashElem *elem;       /* Used to loop thru the element list */
110776  Fts3HashElem *new_elem;   /* New element added to the pH */
110777  int (*xHash)(const void*,int);  /* The hash function */
110778
110779  assert( pH!=0 );
110780  xHash = ftsHashFunction(pH->keyClass);
110781  assert( xHash!=0 );
110782  hraw = (*xHash)(pKey, nKey);
110783  assert( (pH->htsize & (pH->htsize-1))==0 );
110784  h = hraw & (pH->htsize-1);
110785  elem = fts3FindElementByHash(pH,pKey,nKey,h);
110786  if( elem ){
110787    void *old_data = elem->data;
110788    if( data==0 ){
110789      fts3RemoveElementByHash(pH,elem,h);
110790    }else{
110791      elem->data = data;
110792    }
110793    return old_data;
110794  }
110795  if( data==0 ) return 0;
110796  if( (pH->htsize==0 && fts3Rehash(pH,8))
110797   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
110798  ){
110799    pH->count = 0;
110800    return data;
110801  }
110802  assert( pH->htsize>0 );
110803  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
110804  if( new_elem==0 ) return data;
110805  if( pH->copyKey && pKey!=0 ){
110806    new_elem->pKey = fts3HashMalloc( nKey );
110807    if( new_elem->pKey==0 ){
110808      fts3HashFree(new_elem);
110809      return data;
110810    }
110811    memcpy((void*)new_elem->pKey, pKey, nKey);
110812  }else{
110813    new_elem->pKey = (void*)pKey;
110814  }
110815  new_elem->nKey = nKey;
110816  pH->count++;
110817  assert( pH->htsize>0 );
110818  assert( (pH->htsize & (pH->htsize-1))==0 );
110819  h = hraw & (pH->htsize-1);
110820  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
110821  new_elem->data = data;
110822  return 0;
110823}
110824
110825#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110826
110827/************** End of fts3_hash.c *******************************************/
110828/************** Begin file fts3_porter.c *************************************/
110829/*
110830** 2006 September 30
110831**
110832** The author disclaims copyright to this source code.  In place of
110833** a legal notice, here is a blessing:
110834**
110835**    May you do good and not evil.
110836**    May you find forgiveness for yourself and forgive others.
110837**    May you share freely, never taking more than you give.
110838**
110839*************************************************************************
110840** Implementation of the full-text-search tokenizer that implements
110841** a Porter stemmer.
110842*/
110843
110844/*
110845** The code in this file is only compiled if:
110846**
110847**     * The FTS3 module is being built as an extension
110848**       (in which case SQLITE_CORE is not defined), or
110849**
110850**     * The FTS3 module is being built into the core of
110851**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
110852*/
110853#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110854
110855
110856
110857
110858/*
110859** Class derived from sqlite3_tokenizer
110860*/
110861typedef struct porter_tokenizer {
110862  sqlite3_tokenizer base;      /* Base class */
110863} porter_tokenizer;
110864
110865/*
110866** Class derived from sqlit3_tokenizer_cursor
110867*/
110868typedef struct porter_tokenizer_cursor {
110869  sqlite3_tokenizer_cursor base;
110870  const char *zInput;          /* input we are tokenizing */
110871  int nInput;                  /* size of the input */
110872  int iOffset;                 /* current position in zInput */
110873  int iToken;                  /* index of next token to be returned */
110874  char *zToken;                /* storage for current token */
110875  int nAllocated;              /* space allocated to zToken buffer */
110876} porter_tokenizer_cursor;
110877
110878
110879/*
110880** Create a new tokenizer instance.
110881*/
110882static int porterCreate(
110883  int argc, const char * const *argv,
110884  sqlite3_tokenizer **ppTokenizer
110885){
110886  porter_tokenizer *t;
110887
110888  UNUSED_PARAMETER(argc);
110889  UNUSED_PARAMETER(argv);
110890
110891  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
110892  if( t==NULL ) return SQLITE_NOMEM;
110893  memset(t, 0, sizeof(*t));
110894  *ppTokenizer = &t->base;
110895  return SQLITE_OK;
110896}
110897
110898/*
110899** Destroy a tokenizer
110900*/
110901static int porterDestroy(sqlite3_tokenizer *pTokenizer){
110902  sqlite3_free(pTokenizer);
110903  return SQLITE_OK;
110904}
110905
110906/*
110907** Prepare to begin tokenizing a particular string.  The input
110908** string to be tokenized is zInput[0..nInput-1].  A cursor
110909** used to incrementally tokenize this string is returned in
110910** *ppCursor.
110911*/
110912static int porterOpen(
110913  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110914  const char *zInput, int nInput,        /* String to be tokenized */
110915  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110916){
110917  porter_tokenizer_cursor *c;
110918
110919  UNUSED_PARAMETER(pTokenizer);
110920
110921  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
110922  if( c==NULL ) return SQLITE_NOMEM;
110923
110924  c->zInput = zInput;
110925  if( zInput==0 ){
110926    c->nInput = 0;
110927  }else if( nInput<0 ){
110928    c->nInput = (int)strlen(zInput);
110929  }else{
110930    c->nInput = nInput;
110931  }
110932  c->iOffset = 0;                 /* start tokenizing at the beginning */
110933  c->iToken = 0;
110934  c->zToken = NULL;               /* no space allocated, yet. */
110935  c->nAllocated = 0;
110936
110937  *ppCursor = &c->base;
110938  return SQLITE_OK;
110939}
110940
110941/*
110942** Close a tokenization cursor previously opened by a call to
110943** porterOpen() above.
110944*/
110945static int porterClose(sqlite3_tokenizer_cursor *pCursor){
110946  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
110947  sqlite3_free(c->zToken);
110948  sqlite3_free(c);
110949  return SQLITE_OK;
110950}
110951/*
110952** Vowel or consonant
110953*/
110954static const char cType[] = {
110955   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
110956   1, 1, 1, 2, 1
110957};
110958
110959/*
110960** isConsonant() and isVowel() determine if their first character in
110961** the string they point to is a consonant or a vowel, according
110962** to Porter ruls.
110963**
110964** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
110965** 'Y' is a consonant unless it follows another consonant,
110966** in which case it is a vowel.
110967**
110968** In these routine, the letters are in reverse order.  So the 'y' rule
110969** is that 'y' is a consonant unless it is followed by another
110970** consonent.
110971*/
110972static int isVowel(const char*);
110973static int isConsonant(const char *z){
110974  int j;
110975  char x = *z;
110976  if( x==0 ) return 0;
110977  assert( x>='a' && x<='z' );
110978  j = cType[x-'a'];
110979  if( j<2 ) return j;
110980  return z[1]==0 || isVowel(z + 1);
110981}
110982static int isVowel(const char *z){
110983  int j;
110984  char x = *z;
110985  if( x==0 ) return 0;
110986  assert( x>='a' && x<='z' );
110987  j = cType[x-'a'];
110988  if( j<2 ) return 1-j;
110989  return isConsonant(z + 1);
110990}
110991
110992/*
110993** Let any sequence of one or more vowels be represented by V and let
110994** C be sequence of one or more consonants.  Then every word can be
110995** represented as:
110996**
110997**           [C] (VC){m} [V]
110998**
110999** In prose:  A word is an optional consonant followed by zero or
111000** vowel-consonant pairs followed by an optional vowel.  "m" is the
111001** number of vowel consonant pairs.  This routine computes the value
111002** of m for the first i bytes of a word.
111003**
111004** Return true if the m-value for z is 1 or more.  In other words,
111005** return true if z contains at least one vowel that is followed
111006** by a consonant.
111007**
111008** In this routine z[] is in reverse order.  So we are really looking
111009** for an instance of of a consonant followed by a vowel.
111010*/
111011static int m_gt_0(const char *z){
111012  while( isVowel(z) ){ z++; }
111013  if( *z==0 ) return 0;
111014  while( isConsonant(z) ){ z++; }
111015  return *z!=0;
111016}
111017
111018/* Like mgt0 above except we are looking for a value of m which is
111019** exactly 1
111020*/
111021static int m_eq_1(const char *z){
111022  while( isVowel(z) ){ z++; }
111023  if( *z==0 ) return 0;
111024  while( isConsonant(z) ){ z++; }
111025  if( *z==0 ) return 0;
111026  while( isVowel(z) ){ z++; }
111027  if( *z==0 ) return 1;
111028  while( isConsonant(z) ){ z++; }
111029  return *z==0;
111030}
111031
111032/* Like mgt0 above except we are looking for a value of m>1 instead
111033** or m>0
111034*/
111035static int m_gt_1(const char *z){
111036  while( isVowel(z) ){ z++; }
111037  if( *z==0 ) return 0;
111038  while( isConsonant(z) ){ z++; }
111039  if( *z==0 ) return 0;
111040  while( isVowel(z) ){ z++; }
111041  if( *z==0 ) return 0;
111042  while( isConsonant(z) ){ z++; }
111043  return *z!=0;
111044}
111045
111046/*
111047** Return TRUE if there is a vowel anywhere within z[0..n-1]
111048*/
111049static int hasVowel(const char *z){
111050  while( isConsonant(z) ){ z++; }
111051  return *z!=0;
111052}
111053
111054/*
111055** Return TRUE if the word ends in a double consonant.
111056**
111057** The text is reversed here. So we are really looking at
111058** the first two characters of z[].
111059*/
111060static int doubleConsonant(const char *z){
111061  return isConsonant(z) && z[0]==z[1];
111062}
111063
111064/*
111065** Return TRUE if the word ends with three letters which
111066** are consonant-vowel-consonent and where the final consonant
111067** is not 'w', 'x', or 'y'.
111068**
111069** The word is reversed here.  So we are really checking the
111070** first three letters and the first one cannot be in [wxy].
111071*/
111072static int star_oh(const char *z){
111073  return
111074    isConsonant(z) &&
111075    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
111076    isVowel(z+1) &&
111077    isConsonant(z+2);
111078}
111079
111080/*
111081** If the word ends with zFrom and xCond() is true for the stem
111082** of the word that preceeds the zFrom ending, then change the
111083** ending to zTo.
111084**
111085** The input word *pz and zFrom are both in reverse order.  zTo
111086** is in normal order.
111087**
111088** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
111089** match.  Not that TRUE is returned even if xCond() fails and
111090** no substitution occurs.
111091*/
111092static int stem(
111093  char **pz,             /* The word being stemmed (Reversed) */
111094  const char *zFrom,     /* If the ending matches this... (Reversed) */
111095  const char *zTo,       /* ... change the ending to this (not reversed) */
111096  int (*xCond)(const char*)   /* Condition that must be true */
111097){
111098  char *z = *pz;
111099  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
111100  if( *zFrom!=0 ) return 0;
111101  if( xCond && !xCond(z) ) return 1;
111102  while( *zTo ){
111103    *(--z) = *(zTo++);
111104  }
111105  *pz = z;
111106  return 1;
111107}
111108
111109/*
111110** This is the fallback stemmer used when the porter stemmer is
111111** inappropriate.  The input word is copied into the output with
111112** US-ASCII case folding.  If the input word is too long (more
111113** than 20 bytes if it contains no digits or more than 6 bytes if
111114** it contains digits) then word is truncated to 20 or 6 bytes
111115** by taking 10 or 3 bytes from the beginning and end.
111116*/
111117static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
111118  int i, mx, j;
111119  int hasDigit = 0;
111120  for(i=0; i<nIn; i++){
111121    char c = zIn[i];
111122    if( c>='A' && c<='Z' ){
111123      zOut[i] = c - 'A' + 'a';
111124    }else{
111125      if( c>='0' && c<='9' ) hasDigit = 1;
111126      zOut[i] = c;
111127    }
111128  }
111129  mx = hasDigit ? 3 : 10;
111130  if( nIn>mx*2 ){
111131    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
111132      zOut[j] = zOut[i];
111133    }
111134    i = j;
111135  }
111136  zOut[i] = 0;
111137  *pnOut = i;
111138}
111139
111140
111141/*
111142** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
111143** zOut is at least big enough to hold nIn bytes.  Write the actual
111144** size of the output word (exclusive of the '\0' terminator) into *pnOut.
111145**
111146** Any upper-case characters in the US-ASCII character set ([A-Z])
111147** are converted to lower case.  Upper-case UTF characters are
111148** unchanged.
111149**
111150** Words that are longer than about 20 bytes are stemmed by retaining
111151** a few bytes from the beginning and the end of the word.  If the
111152** word contains digits, 3 bytes are taken from the beginning and
111153** 3 bytes from the end.  For long words without digits, 10 bytes
111154** are taken from each end.  US-ASCII case folding still applies.
111155**
111156** If the input word contains not digits but does characters not
111157** in [a-zA-Z] then no stemming is attempted and this routine just
111158** copies the input into the input into the output with US-ASCII
111159** case folding.
111160**
111161** Stemming never increases the length of the word.  So there is
111162** no chance of overflowing the zOut buffer.
111163*/
111164static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
111165  int i, j;
111166  char zReverse[28];
111167  char *z, *z2;
111168  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
111169    /* The word is too big or too small for the porter stemmer.
111170    ** Fallback to the copy stemmer */
111171    copy_stemmer(zIn, nIn, zOut, pnOut);
111172    return;
111173  }
111174  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
111175    char c = zIn[i];
111176    if( c>='A' && c<='Z' ){
111177      zReverse[j] = c + 'a' - 'A';
111178    }else if( c>='a' && c<='z' ){
111179      zReverse[j] = c;
111180    }else{
111181      /* The use of a character not in [a-zA-Z] means that we fallback
111182      ** to the copy stemmer */
111183      copy_stemmer(zIn, nIn, zOut, pnOut);
111184      return;
111185    }
111186  }
111187  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
111188  z = &zReverse[j+1];
111189
111190
111191  /* Step 1a */
111192  if( z[0]=='s' ){
111193    if(
111194     !stem(&z, "sess", "ss", 0) &&
111195     !stem(&z, "sei", "i", 0)  &&
111196     !stem(&z, "ss", "ss", 0)
111197    ){
111198      z++;
111199    }
111200  }
111201
111202  /* Step 1b */
111203  z2 = z;
111204  if( stem(&z, "dee", "ee", m_gt_0) ){
111205    /* Do nothing.  The work was all in the test */
111206  }else if(
111207     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
111208      && z!=z2
111209  ){
111210     if( stem(&z, "ta", "ate", 0) ||
111211         stem(&z, "lb", "ble", 0) ||
111212         stem(&z, "zi", "ize", 0) ){
111213       /* Do nothing.  The work was all in the test */
111214     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
111215       z++;
111216     }else if( m_eq_1(z) && star_oh(z) ){
111217       *(--z) = 'e';
111218     }
111219  }
111220
111221  /* Step 1c */
111222  if( z[0]=='y' && hasVowel(z+1) ){
111223    z[0] = 'i';
111224  }
111225
111226  /* Step 2 */
111227  switch( z[1] ){
111228   case 'a':
111229     stem(&z, "lanoita", "ate", m_gt_0) ||
111230     stem(&z, "lanoit", "tion", m_gt_0);
111231     break;
111232   case 'c':
111233     stem(&z, "icne", "ence", m_gt_0) ||
111234     stem(&z, "icna", "ance", m_gt_0);
111235     break;
111236   case 'e':
111237     stem(&z, "rezi", "ize", m_gt_0);
111238     break;
111239   case 'g':
111240     stem(&z, "igol", "log", m_gt_0);
111241     break;
111242   case 'l':
111243     stem(&z, "ilb", "ble", m_gt_0) ||
111244     stem(&z, "illa", "al", m_gt_0) ||
111245     stem(&z, "iltne", "ent", m_gt_0) ||
111246     stem(&z, "ile", "e", m_gt_0) ||
111247     stem(&z, "ilsuo", "ous", m_gt_0);
111248     break;
111249   case 'o':
111250     stem(&z, "noitazi", "ize", m_gt_0) ||
111251     stem(&z, "noita", "ate", m_gt_0) ||
111252     stem(&z, "rota", "ate", m_gt_0);
111253     break;
111254   case 's':
111255     stem(&z, "msila", "al", m_gt_0) ||
111256     stem(&z, "ssenevi", "ive", m_gt_0) ||
111257     stem(&z, "ssenluf", "ful", m_gt_0) ||
111258     stem(&z, "ssensuo", "ous", m_gt_0);
111259     break;
111260   case 't':
111261     stem(&z, "itila", "al", m_gt_0) ||
111262     stem(&z, "itivi", "ive", m_gt_0) ||
111263     stem(&z, "itilib", "ble", m_gt_0);
111264     break;
111265  }
111266
111267  /* Step 3 */
111268  switch( z[0] ){
111269   case 'e':
111270     stem(&z, "etaci", "ic", m_gt_0) ||
111271     stem(&z, "evita", "", m_gt_0)   ||
111272     stem(&z, "ezila", "al", m_gt_0);
111273     break;
111274   case 'i':
111275     stem(&z, "itici", "ic", m_gt_0);
111276     break;
111277   case 'l':
111278     stem(&z, "laci", "ic", m_gt_0) ||
111279     stem(&z, "luf", "", m_gt_0);
111280     break;
111281   case 's':
111282     stem(&z, "ssen", "", m_gt_0);
111283     break;
111284  }
111285
111286  /* Step 4 */
111287  switch( z[1] ){
111288   case 'a':
111289     if( z[0]=='l' && m_gt_1(z+2) ){
111290       z += 2;
111291     }
111292     break;
111293   case 'c':
111294     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
111295       z += 4;
111296     }
111297     break;
111298   case 'e':
111299     if( z[0]=='r' && m_gt_1(z+2) ){
111300       z += 2;
111301     }
111302     break;
111303   case 'i':
111304     if( z[0]=='c' && m_gt_1(z+2) ){
111305       z += 2;
111306     }
111307     break;
111308   case 'l':
111309     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
111310       z += 4;
111311     }
111312     break;
111313   case 'n':
111314     if( z[0]=='t' ){
111315       if( z[2]=='a' ){
111316         if( m_gt_1(z+3) ){
111317           z += 3;
111318         }
111319       }else if( z[2]=='e' ){
111320         stem(&z, "tneme", "", m_gt_1) ||
111321         stem(&z, "tnem", "", m_gt_1) ||
111322         stem(&z, "tne", "", m_gt_1);
111323       }
111324     }
111325     break;
111326   case 'o':
111327     if( z[0]=='u' ){
111328       if( m_gt_1(z+2) ){
111329         z += 2;
111330       }
111331     }else if( z[3]=='s' || z[3]=='t' ){
111332       stem(&z, "noi", "", m_gt_1);
111333     }
111334     break;
111335   case 's':
111336     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
111337       z += 3;
111338     }
111339     break;
111340   case 't':
111341     stem(&z, "eta", "", m_gt_1) ||
111342     stem(&z, "iti", "", m_gt_1);
111343     break;
111344   case 'u':
111345     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
111346       z += 3;
111347     }
111348     break;
111349   case 'v':
111350   case 'z':
111351     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
111352       z += 3;
111353     }
111354     break;
111355  }
111356
111357  /* Step 5a */
111358  if( z[0]=='e' ){
111359    if( m_gt_1(z+1) ){
111360      z++;
111361    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
111362      z++;
111363    }
111364  }
111365
111366  /* Step 5b */
111367  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
111368    z++;
111369  }
111370
111371  /* z[] is now the stemmed word in reverse order.  Flip it back
111372  ** around into forward order and return.
111373  */
111374  *pnOut = i = (int)strlen(z);
111375  zOut[i] = 0;
111376  while( *z ){
111377    zOut[--i] = *(z++);
111378  }
111379}
111380
111381/*
111382** Characters that can be part of a token.  We assume any character
111383** whose value is greater than 0x80 (any UTF character) can be
111384** part of a token.  In other words, delimiters all must have
111385** values of 0x7f or lower.
111386*/
111387static const char porterIdChar[] = {
111388/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
111389    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
111390    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
111391    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
111392    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
111393    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
111394};
111395#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
111396
111397/*
111398** Extract the next token from a tokenization cursor.  The cursor must
111399** have been opened by a prior call to porterOpen().
111400*/
111401static int porterNext(
111402  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
111403  const char **pzToken,               /* OUT: *pzToken is the token text */
111404  int *pnBytes,                       /* OUT: Number of bytes in token */
111405  int *piStartOffset,                 /* OUT: Starting offset of token */
111406  int *piEndOffset,                   /* OUT: Ending offset of token */
111407  int *piPosition                     /* OUT: Position integer of token */
111408){
111409  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
111410  const char *z = c->zInput;
111411
111412  while( c->iOffset<c->nInput ){
111413    int iStartOffset, ch;
111414
111415    /* Scan past delimiter characters */
111416    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
111417      c->iOffset++;
111418    }
111419
111420    /* Count non-delimiter characters. */
111421    iStartOffset = c->iOffset;
111422    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
111423      c->iOffset++;
111424    }
111425
111426    if( c->iOffset>iStartOffset ){
111427      int n = c->iOffset-iStartOffset;
111428      if( n>c->nAllocated ){
111429        char *pNew;
111430        c->nAllocated = n+20;
111431        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
111432        if( !pNew ) return SQLITE_NOMEM;
111433        c->zToken = pNew;
111434      }
111435      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
111436      *pzToken = c->zToken;
111437      *piStartOffset = iStartOffset;
111438      *piEndOffset = c->iOffset;
111439      *piPosition = c->iToken++;
111440      return SQLITE_OK;
111441    }
111442  }
111443  return SQLITE_DONE;
111444}
111445
111446/*
111447** The set of routines that implement the porter-stemmer tokenizer
111448*/
111449static const sqlite3_tokenizer_module porterTokenizerModule = {
111450  0,
111451  porterCreate,
111452  porterDestroy,
111453  porterOpen,
111454  porterClose,
111455  porterNext,
111456};
111457
111458/*
111459** Allocate a new porter tokenizer.  Return a pointer to the new
111460** tokenizer in *ppModule
111461*/
111462SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
111463  sqlite3_tokenizer_module const**ppModule
111464){
111465  *ppModule = &porterTokenizerModule;
111466}
111467
111468#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111469
111470/************** End of fts3_porter.c *****************************************/
111471/************** Begin file fts3_tokenizer.c **********************************/
111472/*
111473** 2007 June 22
111474**
111475** The author disclaims copyright to this source code.  In place of
111476** a legal notice, here is a blessing:
111477**
111478**    May you do good and not evil.
111479**    May you find forgiveness for yourself and forgive others.
111480**    May you share freely, never taking more than you give.
111481**
111482******************************************************************************
111483**
111484** This is part of an SQLite module implementing full-text search.
111485** This particular file implements the generic tokenizer interface.
111486*/
111487
111488/*
111489** The code in this file is only compiled if:
111490**
111491**     * The FTS3 module is being built as an extension
111492**       (in which case SQLITE_CORE is not defined), or
111493**
111494**     * The FTS3 module is being built into the core of
111495**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111496*/
111497#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111498
111499#ifndef SQLITE_CORE
111500  SQLITE_EXTENSION_INIT1
111501#endif
111502
111503
111504/*
111505** Implementation of the SQL scalar function for accessing the underlying
111506** hash table. This function may be called as follows:
111507**
111508**   SELECT <function-name>(<key-name>);
111509**   SELECT <function-name>(<key-name>, <pointer>);
111510**
111511** where <function-name> is the name passed as the second argument
111512** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
111513**
111514** If the <pointer> argument is specified, it must be a blob value
111515** containing a pointer to be stored as the hash data corresponding
111516** to the string <key-name>. If <pointer> is not specified, then
111517** the string <key-name> must already exist in the has table. Otherwise,
111518** an error is returned.
111519**
111520** Whether or not the <pointer> argument is specified, the value returned
111521** is a blob containing the pointer stored as the hash data corresponding
111522** to string <key-name> (after the hash-table is updated, if applicable).
111523*/
111524static void scalarFunc(
111525  sqlite3_context *context,
111526  int argc,
111527  sqlite3_value **argv
111528){
111529  Fts3Hash *pHash;
111530  void *pPtr = 0;
111531  const unsigned char *zName;
111532  int nName;
111533
111534  assert( argc==1 || argc==2 );
111535
111536  pHash = (Fts3Hash *)sqlite3_user_data(context);
111537
111538  zName = sqlite3_value_text(argv[0]);
111539  nName = sqlite3_value_bytes(argv[0])+1;
111540
111541  if( argc==2 ){
111542    void *pOld;
111543    int n = sqlite3_value_bytes(argv[1]);
111544    if( n!=sizeof(pPtr) ){
111545      sqlite3_result_error(context, "argument type mismatch", -1);
111546      return;
111547    }
111548    pPtr = *(void **)sqlite3_value_blob(argv[1]);
111549    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
111550    if( pOld==pPtr ){
111551      sqlite3_result_error(context, "out of memory", -1);
111552      return;
111553    }
111554  }else{
111555    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
111556    if( !pPtr ){
111557      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
111558      sqlite3_result_error(context, zErr, -1);
111559      sqlite3_free(zErr);
111560      return;
111561    }
111562  }
111563
111564  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
111565}
111566
111567static int fts3IsIdChar(char c){
111568  static const char isFtsIdChar[] = {
111569      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
111570      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
111571      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
111572      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
111573      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
111574      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
111575      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
111576      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
111577  };
111578  return (c&0x80 || isFtsIdChar[(int)(c)]);
111579}
111580
111581SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
111582  const char *z1;
111583  const char *z2 = 0;
111584
111585  /* Find the start of the next token. */
111586  z1 = zStr;
111587  while( z2==0 ){
111588    char c = *z1;
111589    switch( c ){
111590      case '\0': return 0;        /* No more tokens here */
111591      case '\'':
111592      case '"':
111593      case '`': {
111594        z2 = z1;
111595        while( *++z2 && (*z2!=c || *++z2==c) );
111596        break;
111597      }
111598      case '[':
111599        z2 = &z1[1];
111600        while( *z2 && z2[0]!=']' ) z2++;
111601        if( *z2 ) z2++;
111602        break;
111603
111604      default:
111605        if( fts3IsIdChar(*z1) ){
111606          z2 = &z1[1];
111607          while( fts3IsIdChar(*z2) ) z2++;
111608        }else{
111609          z1++;
111610        }
111611    }
111612  }
111613
111614  *pn = (int)(z2-z1);
111615  return z1;
111616}
111617
111618SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
111619  Fts3Hash *pHash,                /* Tokenizer hash table */
111620  const char *zArg,               /* Possible tokenizer specification */
111621  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
111622  const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
111623  char **pzErr                    /* OUT: Set to malloced error message */
111624){
111625  int rc;
111626  char *z = (char *)zArg;
111627  int n;
111628  char *zCopy;
111629  char *zEnd;                     /* Pointer to nul-term of zCopy */
111630  sqlite3_tokenizer_module *m;
111631
111632  if( !z ){
111633    zCopy = sqlite3_mprintf("simple");
111634  }else{
111635    if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
111636      return SQLITE_OK;
111637    }
111638    zCopy = sqlite3_mprintf("%s", &z[8]);
111639    *pzTokenizer = zArg;
111640  }
111641  if( !zCopy ){
111642    return SQLITE_NOMEM;
111643  }
111644
111645  zEnd = &zCopy[strlen(zCopy)];
111646
111647  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
111648  z[n] = '\0';
111649  sqlite3Fts3Dequote(z);
111650
111651  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
111652  if( !m ){
111653    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
111654    rc = SQLITE_ERROR;
111655  }else{
111656    char const **aArg = 0;
111657    int iArg = 0;
111658    z = &z[n+1];
111659    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
111660      int nNew = sizeof(char *)*(iArg+1);
111661      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
111662      if( !aNew ){
111663        sqlite3_free(zCopy);
111664        sqlite3_free((void *)aArg);
111665        return SQLITE_NOMEM;
111666      }
111667      aArg = aNew;
111668      aArg[iArg++] = z;
111669      z[n] = '\0';
111670      sqlite3Fts3Dequote(z);
111671      z = &z[n+1];
111672    }
111673    rc = m->xCreate(iArg, aArg, ppTok);
111674    assert( rc!=SQLITE_OK || *ppTok );
111675    if( rc!=SQLITE_OK ){
111676      *pzErr = sqlite3_mprintf("unknown tokenizer");
111677    }else{
111678      (*ppTok)->pModule = m;
111679    }
111680    sqlite3_free((void *)aArg);
111681  }
111682
111683  sqlite3_free(zCopy);
111684  return rc;
111685}
111686
111687
111688#ifdef SQLITE_TEST
111689
111690
111691/*
111692** Implementation of a special SQL scalar function for testing tokenizers
111693** designed to be used in concert with the Tcl testing framework. This
111694** function must be called with two arguments:
111695**
111696**   SELECT <function-name>(<key-name>, <input-string>);
111697**   SELECT <function-name>(<key-name>, <pointer>);
111698**
111699** where <function-name> is the name passed as the second argument
111700** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
111701** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
111702**
111703** The return value is a string that may be interpreted as a Tcl
111704** list. For each token in the <input-string>, three elements are
111705** added to the returned list. The first is the token position, the
111706** second is the token text (folded, stemmed, etc.) and the third is the
111707** substring of <input-string> associated with the token. For example,
111708** using the built-in "simple" tokenizer:
111709**
111710**   SELECT fts_tokenizer_test('simple', 'I don't see how');
111711**
111712** will return the string:
111713**
111714**   "{0 i I 1 dont don't 2 see see 3 how how}"
111715**
111716*/
111717static void testFunc(
111718  sqlite3_context *context,
111719  int argc,
111720  sqlite3_value **argv
111721){
111722  Fts3Hash *pHash;
111723  sqlite3_tokenizer_module *p;
111724  sqlite3_tokenizer *pTokenizer = 0;
111725  sqlite3_tokenizer_cursor *pCsr = 0;
111726
111727  const char *zErr = 0;
111728
111729  const char *zName;
111730  int nName;
111731  const char *zInput;
111732  int nInput;
111733
111734  const char *zArg = 0;
111735
111736  const char *zToken;
111737  int nToken;
111738  int iStart;
111739  int iEnd;
111740  int iPos;
111741
111742  Tcl_Obj *pRet;
111743
111744  assert( argc==2 || argc==3 );
111745
111746  nName = sqlite3_value_bytes(argv[0]);
111747  zName = (const char *)sqlite3_value_text(argv[0]);
111748  nInput = sqlite3_value_bytes(argv[argc-1]);
111749  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
111750
111751  if( argc==3 ){
111752    zArg = (const char *)sqlite3_value_text(argv[1]);
111753  }
111754
111755  pHash = (Fts3Hash *)sqlite3_user_data(context);
111756  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
111757
111758  if( !p ){
111759    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
111760    sqlite3_result_error(context, zErr, -1);
111761    sqlite3_free(zErr);
111762    return;
111763  }
111764
111765  pRet = Tcl_NewObj();
111766  Tcl_IncrRefCount(pRet);
111767
111768  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
111769    zErr = "error in xCreate()";
111770    goto finish;
111771  }
111772  pTokenizer->pModule = p;
111773  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
111774    zErr = "error in xOpen()";
111775    goto finish;
111776  }
111777  pCsr->pTokenizer = pTokenizer;
111778
111779  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
111780    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
111781    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
111782    zToken = &zInput[iStart];
111783    nToken = iEnd-iStart;
111784    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
111785  }
111786
111787  if( SQLITE_OK!=p->xClose(pCsr) ){
111788    zErr = "error in xClose()";
111789    goto finish;
111790  }
111791  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
111792    zErr = "error in xDestroy()";
111793    goto finish;
111794  }
111795
111796finish:
111797  if( zErr ){
111798    sqlite3_result_error(context, zErr, -1);
111799  }else{
111800    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
111801  }
111802  Tcl_DecrRefCount(pRet);
111803}
111804
111805static
111806int registerTokenizer(
111807  sqlite3 *db,
111808  char *zName,
111809  const sqlite3_tokenizer_module *p
111810){
111811  int rc;
111812  sqlite3_stmt *pStmt;
111813  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
111814
111815  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
111816  if( rc!=SQLITE_OK ){
111817    return rc;
111818  }
111819
111820  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
111821  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
111822  sqlite3_step(pStmt);
111823
111824  return sqlite3_finalize(pStmt);
111825}
111826
111827static
111828int queryTokenizer(
111829  sqlite3 *db,
111830  char *zName,
111831  const sqlite3_tokenizer_module **pp
111832){
111833  int rc;
111834  sqlite3_stmt *pStmt;
111835  const char zSql[] = "SELECT fts3_tokenizer(?)";
111836
111837  *pp = 0;
111838  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
111839  if( rc!=SQLITE_OK ){
111840    return rc;
111841  }
111842
111843  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
111844  if( SQLITE_ROW==sqlite3_step(pStmt) ){
111845    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
111846      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
111847    }
111848  }
111849
111850  return sqlite3_finalize(pStmt);
111851}
111852
111853SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111854
111855/*
111856** Implementation of the scalar function fts3_tokenizer_internal_test().
111857** This function is used for testing only, it is not included in the
111858** build unless SQLITE_TEST is defined.
111859**
111860** The purpose of this is to test that the fts3_tokenizer() function
111861** can be used as designed by the C-code in the queryTokenizer and
111862** registerTokenizer() functions above. These two functions are repeated
111863** in the README.tokenizer file as an example, so it is important to
111864** test them.
111865**
111866** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
111867** function with no arguments. An assert() will fail if a problem is
111868** detected. i.e.:
111869**
111870**     SELECT fts3_tokenizer_internal_test();
111871**
111872*/
111873static void intTestFunc(
111874  sqlite3_context *context,
111875  int argc,
111876  sqlite3_value **argv
111877){
111878  int rc;
111879  const sqlite3_tokenizer_module *p1;
111880  const sqlite3_tokenizer_module *p2;
111881  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
111882
111883  UNUSED_PARAMETER(argc);
111884  UNUSED_PARAMETER(argv);
111885
111886  /* Test the query function */
111887  sqlite3Fts3SimpleTokenizerModule(&p1);
111888  rc = queryTokenizer(db, "simple", &p2);
111889  assert( rc==SQLITE_OK );
111890  assert( p1==p2 );
111891  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
111892  assert( rc==SQLITE_ERROR );
111893  assert( p2==0 );
111894  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
111895
111896  /* Test the storage function */
111897  rc = registerTokenizer(db, "nosuchtokenizer", p1);
111898  assert( rc==SQLITE_OK );
111899  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
111900  assert( rc==SQLITE_OK );
111901  assert( p2==p1 );
111902
111903  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
111904}
111905
111906#endif
111907
111908/*
111909** Set up SQL objects in database db used to access the contents of
111910** the hash table pointed to by argument pHash. The hash table must
111911** been initialised to use string keys, and to take a private copy
111912** of the key when a value is inserted. i.e. by a call similar to:
111913**
111914**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
111915**
111916** This function adds a scalar function (see header comment above
111917** scalarFunc() in this file for details) and, if ENABLE_TABLE is
111918** defined at compilation time, a temporary virtual table (see header
111919** comment above struct HashTableVtab) to the database schema. Both
111920** provide read/write access to the contents of *pHash.
111921**
111922** The third argument to this function, zName, is used as the name
111923** of both the scalar and, if created, the virtual table.
111924*/
111925SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
111926  sqlite3 *db,
111927  Fts3Hash *pHash,
111928  const char *zName
111929){
111930  int rc = SQLITE_OK;
111931  void *p = (void *)pHash;
111932  const int any = SQLITE_ANY;
111933
111934#ifdef SQLITE_TEST
111935  char *zTest = 0;
111936  char *zTest2 = 0;
111937  void *pdb = (void *)db;
111938  zTest = sqlite3_mprintf("%s_test", zName);
111939  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
111940  if( !zTest || !zTest2 ){
111941    rc = SQLITE_NOMEM;
111942  }
111943#endif
111944
111945  if( SQLITE_OK!=rc
111946   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
111947   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
111948#ifdef SQLITE_TEST
111949   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
111950   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
111951   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
111952#endif
111953   );
111954
111955#ifdef SQLITE_TEST
111956  sqlite3_free(zTest);
111957  sqlite3_free(zTest2);
111958#endif
111959
111960  return rc;
111961}
111962
111963#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111964
111965/************** End of fts3_tokenizer.c **************************************/
111966/************** Begin file fts3_tokenizer1.c *********************************/
111967/*
111968** 2006 Oct 10
111969**
111970** The author disclaims copyright to this source code.  In place of
111971** a legal notice, here is a blessing:
111972**
111973**    May you do good and not evil.
111974**    May you find forgiveness for yourself and forgive others.
111975**    May you share freely, never taking more than you give.
111976**
111977******************************************************************************
111978**
111979** Implementation of the "simple" full-text-search tokenizer.
111980*/
111981
111982/*
111983** The code in this file is only compiled if:
111984**
111985**     * The FTS3 module is being built as an extension
111986**       (in which case SQLITE_CORE is not defined), or
111987**
111988**     * The FTS3 module is being built into the core of
111989**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111990*/
111991#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111992
111993
111994
111995
111996typedef struct simple_tokenizer {
111997  sqlite3_tokenizer base;
111998  char delim[128];             /* flag ASCII delimiters */
111999} simple_tokenizer;
112000
112001typedef struct simple_tokenizer_cursor {
112002  sqlite3_tokenizer_cursor base;
112003  const char *pInput;          /* input we are tokenizing */
112004  int nBytes;                  /* size of the input */
112005  int iOffset;                 /* current position in pInput */
112006  int iToken;                  /* index of next token to be returned */
112007  char *pToken;                /* storage for current token */
112008  int nTokenAllocated;         /* space allocated to zToken buffer */
112009} simple_tokenizer_cursor;
112010
112011
112012static int simpleDelim(simple_tokenizer *t, unsigned char c){
112013  return c<0x80 && t->delim[c];
112014}
112015static int fts3_isalnum(int x){
112016  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
112017}
112018
112019/*
112020** Create a new tokenizer instance.
112021*/
112022static int simpleCreate(
112023  int argc, const char * const *argv,
112024  sqlite3_tokenizer **ppTokenizer
112025){
112026  simple_tokenizer *t;
112027
112028  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
112029  if( t==NULL ) return SQLITE_NOMEM;
112030  memset(t, 0, sizeof(*t));
112031
112032  /* TODO(shess) Delimiters need to remain the same from run to run,
112033  ** else we need to reindex.  One solution would be a meta-table to
112034  ** track such information in the database, then we'd only want this
112035  ** information on the initial create.
112036  */
112037  if( argc>1 ){
112038    int i, n = (int)strlen(argv[1]);
112039    for(i=0; i<n; i++){
112040      unsigned char ch = argv[1][i];
112041      /* We explicitly don't support UTF-8 delimiters for now. */
112042      if( ch>=0x80 ){
112043        sqlite3_free(t);
112044        return SQLITE_ERROR;
112045      }
112046      t->delim[ch] = 1;
112047    }
112048  } else {
112049    /* Mark non-alphanumeric ASCII characters as delimiters */
112050    int i;
112051    for(i=1; i<0x80; i++){
112052      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
112053    }
112054  }
112055
112056  *ppTokenizer = &t->base;
112057  return SQLITE_OK;
112058}
112059
112060/*
112061** Destroy a tokenizer
112062*/
112063static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
112064  sqlite3_free(pTokenizer);
112065  return SQLITE_OK;
112066}
112067
112068/*
112069** Prepare to begin tokenizing a particular string.  The input
112070** string to be tokenized is pInput[0..nBytes-1].  A cursor
112071** used to incrementally tokenize this string is returned in
112072** *ppCursor.
112073*/
112074static int simpleOpen(
112075  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
112076  const char *pInput, int nBytes,        /* String to be tokenized */
112077  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
112078){
112079  simple_tokenizer_cursor *c;
112080
112081  UNUSED_PARAMETER(pTokenizer);
112082
112083  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
112084  if( c==NULL ) return SQLITE_NOMEM;
112085
112086  c->pInput = pInput;
112087  if( pInput==0 ){
112088    c->nBytes = 0;
112089  }else if( nBytes<0 ){
112090    c->nBytes = (int)strlen(pInput);
112091  }else{
112092    c->nBytes = nBytes;
112093  }
112094  c->iOffset = 0;                 /* start tokenizing at the beginning */
112095  c->iToken = 0;
112096  c->pToken = NULL;               /* no space allocated, yet. */
112097  c->nTokenAllocated = 0;
112098
112099  *ppCursor = &c->base;
112100  return SQLITE_OK;
112101}
112102
112103/*
112104** Close a tokenization cursor previously opened by a call to
112105** simpleOpen() above.
112106*/
112107static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
112108  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
112109  sqlite3_free(c->pToken);
112110  sqlite3_free(c);
112111  return SQLITE_OK;
112112}
112113
112114/*
112115** Extract the next token from a tokenization cursor.  The cursor must
112116** have been opened by a prior call to simpleOpen().
112117*/
112118static int simpleNext(
112119  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
112120  const char **ppToken,               /* OUT: *ppToken is the token text */
112121  int *pnBytes,                       /* OUT: Number of bytes in token */
112122  int *piStartOffset,                 /* OUT: Starting offset of token */
112123  int *piEndOffset,                   /* OUT: Ending offset of token */
112124  int *piPosition                     /* OUT: Position integer of token */
112125){
112126  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
112127  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
112128  unsigned char *p = (unsigned char *)c->pInput;
112129
112130  while( c->iOffset<c->nBytes ){
112131    int iStartOffset;
112132
112133    /* Scan past delimiter characters */
112134    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
112135      c->iOffset++;
112136    }
112137
112138    /* Count non-delimiter characters. */
112139    iStartOffset = c->iOffset;
112140    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
112141      c->iOffset++;
112142    }
112143
112144    if( c->iOffset>iStartOffset ){
112145      int i, n = c->iOffset-iStartOffset;
112146      if( n>c->nTokenAllocated ){
112147        char *pNew;
112148        c->nTokenAllocated = n+20;
112149        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
112150        if( !pNew ) return SQLITE_NOMEM;
112151        c->pToken = pNew;
112152      }
112153      for(i=0; i<n; i++){
112154        /* TODO(shess) This needs expansion to handle UTF-8
112155        ** case-insensitivity.
112156        */
112157        unsigned char ch = p[iStartOffset+i];
112158        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
112159      }
112160      *ppToken = c->pToken;
112161      *pnBytes = n;
112162      *piStartOffset = iStartOffset;
112163      *piEndOffset = c->iOffset;
112164      *piPosition = c->iToken++;
112165
112166      return SQLITE_OK;
112167    }
112168  }
112169  return SQLITE_DONE;
112170}
112171
112172/*
112173** The set of routines that implement the simple tokenizer
112174*/
112175static const sqlite3_tokenizer_module simpleTokenizerModule = {
112176  0,
112177  simpleCreate,
112178  simpleDestroy,
112179  simpleOpen,
112180  simpleClose,
112181  simpleNext,
112182};
112183
112184/*
112185** Allocate a new simple tokenizer.  Return a pointer to the new
112186** tokenizer in *ppModule
112187*/
112188SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
112189  sqlite3_tokenizer_module const**ppModule
112190){
112191  *ppModule = &simpleTokenizerModule;
112192}
112193
112194#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
112195
112196/************** End of fts3_tokenizer1.c *************************************/
112197/************** Begin file fts3_write.c **************************************/
112198/*
112199** 2009 Oct 23
112200**
112201** The author disclaims copyright to this source code.  In place of
112202** a legal notice, here is a blessing:
112203**
112204**    May you do good and not evil.
112205**    May you find forgiveness for yourself and forgive others.
112206**    May you share freely, never taking more than you give.
112207**
112208******************************************************************************
112209**
112210** This file is part of the SQLite FTS3 extension module. Specifically,
112211** this file contains code to insert, update and delete rows from FTS3
112212** tables. It also contains code to merge FTS3 b-tree segments. Some
112213** of the sub-routines used to merge segments are also used by the query
112214** code in fts3.c.
112215*/
112216
112217#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112218
112219
112220typedef struct PendingList PendingList;
112221typedef struct SegmentNode SegmentNode;
112222typedef struct SegmentWriter SegmentWriter;
112223
112224/*
112225** Data structure used while accumulating terms in the pending-terms hash
112226** table. The hash table entry maps from term (a string) to a malloc'd
112227** instance of this structure.
112228*/
112229struct PendingList {
112230  int nData;
112231  char *aData;
112232  int nSpace;
112233  sqlite3_int64 iLastDocid;
112234  sqlite3_int64 iLastCol;
112235  sqlite3_int64 iLastPos;
112236};
112237
112238/*
112239** An instance of this structure is used to iterate through the terms on
112240** a contiguous set of segment b-tree leaf nodes. Although the details of
112241** this structure are only manipulated by code in this file, opaque handles
112242** of type Fts3SegReader* are also used by code in fts3.c to iterate through
112243** terms when querying the full-text index. See functions:
112244**
112245**   sqlite3Fts3SegReaderNew()
112246**   sqlite3Fts3SegReaderFree()
112247**   sqlite3Fts3SegReaderIterate()
112248**
112249** Methods used to manipulate Fts3SegReader structures:
112250**
112251**   fts3SegReaderNext()
112252**   fts3SegReaderFirstDocid()
112253**   fts3SegReaderNextDocid()
112254*/
112255struct Fts3SegReader {
112256  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
112257  sqlite3_int64 iStartBlock;
112258  sqlite3_int64 iEndBlock;
112259  sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
112260  char *aNode;                    /* Pointer to node data (or NULL) */
112261  int nNode;                      /* Size of buffer at aNode (or 0) */
112262  int nTermAlloc;                 /* Allocated size of zTerm buffer */
112263  Fts3HashElem **ppNextElem;
112264
112265  /* Variables set by fts3SegReaderNext(). These may be read directly
112266  ** by the caller. They are valid from the time SegmentReaderNew() returns
112267  ** until SegmentReaderNext() returns something other than SQLITE_OK
112268  ** (i.e. SQLITE_DONE).
112269  */
112270  int nTerm;                      /* Number of bytes in current term */
112271  char *zTerm;                    /* Pointer to current term */
112272  char *aDoclist;                 /* Pointer to doclist of current entry */
112273  int nDoclist;                   /* Size of doclist in current entry */
112274
112275  /* The following variables are used to iterate through the current doclist */
112276  char *pOffsetList;
112277  sqlite3_int64 iDocid;
112278};
112279
112280#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
112281
112282/*
112283** An instance of this structure is used to create a segment b-tree in the
112284** database. The internal details of this type are only accessed by the
112285** following functions:
112286**
112287**   fts3SegWriterAdd()
112288**   fts3SegWriterFlush()
112289**   fts3SegWriterFree()
112290*/
112291struct SegmentWriter {
112292  SegmentNode *pTree;             /* Pointer to interior tree structure */
112293  sqlite3_int64 iFirst;           /* First slot in %_segments written */
112294  sqlite3_int64 iFree;            /* Next free slot in %_segments */
112295  char *zTerm;                    /* Pointer to previous term buffer */
112296  int nTerm;                      /* Number of bytes in zTerm */
112297  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
112298  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
112299  int nSize;                      /* Size of allocation at aData */
112300  int nData;                      /* Bytes of data in aData */
112301  char *aData;                    /* Pointer to block from malloc() */
112302};
112303
112304/*
112305** Type SegmentNode is used by the following three functions to create
112306** the interior part of the segment b+-tree structures (everything except
112307** the leaf nodes). These functions and type are only ever used by code
112308** within the fts3SegWriterXXX() family of functions described above.
112309**
112310**   fts3NodeAddTerm()
112311**   fts3NodeWrite()
112312**   fts3NodeFree()
112313*/
112314struct SegmentNode {
112315  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
112316  SegmentNode *pRight;            /* Pointer to right-sibling */
112317  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
112318  int nEntry;                     /* Number of terms written to node so far */
112319  char *zTerm;                    /* Pointer to previous term buffer */
112320  int nTerm;                      /* Number of bytes in zTerm */
112321  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
112322  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
112323  int nData;                      /* Bytes of valid data so far */
112324  char *aData;                    /* Node data */
112325};
112326
112327/*
112328** Valid values for the second argument to fts3SqlStmt().
112329*/
112330#define SQL_DELETE_CONTENT             0
112331#define SQL_IS_EMPTY                   1
112332#define SQL_DELETE_ALL_CONTENT         2
112333#define SQL_DELETE_ALL_SEGMENTS        3
112334#define SQL_DELETE_ALL_SEGDIR          4
112335#define SQL_DELETE_ALL_DOCSIZE         5
112336#define SQL_DELETE_ALL_STAT            6
112337#define SQL_SELECT_CONTENT_BY_ROWID    7
112338#define SQL_NEXT_SEGMENT_INDEX         8
112339#define SQL_INSERT_SEGMENTS            9
112340#define SQL_NEXT_SEGMENTS_ID          10
112341#define SQL_INSERT_SEGDIR             11
112342#define SQL_SELECT_LEVEL              12
112343#define SQL_SELECT_ALL_LEVEL          13
112344#define SQL_SELECT_LEVEL_COUNT        14
112345#define SQL_SELECT_SEGDIR_COUNT_MAX   15
112346#define SQL_DELETE_SEGDIR_BY_LEVEL    16
112347#define SQL_DELETE_SEGMENTS_RANGE     17
112348#define SQL_CONTENT_INSERT            18
112349#define SQL_GET_BLOCK                 19
112350#define SQL_DELETE_DOCSIZE            20
112351#define SQL_REPLACE_DOCSIZE           21
112352#define SQL_SELECT_DOCSIZE            22
112353#define SQL_SELECT_DOCTOTAL           23
112354#define SQL_REPLACE_DOCTOTAL          24
112355
112356/*
112357** This function is used to obtain an SQLite prepared statement handle
112358** for the statement identified by the second argument. If successful,
112359** *pp is set to the requested statement handle and SQLITE_OK returned.
112360** Otherwise, an SQLite error code is returned and *pp is set to 0.
112361**
112362** If argument apVal is not NULL, then it must point to an array with
112363** at least as many entries as the requested statement has bound
112364** parameters. The values are bound to the statements parameters before
112365** returning.
112366*/
112367static int fts3SqlStmt(
112368  Fts3Table *p,                   /* Virtual table handle */
112369  int eStmt,                      /* One of the SQL_XXX constants above */
112370  sqlite3_stmt **pp,              /* OUT: Statement handle */
112371  sqlite3_value **apVal           /* Values to bind to statement */
112372){
112373  const char *azSql[] = {
112374/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
112375/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
112376/* 2  */  "DELETE FROM %Q.'%q_content'",
112377/* 3  */  "DELETE FROM %Q.'%q_segments'",
112378/* 4  */  "DELETE FROM %Q.'%q_segdir'",
112379/* 5  */  "DELETE FROM %Q.'%q_docsize'",
112380/* 6  */  "DELETE FROM %Q.'%q_stat'",
112381/* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
112382/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
112383/* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
112384/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
112385/* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
112386
112387          /* Return segments in order from oldest to newest.*/
112388/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
112389            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
112390/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
112391            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
112392
112393/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
112394/* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
112395
112396/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
112397/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
112398/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
112399/* 19 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
112400/* 20 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
112401/* 21 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
112402/* 22 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
112403/* 23 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
112404/* 24 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
112405  };
112406  int rc = SQLITE_OK;
112407  sqlite3_stmt *pStmt;
112408
112409  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
112410  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
112411
112412  pStmt = p->aStmt[eStmt];
112413  if( !pStmt ){
112414    char *zSql;
112415    if( eStmt==SQL_CONTENT_INSERT ){
112416      int i;                      /* Iterator variable */
112417      char *zVarlist;             /* The "?, ?, ..." string */
112418      zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
112419      if( !zVarlist ){
112420        *pp = 0;
112421        return SQLITE_NOMEM;
112422      }
112423      zVarlist[0] = '?';
112424      zVarlist[p->nColumn*2+1] = '\0';
112425      for(i=1; i<=p->nColumn; i++){
112426        zVarlist[i*2-1] = ',';
112427        zVarlist[i*2] = '?';
112428      }
112429      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
112430    }else{
112431      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
112432    }
112433    if( !zSql ){
112434      rc = SQLITE_NOMEM;
112435    }else{
112436      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
112437      sqlite3_free(zSql);
112438      assert( rc==SQLITE_OK || pStmt==0 );
112439      p->aStmt[eStmt] = pStmt;
112440    }
112441  }
112442  if( apVal ){
112443    int i;
112444    int nParam = sqlite3_bind_parameter_count(pStmt);
112445    for(i=0; rc==SQLITE_OK && i<nParam; i++){
112446      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
112447    }
112448  }
112449  *pp = pStmt;
112450  return rc;
112451}
112452
112453/*
112454** Similar to fts3SqlStmt(). Except, after binding the parameters in
112455** array apVal[] to the SQL statement identified by eStmt, the statement
112456** is executed.
112457**
112458** Returns SQLITE_OK if the statement is successfully executed, or an
112459** SQLite error code otherwise.
112460*/
112461static void fts3SqlExec(
112462  int *pRC,                /* Result code */
112463  Fts3Table *p,            /* The FTS3 table */
112464  int eStmt,               /* Index of statement to evaluate */
112465  sqlite3_value **apVal    /* Parameters to bind */
112466){
112467  sqlite3_stmt *pStmt;
112468  int rc;
112469  if( *pRC ) return;
112470  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
112471  if( rc==SQLITE_OK ){
112472    sqlite3_step(pStmt);
112473    rc = sqlite3_reset(pStmt);
112474  }
112475  *pRC = rc;
112476}
112477
112478
112479/*
112480** Read a single block from the %_segments table. If the specified block
112481** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
112482** etc.) occurs, return the appropriate SQLite error code.
112483**
112484** Otherwise, if successful, set *pzBlock to point to a buffer containing
112485** the block read from the database, and *pnBlock to the size of the read
112486** block in bytes.
112487**
112488** WARNING: The returned buffer is only valid until the next call to
112489** sqlite3Fts3ReadBlock().
112490*/
112491SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
112492  Fts3Table *p,
112493  sqlite3_int64 iBlock,
112494  char const **pzBlock,
112495  int *pnBlock
112496){
112497  sqlite3_stmt *pStmt;
112498  int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
112499  if( rc!=SQLITE_OK ) return rc;
112500  sqlite3_reset(pStmt);
112501
112502  if( pzBlock ){
112503    sqlite3_bind_int64(pStmt, 1, iBlock);
112504    rc = sqlite3_step(pStmt);
112505    if( rc!=SQLITE_ROW ){
112506      return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
112507    }
112508
112509    *pnBlock = sqlite3_column_bytes(pStmt, 0);
112510    *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
112511    if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
112512      return SQLITE_CORRUPT;
112513    }
112514  }
112515  return SQLITE_OK;
112516}
112517
112518/*
112519** Set *ppStmt to a statement handle that may be used to iterate through
112520** all rows in the %_segdir table, from oldest to newest. If successful,
112521** return SQLITE_OK. If an error occurs while preparing the statement,
112522** return an SQLite error code.
112523**
112524** There is only ever one instance of this SQL statement compiled for
112525** each FTS3 table.
112526**
112527** The statement returns the following columns from the %_segdir table:
112528**
112529**   0: idx
112530**   1: start_block
112531**   2: leaves_end_block
112532**   3: end_block
112533**   4: root
112534*/
112535SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
112536  return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
112537}
112538
112539
112540/*
112541** Append a single varint to a PendingList buffer. SQLITE_OK is returned
112542** if successful, or an SQLite error code otherwise.
112543**
112544** This function also serves to allocate the PendingList structure itself.
112545** For example, to create a new PendingList structure containing two
112546** varints:
112547**
112548**   PendingList *p = 0;
112549**   fts3PendingListAppendVarint(&p, 1);
112550**   fts3PendingListAppendVarint(&p, 2);
112551*/
112552static int fts3PendingListAppendVarint(
112553  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
112554  sqlite3_int64 i                 /* Value to append to data */
112555){
112556  PendingList *p = *pp;
112557
112558  /* Allocate or grow the PendingList as required. */
112559  if( !p ){
112560    p = sqlite3_malloc(sizeof(*p) + 100);
112561    if( !p ){
112562      return SQLITE_NOMEM;
112563    }
112564    p->nSpace = 100;
112565    p->aData = (char *)&p[1];
112566    p->nData = 0;
112567  }
112568  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
112569    int nNew = p->nSpace * 2;
112570    p = sqlite3_realloc(p, sizeof(*p) + nNew);
112571    if( !p ){
112572      sqlite3_free(*pp);
112573      *pp = 0;
112574      return SQLITE_NOMEM;
112575    }
112576    p->nSpace = nNew;
112577    p->aData = (char *)&p[1];
112578  }
112579
112580  /* Append the new serialized varint to the end of the list. */
112581  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
112582  p->aData[p->nData] = '\0';
112583  *pp = p;
112584  return SQLITE_OK;
112585}
112586
112587/*
112588** Add a docid/column/position entry to a PendingList structure. Non-zero
112589** is returned if the structure is sqlite3_realloced as part of adding
112590** the entry. Otherwise, zero.
112591**
112592** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
112593** Zero is always returned in this case. Otherwise, if no OOM error occurs,
112594** it is set to SQLITE_OK.
112595*/
112596static int fts3PendingListAppend(
112597  PendingList **pp,               /* IN/OUT: PendingList structure */
112598  sqlite3_int64 iDocid,           /* Docid for entry to add */
112599  sqlite3_int64 iCol,             /* Column for entry to add */
112600  sqlite3_int64 iPos,             /* Position of term for entry to add */
112601  int *pRc                        /* OUT: Return code */
112602){
112603  PendingList *p = *pp;
112604  int rc = SQLITE_OK;
112605
112606  assert( !p || p->iLastDocid<=iDocid );
112607
112608  if( !p || p->iLastDocid!=iDocid ){
112609    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
112610    if( p ){
112611      assert( p->nData<p->nSpace );
112612      assert( p->aData[p->nData]==0 );
112613      p->nData++;
112614    }
112615    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
112616      goto pendinglistappend_out;
112617    }
112618    p->iLastCol = -1;
112619    p->iLastPos = 0;
112620    p->iLastDocid = iDocid;
112621  }
112622  if( iCol>0 && p->iLastCol!=iCol ){
112623    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
112624     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
112625    ){
112626      goto pendinglistappend_out;
112627    }
112628    p->iLastCol = iCol;
112629    p->iLastPos = 0;
112630  }
112631  if( iCol>=0 ){
112632    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
112633    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
112634    if( rc==SQLITE_OK ){
112635      p->iLastPos = iPos;
112636    }
112637  }
112638
112639 pendinglistappend_out:
112640  *pRc = rc;
112641  if( p!=*pp ){
112642    *pp = p;
112643    return 1;
112644  }
112645  return 0;
112646}
112647
112648/*
112649** Tokenize the nul-terminated string zText and add all tokens to the
112650** pending-terms hash-table. The docid used is that currently stored in
112651** p->iPrevDocid, and the column is specified by argument iCol.
112652**
112653** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
112654*/
112655static int fts3PendingTermsAdd(
112656  Fts3Table *p,          /* FTS table into which text will be inserted */
112657  const char *zText,     /* Text of document to be inseted */
112658  int iCol,              /* Column number into which text is inserted */
112659  u32 *pnWord            /* OUT: Number of tokens inserted */
112660){
112661  int rc;
112662  int iStart;
112663  int iEnd;
112664  int iPos;
112665  int nWord = 0;
112666
112667  char const *zToken;
112668  int nToken;
112669
112670  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
112671  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
112672  sqlite3_tokenizer_cursor *pCsr;
112673  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
112674      const char**,int*,int*,int*,int*);
112675
112676  assert( pTokenizer && pModule );
112677
112678  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
112679  if( rc!=SQLITE_OK ){
112680    return rc;
112681  }
112682  pCsr->pTokenizer = pTokenizer;
112683
112684  xNext = pModule->xNext;
112685  while( SQLITE_OK==rc
112686      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
112687  ){
112688    PendingList *pList;
112689
112690    if( iPos>=nWord ) nWord = iPos+1;
112691
112692    /* Positions cannot be negative; we use -1 as a terminator internally.
112693    ** Tokens must have a non-zero length.
112694    */
112695    if( iPos<0 || !zToken || nToken<=0 ){
112696      rc = SQLITE_ERROR;
112697      break;
112698    }
112699
112700    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
112701    if( pList ){
112702      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
112703    }
112704    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
112705      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
112706        /* Malloc failed while inserting the new entry. This can only
112707        ** happen if there was no previous entry for this token.
112708        */
112709        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
112710        sqlite3_free(pList);
112711        rc = SQLITE_NOMEM;
112712      }
112713    }
112714    if( rc==SQLITE_OK ){
112715      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
112716    }
112717  }
112718
112719  pModule->xClose(pCsr);
112720  *pnWord = nWord;
112721  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
112722}
112723
112724/*
112725** Calling this function indicates that subsequent calls to
112726** fts3PendingTermsAdd() are to add term/position-list pairs for the
112727** contents of the document with docid iDocid.
112728*/
112729static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
112730  /* TODO(shess) Explore whether partially flushing the buffer on
112731  ** forced-flush would provide better performance.  I suspect that if
112732  ** we ordered the doclists by size and flushed the largest until the
112733  ** buffer was half empty, that would let the less frequent terms
112734  ** generate longer doclists.
112735  */
112736  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
112737    int rc = sqlite3Fts3PendingTermsFlush(p);
112738    if( rc!=SQLITE_OK ) return rc;
112739  }
112740  p->iPrevDocid = iDocid;
112741  return SQLITE_OK;
112742}
112743
112744SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
112745  Fts3HashElem *pElem;
112746  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
112747    sqlite3_free(fts3HashData(pElem));
112748  }
112749  fts3HashClear(&p->pendingTerms);
112750  p->nPendingData = 0;
112751}
112752
112753/*
112754** This function is called by the xUpdate() method as part of an INSERT
112755** operation. It adds entries for each term in the new record to the
112756** pendingTerms hash table.
112757**
112758** Argument apVal is the same as the similarly named argument passed to
112759** fts3InsertData(). Parameter iDocid is the docid of the new row.
112760*/
112761static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
112762  int i;                          /* Iterator variable */
112763  for(i=2; i<p->nColumn+2; i++){
112764    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
112765    if( zText ){
112766      int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
112767      if( rc!=SQLITE_OK ){
112768        return rc;
112769      }
112770    }
112771  }
112772  return SQLITE_OK;
112773}
112774
112775/*
112776** This function is called by the xUpdate() method for an INSERT operation.
112777** The apVal parameter is passed a copy of the apVal argument passed by
112778** SQLite to the xUpdate() method. i.e:
112779**
112780**   apVal[0]                Not used for INSERT.
112781**   apVal[1]                rowid
112782**   apVal[2]                Left-most user-defined column
112783**   ...
112784**   apVal[p->nColumn+1]     Right-most user-defined column
112785**   apVal[p->nColumn+2]     Hidden column with same name as table
112786**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
112787*/
112788static int fts3InsertData(
112789  Fts3Table *p,                   /* Full-text table */
112790  sqlite3_value **apVal,          /* Array of values to insert */
112791  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
112792){
112793  int rc;                         /* Return code */
112794  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
112795
112796  /* Locate the statement handle used to insert data into the %_content
112797  ** table. The SQL for this statement is:
112798  **
112799  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
112800  **
112801  ** The statement features N '?' variables, where N is the number of user
112802  ** defined columns in the FTS3 table, plus one for the docid field.
112803  */
112804  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
112805  if( rc!=SQLITE_OK ){
112806    return rc;
112807  }
112808
112809  /* There is a quirk here. The users INSERT statement may have specified
112810  ** a value for the "rowid" field, for the "docid" field, or for both.
112811  ** Which is a problem, since "rowid" and "docid" are aliases for the
112812  ** same value. For example:
112813  **
112814  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
112815  **
112816  ** In FTS3, this is an error. It is an error to specify non-NULL values
112817  ** for both docid and some other rowid alias.
112818  */
112819  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
112820    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
112821     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
112822    ){
112823      /* A rowid/docid conflict. */
112824      return SQLITE_ERROR;
112825    }
112826    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
112827    if( rc!=SQLITE_OK ) return rc;
112828  }
112829
112830  /* Execute the statement to insert the record. Set *piDocid to the
112831  ** new docid value.
112832  */
112833  sqlite3_step(pContentInsert);
112834  rc = sqlite3_reset(pContentInsert);
112835
112836  *piDocid = sqlite3_last_insert_rowid(p->db);
112837  return rc;
112838}
112839
112840
112841
112842/*
112843** Remove all data from the FTS3 table. Clear the hash table containing
112844** pending terms.
112845*/
112846static int fts3DeleteAll(Fts3Table *p){
112847  int rc = SQLITE_OK;             /* Return code */
112848
112849  /* Discard the contents of the pending-terms hash table. */
112850  sqlite3Fts3PendingTermsClear(p);
112851
112852  /* Delete everything from the %_content, %_segments and %_segdir tables. */
112853  fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
112854  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
112855  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
112856  if( p->bHasDocsize ){
112857    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
112858    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
112859  }
112860  return rc;
112861}
112862
112863/*
112864** The first element in the apVal[] array is assumed to contain the docid
112865** (an integer) of a row about to be deleted. Remove all terms from the
112866** full-text index.
112867*/
112868static void fts3DeleteTerms(
112869  int *pRC,               /* Result code */
112870  Fts3Table *p,           /* The FTS table to delete from */
112871  sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
112872  u32 *aSz                /* Sizes of deleted document written here */
112873){
112874  int rc;
112875  sqlite3_stmt *pSelect;
112876
112877  if( *pRC ) return;
112878  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
112879  if( rc==SQLITE_OK ){
112880    if( SQLITE_ROW==sqlite3_step(pSelect) ){
112881      int i;
112882      for(i=1; i<=p->nColumn; i++){
112883        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
112884        rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
112885        if( rc!=SQLITE_OK ){
112886          sqlite3_reset(pSelect);
112887          *pRC = rc;
112888          return;
112889        }
112890      }
112891    }
112892    rc = sqlite3_reset(pSelect);
112893  }else{
112894    sqlite3_reset(pSelect);
112895  }
112896  *pRC = rc;
112897}
112898
112899/*
112900** Forward declaration to account for the circular dependency between
112901** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
112902*/
112903static int fts3SegmentMerge(Fts3Table *, int);
112904
112905/*
112906** This function allocates a new level iLevel index in the segdir table.
112907** Usually, indexes are allocated within a level sequentially starting
112908** with 0, so the allocated index is one greater than the value returned
112909** by:
112910**
112911**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
112912**
112913** However, if there are already FTS3_MERGE_COUNT indexes at the requested
112914** level, they are merged into a single level (iLevel+1) segment and the
112915** allocated index is 0.
112916**
112917** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
112918** returned. Otherwise, an SQLite error code is returned.
112919*/
112920static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
112921  int rc;                         /* Return Code */
112922  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
112923  int iNext = 0;                  /* Result of query pNextIdx */
112924
112925  /* Set variable iNext to the next available segdir index at level iLevel. */
112926  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
112927  if( rc==SQLITE_OK ){
112928    sqlite3_bind_int(pNextIdx, 1, iLevel);
112929    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
112930      iNext = sqlite3_column_int(pNextIdx, 0);
112931    }
112932    rc = sqlite3_reset(pNextIdx);
112933  }
112934
112935  if( rc==SQLITE_OK ){
112936    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
112937    ** full, merge all segments in level iLevel into a single iLevel+1
112938    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
112939    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
112940    */
112941    if( iNext>=FTS3_MERGE_COUNT ){
112942      rc = fts3SegmentMerge(p, iLevel);
112943      *piIdx = 0;
112944    }else{
112945      *piIdx = iNext;
112946    }
112947  }
112948
112949  return rc;
112950}
112951
112952/*
112953** Move the iterator passed as the first argument to the next term in the
112954** segment. If successful, SQLITE_OK is returned. If there is no next term,
112955** SQLITE_DONE. Otherwise, an SQLite error code.
112956*/
112957static int fts3SegReaderNext(Fts3SegReader *pReader){
112958  char *pNext;                    /* Cursor variable */
112959  int nPrefix;                    /* Number of bytes in term prefix */
112960  int nSuffix;                    /* Number of bytes in term suffix */
112961
112962  if( !pReader->aDoclist ){
112963    pNext = pReader->aNode;
112964  }else{
112965    pNext = &pReader->aDoclist[pReader->nDoclist];
112966  }
112967
112968  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
112969    int rc;
112970    if( fts3SegReaderIsPending(pReader) ){
112971      Fts3HashElem *pElem = *(pReader->ppNextElem);
112972      if( pElem==0 ){
112973        pReader->aNode = 0;
112974      }else{
112975        PendingList *pList = (PendingList *)fts3HashData(pElem);
112976        pReader->zTerm = (char *)fts3HashKey(pElem);
112977        pReader->nTerm = fts3HashKeysize(pElem);
112978        pReader->nNode = pReader->nDoclist = pList->nData + 1;
112979        pReader->aNode = pReader->aDoclist = pList->aData;
112980        pReader->ppNextElem++;
112981        assert( pReader->aNode );
112982      }
112983      return SQLITE_OK;
112984    }
112985    if( !pReader->pStmt ){
112986      pReader->aNode = 0;
112987      return SQLITE_OK;
112988    }
112989    rc = sqlite3_step(pReader->pStmt);
112990    if( rc!=SQLITE_ROW ){
112991      pReader->aNode = 0;
112992      return (rc==SQLITE_DONE ? SQLITE_OK : rc);
112993    }
112994    pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
112995    pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
112996    pNext = pReader->aNode;
112997  }
112998
112999  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
113000  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
113001
113002  if( nPrefix+nSuffix>pReader->nTermAlloc ){
113003    int nNew = (nPrefix+nSuffix)*2;
113004    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
113005    if( !zNew ){
113006      return SQLITE_NOMEM;
113007    }
113008    pReader->zTerm = zNew;
113009    pReader->nTermAlloc = nNew;
113010  }
113011  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
113012  pReader->nTerm = nPrefix+nSuffix;
113013  pNext += nSuffix;
113014  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
113015  assert( pNext<&pReader->aNode[pReader->nNode] );
113016  pReader->aDoclist = pNext;
113017  pReader->pOffsetList = 0;
113018  return SQLITE_OK;
113019}
113020
113021/*
113022** Set the SegReader to point to the first docid in the doclist associated
113023** with the current term.
113024*/
113025static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
113026  int n;
113027  assert( pReader->aDoclist );
113028  assert( !pReader->pOffsetList );
113029  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
113030  pReader->pOffsetList = &pReader->aDoclist[n];
113031}
113032
113033/*
113034** Advance the SegReader to point to the next docid in the doclist
113035** associated with the current term.
113036**
113037** If arguments ppOffsetList and pnOffsetList are not NULL, then
113038** *ppOffsetList is set to point to the first column-offset list
113039** in the doclist entry (i.e. immediately past the docid varint).
113040** *pnOffsetList is set to the length of the set of column-offset
113041** lists, not including the nul-terminator byte. For example:
113042*/
113043static void fts3SegReaderNextDocid(
113044  Fts3SegReader *pReader,
113045  char **ppOffsetList,
113046  int *pnOffsetList
113047){
113048  char *p = pReader->pOffsetList;
113049  char c = 0;
113050
113051  /* Pointer p currently points at the first byte of an offset list. The
113052  ** following two lines advance it to point one byte past the end of
113053  ** the same offset list.
113054  */
113055  while( *p | c ) c = *p++ & 0x80;
113056  p++;
113057
113058  /* If required, populate the output variables with a pointer to and the
113059  ** size of the previous offset-list.
113060  */
113061  if( ppOffsetList ){
113062    *ppOffsetList = pReader->pOffsetList;
113063    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
113064  }
113065
113066  /* If there are no more entries in the doclist, set pOffsetList to
113067  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
113068  ** Fts3SegReader.pOffsetList to point to the next offset list before
113069  ** returning.
113070  */
113071  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
113072    pReader->pOffsetList = 0;
113073  }else{
113074    sqlite3_int64 iDelta;
113075    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
113076    pReader->iDocid += iDelta;
113077  }
113078}
113079
113080/*
113081** Free all allocations associated with the iterator passed as the
113082** second argument.
113083*/
113084SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
113085  if( pReader ){
113086    if( pReader->pStmt ){
113087      /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
113088      ** so that it can be reused when required by another query.
113089      */
113090      assert( p->nLeavesStmt<p->nLeavesTotal );
113091      sqlite3_reset(pReader->pStmt);
113092      p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
113093    }
113094    if( !fts3SegReaderIsPending(pReader) ){
113095      sqlite3_free(pReader->zTerm);
113096    }
113097    sqlite3_free(pReader);
113098  }
113099}
113100
113101/*
113102** Allocate a new SegReader object.
113103*/
113104SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
113105  Fts3Table *p,                   /* Virtual table handle */
113106  int iAge,                       /* Segment "age". */
113107  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
113108  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
113109  sqlite3_int64 iEndBlock,        /* Final block of segment */
113110  const char *zRoot,              /* Buffer containing root node */
113111  int nRoot,                      /* Size of buffer containing root node */
113112  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
113113){
113114  int rc = SQLITE_OK;             /* Return code */
113115  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
113116  int nExtra = 0;                 /* Bytes to allocate segment root node */
113117
113118  if( iStartLeaf==0 ){
113119    nExtra = nRoot;
113120  }
113121
113122  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
113123  if( !pReader ){
113124    return SQLITE_NOMEM;
113125  }
113126  memset(pReader, 0, sizeof(Fts3SegReader));
113127  pReader->iStartBlock = iStartLeaf;
113128  pReader->iIdx = iAge;
113129  pReader->iEndBlock = iEndBlock;
113130
113131  if( nExtra ){
113132    /* The entire segment is stored in the root node. */
113133    pReader->aNode = (char *)&pReader[1];
113134    pReader->nNode = nRoot;
113135    memcpy(pReader->aNode, zRoot, nRoot);
113136  }else{
113137    /* If the text of the SQL statement to iterate through a contiguous
113138    ** set of entries in the %_segments table has not yet been composed,
113139    ** compose it now.
113140    */
113141    if( !p->zSelectLeaves ){
113142      p->zSelectLeaves = sqlite3_mprintf(
113143          "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
113144          "ORDER BY blockid", p->zDb, p->zName
113145      );
113146      if( !p->zSelectLeaves ){
113147        rc = SQLITE_NOMEM;
113148        goto finished;
113149      }
113150    }
113151
113152    /* If there are no free statements in the aLeavesStmt[] array, prepare
113153    ** a new statement now. Otherwise, reuse a prepared statement from
113154    ** aLeavesStmt[].
113155    */
113156    if( p->nLeavesStmt==0 ){
113157      if( p->nLeavesTotal==p->nLeavesAlloc ){
113158        int nNew = p->nLeavesAlloc + 16;
113159        sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
113160            p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
113161        );
113162        if( !aNew ){
113163          rc = SQLITE_NOMEM;
113164          goto finished;
113165        }
113166        p->nLeavesAlloc = nNew;
113167        p->aLeavesStmt = aNew;
113168      }
113169      rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
113170      if( rc!=SQLITE_OK ){
113171        goto finished;
113172      }
113173      p->nLeavesTotal++;
113174    }else{
113175      pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
113176    }
113177
113178    /* Bind the start and end leaf blockids to the prepared SQL statement. */
113179    sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
113180    sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
113181  }
113182  rc = fts3SegReaderNext(pReader);
113183
113184 finished:
113185  if( rc==SQLITE_OK ){
113186    *ppReader = pReader;
113187  }else{
113188    sqlite3Fts3SegReaderFree(p, pReader);
113189  }
113190  return rc;
113191}
113192
113193/*
113194** This is a comparison function used as a qsort() callback when sorting
113195** an array of pending terms by term. This occurs as part of flushing
113196** the contents of the pending-terms hash table to the database.
113197*/
113198static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
113199  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
113200  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
113201  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
113202  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
113203
113204  int n = (n1<n2 ? n1 : n2);
113205  int c = memcmp(z1, z2, n);
113206  if( c==0 ){
113207    c = n1 - n2;
113208  }
113209  return c;
113210}
113211
113212/*
113213** This function is used to allocate an Fts3SegReader that iterates through
113214** a subset of the terms stored in the Fts3Table.pendingTerms array.
113215*/
113216SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
113217  Fts3Table *p,                   /* Virtual table handle */
113218  const char *zTerm,              /* Term to search for */
113219  int nTerm,                      /* Size of buffer zTerm */
113220  int isPrefix,                   /* True for a term-prefix query */
113221  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
113222){
113223  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
113224  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
113225  int nElem = 0;                  /* Size of array at aElem */
113226  int rc = SQLITE_OK;             /* Return Code */
113227
113228  if( isPrefix ){
113229    int nAlloc = 0;               /* Size of allocated array at aElem */
113230    Fts3HashElem *pE = 0;         /* Iterator variable */
113231
113232    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
113233      char *zKey = (char *)fts3HashKey(pE);
113234      int nKey = fts3HashKeysize(pE);
113235      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
113236        if( nElem==nAlloc ){
113237          Fts3HashElem **aElem2;
113238          nAlloc += 16;
113239          aElem2 = (Fts3HashElem **)sqlite3_realloc(
113240              aElem, nAlloc*sizeof(Fts3HashElem *)
113241          );
113242          if( !aElem2 ){
113243            rc = SQLITE_NOMEM;
113244            nElem = 0;
113245            break;
113246          }
113247          aElem = aElem2;
113248        }
113249        aElem[nElem++] = pE;
113250      }
113251    }
113252
113253    /* If more than one term matches the prefix, sort the Fts3HashElem
113254    ** objects in term order using qsort(). This uses the same comparison
113255    ** callback as is used when flushing terms to disk.
113256    */
113257    if( nElem>1 ){
113258      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
113259    }
113260
113261  }else{
113262    Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
113263    if( pE ){
113264      aElem = &pE;
113265      nElem = 1;
113266    }
113267  }
113268
113269  if( nElem>0 ){
113270    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
113271    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
113272    if( !pReader ){
113273      rc = SQLITE_NOMEM;
113274    }else{
113275      memset(pReader, 0, nByte);
113276      pReader->iIdx = 0x7FFFFFFF;
113277      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
113278      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
113279      fts3SegReaderNext(pReader);
113280    }
113281  }
113282
113283  if( isPrefix ){
113284    sqlite3_free(aElem);
113285  }
113286  *ppReader = pReader;
113287  return rc;
113288}
113289
113290
113291/*
113292** The second argument to this function is expected to be a statement of
113293** the form:
113294**
113295**   SELECT
113296**     idx,                  -- col 0
113297**     start_block,          -- col 1
113298**     leaves_end_block,     -- col 2
113299**     end_block,            -- col 3
113300**     root                  -- col 4
113301**   FROM %_segdir ...
113302**
113303** This function allocates and initializes a Fts3SegReader structure to
113304** iterate through the terms stored in the segment identified by the
113305** current row that pStmt is pointing to.
113306**
113307** If successful, the Fts3SegReader is left pointing to the first term
113308** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
113309** code is returned.
113310*/
113311static int fts3SegReaderNew(
113312  Fts3Table *p,                   /* Virtual table handle */
113313  sqlite3_stmt *pStmt,            /* See above */
113314  int iAge,                       /* Segment "age". */
113315  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
113316){
113317  return sqlite3Fts3SegReaderNew(p, iAge,
113318      sqlite3_column_int64(pStmt, 1),
113319      sqlite3_column_int64(pStmt, 2),
113320      sqlite3_column_int64(pStmt, 3),
113321      sqlite3_column_blob(pStmt, 4),
113322      sqlite3_column_bytes(pStmt, 4),
113323      ppReader
113324  );
113325}
113326
113327/*
113328** Compare the entries pointed to by two Fts3SegReader structures.
113329** Comparison is as follows:
113330**
113331**   1) EOF is greater than not EOF.
113332**
113333**   2) The current terms (if any) are compared using memcmp(). If one
113334**      term is a prefix of another, the longer term is considered the
113335**      larger.
113336**
113337**   3) By segment age. An older segment is considered larger.
113338*/
113339static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
113340  int rc;
113341  if( pLhs->aNode && pRhs->aNode ){
113342    int rc2 = pLhs->nTerm - pRhs->nTerm;
113343    if( rc2<0 ){
113344      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
113345    }else{
113346      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
113347    }
113348    if( rc==0 ){
113349      rc = rc2;
113350    }
113351  }else{
113352    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
113353  }
113354  if( rc==0 ){
113355    rc = pRhs->iIdx - pLhs->iIdx;
113356  }
113357  assert( rc!=0 );
113358  return rc;
113359}
113360
113361/*
113362** A different comparison function for SegReader structures. In this
113363** version, it is assumed that each SegReader points to an entry in
113364** a doclist for identical terms. Comparison is made as follows:
113365**
113366**   1) EOF (end of doclist in this case) is greater than not EOF.
113367**
113368**   2) By current docid.
113369**
113370**   3) By segment age. An older segment is considered larger.
113371*/
113372static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
113373  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
113374  if( rc==0 ){
113375    if( pLhs->iDocid==pRhs->iDocid ){
113376      rc = pRhs->iIdx - pLhs->iIdx;
113377    }else{
113378      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
113379    }
113380  }
113381  assert( pLhs->aNode && pRhs->aNode );
113382  return rc;
113383}
113384
113385/*
113386** Compare the term that the Fts3SegReader object passed as the first argument
113387** points to with the term specified by arguments zTerm and nTerm.
113388**
113389** If the pSeg iterator is already at EOF, return 0. Otherwise, return
113390** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
113391** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
113392*/
113393static int fts3SegReaderTermCmp(
113394  Fts3SegReader *pSeg,            /* Segment reader object */
113395  const char *zTerm,              /* Term to compare to */
113396  int nTerm                       /* Size of term zTerm in bytes */
113397){
113398  int res = 0;
113399  if( pSeg->aNode ){
113400    if( pSeg->nTerm>nTerm ){
113401      res = memcmp(pSeg->zTerm, zTerm, nTerm);
113402    }else{
113403      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
113404    }
113405    if( res==0 ){
113406      res = pSeg->nTerm-nTerm;
113407    }
113408  }
113409  return res;
113410}
113411
113412/*
113413** Argument apSegment is an array of nSegment elements. It is known that
113414** the final (nSegment-nSuspect) members are already in sorted order
113415** (according to the comparison function provided). This function shuffles
113416** the array around until all entries are in sorted order.
113417*/
113418static void fts3SegReaderSort(
113419  Fts3SegReader **apSegment,                     /* Array to sort entries of */
113420  int nSegment,                                  /* Size of apSegment array */
113421  int nSuspect,                                  /* Unsorted entry count */
113422  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
113423){
113424  int i;                          /* Iterator variable */
113425
113426  assert( nSuspect<=nSegment );
113427
113428  if( nSuspect==nSegment ) nSuspect--;
113429  for(i=nSuspect-1; i>=0; i--){
113430    int j;
113431    for(j=i; j<(nSegment-1); j++){
113432      Fts3SegReader *pTmp;
113433      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
113434      pTmp = apSegment[j+1];
113435      apSegment[j+1] = apSegment[j];
113436      apSegment[j] = pTmp;
113437    }
113438  }
113439
113440#ifndef NDEBUG
113441  /* Check that the list really is sorted now. */
113442  for(i=0; i<(nSuspect-1); i++){
113443    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
113444  }
113445#endif
113446}
113447
113448/*
113449** Insert a record into the %_segments table.
113450*/
113451static int fts3WriteSegment(
113452  Fts3Table *p,                   /* Virtual table handle */
113453  sqlite3_int64 iBlock,           /* Block id for new block */
113454  char *z,                        /* Pointer to buffer containing block data */
113455  int n                           /* Size of buffer z in bytes */
113456){
113457  sqlite3_stmt *pStmt;
113458  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
113459  if( rc==SQLITE_OK ){
113460    sqlite3_bind_int64(pStmt, 1, iBlock);
113461    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
113462    sqlite3_step(pStmt);
113463    rc = sqlite3_reset(pStmt);
113464  }
113465  return rc;
113466}
113467
113468/*
113469** Insert a record into the %_segdir table.
113470*/
113471static int fts3WriteSegdir(
113472  Fts3Table *p,                   /* Virtual table handle */
113473  int iLevel,                     /* Value for "level" field */
113474  int iIdx,                       /* Value for "idx" field */
113475  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
113476  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
113477  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
113478  char *zRoot,                    /* Blob value for "root" field */
113479  int nRoot                       /* Number of bytes in buffer zRoot */
113480){
113481  sqlite3_stmt *pStmt;
113482  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
113483  if( rc==SQLITE_OK ){
113484    sqlite3_bind_int(pStmt, 1, iLevel);
113485    sqlite3_bind_int(pStmt, 2, iIdx);
113486    sqlite3_bind_int64(pStmt, 3, iStartBlock);
113487    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
113488    sqlite3_bind_int64(pStmt, 5, iEndBlock);
113489    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
113490    sqlite3_step(pStmt);
113491    rc = sqlite3_reset(pStmt);
113492  }
113493  return rc;
113494}
113495
113496/*
113497** Return the size of the common prefix (if any) shared by zPrev and
113498** zNext, in bytes. For example,
113499**
113500**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
113501**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
113502**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
113503*/
113504static int fts3PrefixCompress(
113505  const char *zPrev,              /* Buffer containing previous term */
113506  int nPrev,                      /* Size of buffer zPrev in bytes */
113507  const char *zNext,              /* Buffer containing next term */
113508  int nNext                       /* Size of buffer zNext in bytes */
113509){
113510  int n;
113511  UNUSED_PARAMETER(nNext);
113512  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
113513  return n;
113514}
113515
113516/*
113517** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
113518** (according to memcmp) than the previous term.
113519*/
113520static int fts3NodeAddTerm(
113521  Fts3Table *p,               /* Virtual table handle */
113522  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
113523  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
113524  const char *zTerm,              /* Pointer to buffer containing term */
113525  int nTerm                       /* Size of term in bytes */
113526){
113527  SegmentNode *pTree = *ppTree;
113528  int rc;
113529  SegmentNode *pNew;
113530
113531  /* First try to append the term to the current node. Return early if
113532  ** this is possible.
113533  */
113534  if( pTree ){
113535    int nData = pTree->nData;     /* Current size of node in bytes */
113536    int nReq = nData;             /* Required space after adding zTerm */
113537    int nPrefix;                  /* Number of bytes of prefix compression */
113538    int nSuffix;                  /* Suffix length */
113539
113540    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
113541    nSuffix = nTerm-nPrefix;
113542
113543    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
113544    if( nReq<=p->nNodeSize || !pTree->zTerm ){
113545
113546      if( nReq>p->nNodeSize ){
113547        /* An unusual case: this is the first term to be added to the node
113548        ** and the static node buffer (p->nNodeSize bytes) is not large
113549        ** enough. Use a separately malloced buffer instead This wastes
113550        ** p->nNodeSize bytes, but since this scenario only comes about when
113551        ** the database contain two terms that share a prefix of almost 2KB,
113552        ** this is not expected to be a serious problem.
113553        */
113554        assert( pTree->aData==(char *)&pTree[1] );
113555        pTree->aData = (char *)sqlite3_malloc(nReq);
113556        if( !pTree->aData ){
113557          return SQLITE_NOMEM;
113558        }
113559      }
113560
113561      if( pTree->zTerm ){
113562        /* There is no prefix-length field for first term in a node */
113563        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
113564      }
113565
113566      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
113567      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
113568      pTree->nData = nData + nSuffix;
113569      pTree->nEntry++;
113570
113571      if( isCopyTerm ){
113572        if( pTree->nMalloc<nTerm ){
113573          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
113574          if( !zNew ){
113575            return SQLITE_NOMEM;
113576          }
113577          pTree->nMalloc = nTerm*2;
113578          pTree->zMalloc = zNew;
113579        }
113580        pTree->zTerm = pTree->zMalloc;
113581        memcpy(pTree->zTerm, zTerm, nTerm);
113582        pTree->nTerm = nTerm;
113583      }else{
113584        pTree->zTerm = (char *)zTerm;
113585        pTree->nTerm = nTerm;
113586      }
113587      return SQLITE_OK;
113588    }
113589  }
113590
113591  /* If control flows to here, it was not possible to append zTerm to the
113592  ** current node. Create a new node (a right-sibling of the current node).
113593  ** If this is the first node in the tree, the term is added to it.
113594  **
113595  ** Otherwise, the term is not added to the new node, it is left empty for
113596  ** now. Instead, the term is inserted into the parent of pTree. If pTree
113597  ** has no parent, one is created here.
113598  */
113599  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
113600  if( !pNew ){
113601    return SQLITE_NOMEM;
113602  }
113603  memset(pNew, 0, sizeof(SegmentNode));
113604  pNew->nData = 1 + FTS3_VARINT_MAX;
113605  pNew->aData = (char *)&pNew[1];
113606
113607  if( pTree ){
113608    SegmentNode *pParent = pTree->pParent;
113609    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
113610    if( pTree->pParent==0 ){
113611      pTree->pParent = pParent;
113612    }
113613    pTree->pRight = pNew;
113614    pNew->pLeftmost = pTree->pLeftmost;
113615    pNew->pParent = pParent;
113616    pNew->zMalloc = pTree->zMalloc;
113617    pNew->nMalloc = pTree->nMalloc;
113618    pTree->zMalloc = 0;
113619  }else{
113620    pNew->pLeftmost = pNew;
113621    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
113622  }
113623
113624  *ppTree = pNew;
113625  return rc;
113626}
113627
113628/*
113629** Helper function for fts3NodeWrite().
113630*/
113631static int fts3TreeFinishNode(
113632  SegmentNode *pTree,
113633  int iHeight,
113634  sqlite3_int64 iLeftChild
113635){
113636  int nStart;
113637  assert( iHeight>=1 && iHeight<128 );
113638  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
113639  pTree->aData[nStart] = (char)iHeight;
113640  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
113641  return nStart;
113642}
113643
113644/*
113645** Write the buffer for the segment node pTree and all of its peers to the
113646** database. Then call this function recursively to write the parent of
113647** pTree and its peers to the database.
113648**
113649** Except, if pTree is a root node, do not write it to the database. Instead,
113650** set output variables *paRoot and *pnRoot to contain the root node.
113651**
113652** If successful, SQLITE_OK is returned and output variable *piLast is
113653** set to the largest blockid written to the database (or zero if no
113654** blocks were written to the db). Otherwise, an SQLite error code is
113655** returned.
113656*/
113657static int fts3NodeWrite(
113658  Fts3Table *p,                   /* Virtual table handle */
113659  SegmentNode *pTree,             /* SegmentNode handle */
113660  int iHeight,                    /* Height of this node in tree */
113661  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
113662  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
113663  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
113664  char **paRoot,                  /* OUT: Data for root node */
113665  int *pnRoot                     /* OUT: Size of root node in bytes */
113666){
113667  int rc = SQLITE_OK;
113668
113669  if( !pTree->pParent ){
113670    /* Root node of the tree. */
113671    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
113672    *piLast = iFree-1;
113673    *pnRoot = pTree->nData - nStart;
113674    *paRoot = &pTree->aData[nStart];
113675  }else{
113676    SegmentNode *pIter;
113677    sqlite3_int64 iNextFree = iFree;
113678    sqlite3_int64 iNextLeaf = iLeaf;
113679    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
113680      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
113681      int nWrite = pIter->nData - nStart;
113682
113683      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
113684      iNextFree++;
113685      iNextLeaf += (pIter->nEntry+1);
113686    }
113687    if( rc==SQLITE_OK ){
113688      assert( iNextLeaf==iFree );
113689      rc = fts3NodeWrite(
113690          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
113691      );
113692    }
113693  }
113694
113695  return rc;
113696}
113697
113698/*
113699** Free all memory allocations associated with the tree pTree.
113700*/
113701static void fts3NodeFree(SegmentNode *pTree){
113702  if( pTree ){
113703    SegmentNode *p = pTree->pLeftmost;
113704    fts3NodeFree(p->pParent);
113705    while( p ){
113706      SegmentNode *pRight = p->pRight;
113707      if( p->aData!=(char *)&p[1] ){
113708        sqlite3_free(p->aData);
113709      }
113710      assert( pRight==0 || p->zMalloc==0 );
113711      sqlite3_free(p->zMalloc);
113712      sqlite3_free(p);
113713      p = pRight;
113714    }
113715  }
113716}
113717
113718/*
113719** Add a term to the segment being constructed by the SegmentWriter object
113720** *ppWriter. When adding the first term to a segment, *ppWriter should
113721** be passed NULL. This function will allocate a new SegmentWriter object
113722** and return it via the input/output variable *ppWriter in this case.
113723**
113724** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
113725*/
113726static int fts3SegWriterAdd(
113727  Fts3Table *p,                   /* Virtual table handle */
113728  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
113729  int isCopyTerm,                 /* True if buffer zTerm must be copied */
113730  const char *zTerm,              /* Pointer to buffer containing term */
113731  int nTerm,                      /* Size of term in bytes */
113732  const char *aDoclist,           /* Pointer to buffer containing doclist */
113733  int nDoclist                    /* Size of doclist in bytes */
113734){
113735  int nPrefix;                    /* Size of term prefix in bytes */
113736  int nSuffix;                    /* Size of term suffix in bytes */
113737  int nReq;                       /* Number of bytes required on leaf page */
113738  int nData;
113739  SegmentWriter *pWriter = *ppWriter;
113740
113741  if( !pWriter ){
113742    int rc;
113743    sqlite3_stmt *pStmt;
113744
113745    /* Allocate the SegmentWriter structure */
113746    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
113747    if( !pWriter ) return SQLITE_NOMEM;
113748    memset(pWriter, 0, sizeof(SegmentWriter));
113749    *ppWriter = pWriter;
113750
113751    /* Allocate a buffer in which to accumulate data */
113752    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
113753    if( !pWriter->aData ) return SQLITE_NOMEM;
113754    pWriter->nSize = p->nNodeSize;
113755
113756    /* Find the next free blockid in the %_segments table */
113757    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
113758    if( rc!=SQLITE_OK ) return rc;
113759    if( SQLITE_ROW==sqlite3_step(pStmt) ){
113760      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
113761      pWriter->iFirst = pWriter->iFree;
113762    }
113763    rc = sqlite3_reset(pStmt);
113764    if( rc!=SQLITE_OK ) return rc;
113765  }
113766  nData = pWriter->nData;
113767
113768  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
113769  nSuffix = nTerm-nPrefix;
113770
113771  /* Figure out how many bytes are required by this new entry */
113772  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
113773    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
113774    nSuffix +                               /* Term suffix */
113775    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
113776    nDoclist;                               /* Doclist data */
113777
113778  if( nData>0 && nData+nReq>p->nNodeSize ){
113779    int rc;
113780
113781    /* The current leaf node is full. Write it out to the database. */
113782    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
113783    if( rc!=SQLITE_OK ) return rc;
113784
113785    /* Add the current term to the interior node tree. The term added to
113786    ** the interior tree must:
113787    **
113788    **   a) be greater than the largest term on the leaf node just written
113789    **      to the database (still available in pWriter->zTerm), and
113790    **
113791    **   b) be less than or equal to the term about to be added to the new
113792    **      leaf node (zTerm/nTerm).
113793    **
113794    ** In other words, it must be the prefix of zTerm 1 byte longer than
113795    ** the common prefix (if any) of zTerm and pWriter->zTerm.
113796    */
113797    assert( nPrefix<nTerm );
113798    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
113799    if( rc!=SQLITE_OK ) return rc;
113800
113801    nData = 0;
113802    pWriter->nTerm = 0;
113803
113804    nPrefix = 0;
113805    nSuffix = nTerm;
113806    nReq = 1 +                              /* varint containing prefix size */
113807      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
113808      nTerm +                               /* Term suffix */
113809      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
113810      nDoclist;                             /* Doclist data */
113811  }
113812
113813  /* If the buffer currently allocated is too small for this entry, realloc
113814  ** the buffer to make it large enough.
113815  */
113816  if( nReq>pWriter->nSize ){
113817    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
113818    if( !aNew ) return SQLITE_NOMEM;
113819    pWriter->aData = aNew;
113820    pWriter->nSize = nReq;
113821  }
113822  assert( nData+nReq<=pWriter->nSize );
113823
113824  /* Append the prefix-compressed term and doclist to the buffer. */
113825  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
113826  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
113827  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
113828  nData += nSuffix;
113829  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
113830  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
113831  pWriter->nData = nData + nDoclist;
113832
113833  /* Save the current term so that it can be used to prefix-compress the next.
113834  ** If the isCopyTerm parameter is true, then the buffer pointed to by
113835  ** zTerm is transient, so take a copy of the term data. Otherwise, just
113836  ** store a copy of the pointer.
113837  */
113838  if( isCopyTerm ){
113839    if( nTerm>pWriter->nMalloc ){
113840      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
113841      if( !zNew ){
113842        return SQLITE_NOMEM;
113843      }
113844      pWriter->nMalloc = nTerm*2;
113845      pWriter->zMalloc = zNew;
113846      pWriter->zTerm = zNew;
113847    }
113848    assert( pWriter->zTerm==pWriter->zMalloc );
113849    memcpy(pWriter->zTerm, zTerm, nTerm);
113850  }else{
113851    pWriter->zTerm = (char *)zTerm;
113852  }
113853  pWriter->nTerm = nTerm;
113854
113855  return SQLITE_OK;
113856}
113857
113858/*
113859** Flush all data associated with the SegmentWriter object pWriter to the
113860** database. This function must be called after all terms have been added
113861** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
113862** returned. Otherwise, an SQLite error code.
113863*/
113864static int fts3SegWriterFlush(
113865  Fts3Table *p,                   /* Virtual table handle */
113866  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
113867  int iLevel,                     /* Value for 'level' column of %_segdir */
113868  int iIdx                        /* Value for 'idx' column of %_segdir */
113869){
113870  int rc;                         /* Return code */
113871  if( pWriter->pTree ){
113872    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
113873    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
113874    char *zRoot = NULL;           /* Pointer to buffer containing root node */
113875    int nRoot = 0;                /* Size of buffer zRoot */
113876
113877    iLastLeaf = pWriter->iFree;
113878    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
113879    if( rc==SQLITE_OK ){
113880      rc = fts3NodeWrite(p, pWriter->pTree, 1,
113881          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
113882    }
113883    if( rc==SQLITE_OK ){
113884      rc = fts3WriteSegdir(
113885          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
113886    }
113887  }else{
113888    /* The entire tree fits on the root node. Write it to the segdir table. */
113889    rc = fts3WriteSegdir(
113890        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
113891  }
113892  return rc;
113893}
113894
113895/*
113896** Release all memory held by the SegmentWriter object passed as the
113897** first argument.
113898*/
113899static void fts3SegWriterFree(SegmentWriter *pWriter){
113900  if( pWriter ){
113901    sqlite3_free(pWriter->aData);
113902    sqlite3_free(pWriter->zMalloc);
113903    fts3NodeFree(pWriter->pTree);
113904    sqlite3_free(pWriter);
113905  }
113906}
113907
113908/*
113909** The first value in the apVal[] array is assumed to contain an integer.
113910** This function tests if there exist any documents with docid values that
113911** are different from that integer. i.e. if deleting the document with docid
113912** apVal[0] would mean the FTS3 table were empty.
113913**
113914** If successful, *pisEmpty is set to true if the table is empty except for
113915** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
113916** error occurs, an SQLite error code is returned.
113917*/
113918static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
113919  sqlite3_stmt *pStmt;
113920  int rc;
113921  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
113922  if( rc==SQLITE_OK ){
113923    if( SQLITE_ROW==sqlite3_step(pStmt) ){
113924      *pisEmpty = sqlite3_column_int(pStmt, 0);
113925    }
113926    rc = sqlite3_reset(pStmt);
113927  }
113928  return rc;
113929}
113930
113931/*
113932** Set *pnSegment to the number of segments of level iLevel in the database.
113933**
113934** Return SQLITE_OK if successful, or an SQLite error code if not.
113935*/
113936static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
113937  sqlite3_stmt *pStmt;
113938  int rc;
113939
113940  assert( iLevel>=0 );
113941  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
113942  if( rc!=SQLITE_OK ) return rc;
113943  sqlite3_bind_int(pStmt, 1, iLevel);
113944  if( SQLITE_ROW==sqlite3_step(pStmt) ){
113945    *pnSegment = sqlite3_column_int(pStmt, 0);
113946  }
113947  return sqlite3_reset(pStmt);
113948}
113949
113950/*
113951** Set *pnSegment to the total number of segments in the database. Set
113952** *pnMax to the largest segment level in the database (segment levels
113953** are stored in the 'level' column of the %_segdir table).
113954**
113955** Return SQLITE_OK if successful, or an SQLite error code if not.
113956*/
113957static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
113958  sqlite3_stmt *pStmt;
113959  int rc;
113960
113961  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
113962  if( rc!=SQLITE_OK ) return rc;
113963  if( SQLITE_ROW==sqlite3_step(pStmt) ){
113964    *pnSegment = sqlite3_column_int(pStmt, 0);
113965    *pnMax = sqlite3_column_int(pStmt, 1);
113966  }
113967  return sqlite3_reset(pStmt);
113968}
113969
113970/*
113971** This function is used after merging multiple segments into a single large
113972** segment to delete the old, now redundant, segment b-trees. Specifically,
113973** it:
113974**
113975**   1) Deletes all %_segments entries for the segments associated with
113976**      each of the SegReader objects in the array passed as the third
113977**      argument, and
113978**
113979**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
113980**      entries regardless of level if (iLevel<0).
113981**
113982** SQLITE_OK is returned if successful, otherwise an SQLite error code.
113983*/
113984static int fts3DeleteSegdir(
113985  Fts3Table *p,                   /* Virtual table handle */
113986  int iLevel,                     /* Level of %_segdir entries to delete */
113987  Fts3SegReader **apSegment,      /* Array of SegReader objects */
113988  int nReader                     /* Size of array apSegment */
113989){
113990  int rc;                         /* Return Code */
113991  int i;                          /* Iterator variable */
113992  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
113993
113994  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
113995  for(i=0; rc==SQLITE_OK && i<nReader; i++){
113996    Fts3SegReader *pSegment = apSegment[i];
113997    if( pSegment->iStartBlock ){
113998      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
113999      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
114000      sqlite3_step(pDelete);
114001      rc = sqlite3_reset(pDelete);
114002    }
114003  }
114004  if( rc!=SQLITE_OK ){
114005    return rc;
114006  }
114007
114008  if( iLevel>=0 ){
114009    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
114010    if( rc==SQLITE_OK ){
114011      sqlite3_bind_int(pDelete, 1, iLevel);
114012      sqlite3_step(pDelete);
114013      rc = sqlite3_reset(pDelete);
114014    }
114015  }else{
114016    fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
114017  }
114018
114019  return rc;
114020}
114021
114022/*
114023** When this function is called, buffer *ppList (size *pnList bytes) contains
114024** a position list that may (or may not) feature multiple columns. This
114025** function adjusts the pointer *ppList and the length *pnList so that they
114026** identify the subset of the position list that corresponds to column iCol.
114027**
114028** If there are no entries in the input position list for column iCol, then
114029** *pnList is set to zero before returning.
114030*/
114031static void fts3ColumnFilter(
114032  int iCol,                       /* Column to filter on */
114033  char **ppList,                  /* IN/OUT: Pointer to position list */
114034  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
114035){
114036  char *pList = *ppList;
114037  int nList = *pnList;
114038  char *pEnd = &pList[nList];
114039  int iCurrent = 0;
114040  char *p = pList;
114041
114042  assert( iCol>=0 );
114043  while( 1 ){
114044    char c = 0;
114045    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
114046
114047    if( iCol==iCurrent ){
114048      nList = (int)(p - pList);
114049      break;
114050    }
114051
114052    nList -= (int)(p - pList);
114053    pList = p;
114054    if( nList==0 ){
114055      break;
114056    }
114057    p = &pList[1];
114058    p += sqlite3Fts3GetVarint32(p, &iCurrent);
114059  }
114060
114061  *ppList = pList;
114062  *pnList = nList;
114063}
114064
114065/*
114066** sqlite3Fts3SegReaderIterate() callback used when merging multiple
114067** segments to create a single, larger segment.
114068*/
114069static int fts3MergeCallback(
114070  Fts3Table *p,                   /* FTS3 Virtual table handle */
114071  void *pContext,                 /* Pointer to SegmentWriter* to write with */
114072  char *zTerm,                    /* Term to write to the db */
114073  int nTerm,                      /* Number of bytes in zTerm */
114074  char *aDoclist,                 /* Doclist associated with zTerm */
114075  int nDoclist                    /* Number of bytes in doclist */
114076){
114077  SegmentWriter **ppW = (SegmentWriter **)pContext;
114078  return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
114079}
114080
114081/*
114082** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
114083** of the pending-terms hash table to the database.
114084*/
114085static int fts3FlushCallback(
114086  Fts3Table *p,                   /* FTS3 Virtual table handle */
114087  void *pContext,                 /* Pointer to SegmentWriter* to write with */
114088  char *zTerm,                    /* Term to write to the db */
114089  int nTerm,                      /* Number of bytes in zTerm */
114090  char *aDoclist,                 /* Doclist associated with zTerm */
114091  int nDoclist                    /* Number of bytes in doclist */
114092){
114093  SegmentWriter **ppW = (SegmentWriter **)pContext;
114094  return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
114095}
114096
114097/*
114098** This function is used to iterate through a contiguous set of terms
114099** stored in the full-text index. It merges data contained in one or
114100** more segments to support this.
114101**
114102** The second argument is passed an array of pointers to SegReader objects
114103** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
114104** of terms selected by each SegReader. If a single term is present in
114105** more than one segment, the associated doclists are merged. For each
114106** term and (possibly merged) doclist in the merged range, the callback
114107** function xFunc is invoked with its arguments set as follows.
114108**
114109**   arg 0: Copy of 'p' parameter passed to this function
114110**   arg 1: Copy of 'pContext' parameter passed to this function
114111**   arg 2: Pointer to buffer containing term
114112**   arg 3: Size of arg 2 buffer in bytes
114113**   arg 4: Pointer to buffer containing doclist
114114**   arg 5: Size of arg 2 buffer in bytes
114115**
114116** The 4th argument to this function is a pointer to a structure of type
114117** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
114118** further restrict the range of terms that callbacks are made for and
114119** modify the behaviour of this function. See comments above structure
114120** definition for details.
114121*/
114122SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
114123  Fts3Table *p,                   /* Virtual table handle */
114124  Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
114125  int nSegment,                   /* Size of apSegment array */
114126  Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
114127  int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
114128  void *pContext                  /* Callback context (2nd argument) */
114129){
114130  int i;                          /* Iterator variable */
114131  char *aBuffer = 0;              /* Buffer to merge doclists in */
114132  int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
114133  int rc = SQLITE_OK;             /* Return code */
114134
114135  int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
114136  int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
114137  int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
114138  int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
114139
114140  /* If there are zero segments, this function is a no-op. This scenario
114141  ** comes about only when reading from an empty database.
114142  */
114143  if( nSegment==0 ) goto finished;
114144
114145  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
114146  ** for, then advance each segment iterator until it points to a term of
114147  ** equal or greater value than the specified term. This prevents many
114148  ** unnecessary merge/sort operations for the case where single segment
114149  ** b-tree leaf nodes contain more than one term.
114150  */
114151  if( pFilter->zTerm ){
114152    int nTerm = pFilter->nTerm;
114153    const char *zTerm = pFilter->zTerm;
114154    for(i=0; i<nSegment; i++){
114155      Fts3SegReader *pSeg = apSegment[i];
114156      while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
114157        rc = fts3SegReaderNext(pSeg);
114158        if( rc!=SQLITE_OK ) goto finished; }
114159    }
114160  }
114161
114162  fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
114163  while( apSegment[0]->aNode ){
114164    int nTerm = apSegment[0]->nTerm;
114165    char *zTerm = apSegment[0]->zTerm;
114166    int nMerge = 1;
114167
114168    /* If this is a prefix-search, and if the term that apSegment[0] points
114169    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
114170    ** required callbacks have been made. In this case exit early.
114171    **
114172    ** Similarly, if this is a search for an exact match, and the first term
114173    ** of segment apSegment[0] is not a match, exit early.
114174    */
114175    if( pFilter->zTerm ){
114176      if( nTerm<pFilter->nTerm
114177       || (!isPrefix && nTerm>pFilter->nTerm)
114178       || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
114179    ){
114180        goto finished;
114181      }
114182    }
114183
114184    while( nMerge<nSegment
114185        && apSegment[nMerge]->aNode
114186        && apSegment[nMerge]->nTerm==nTerm
114187        && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
114188    ){
114189      nMerge++;
114190    }
114191
114192    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
114193    if( nMerge==1 && !isIgnoreEmpty ){
114194      Fts3SegReader *p0 = apSegment[0];
114195      rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
114196      if( rc!=SQLITE_OK ) goto finished;
114197    }else{
114198      int nDoclist = 0;           /* Size of doclist */
114199      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
114200
114201      /* The current term of the first nMerge entries in the array
114202      ** of Fts3SegReader objects is the same. The doclists must be merged
114203      ** and a single term added to the new segment.
114204      */
114205      for(i=0; i<nMerge; i++){
114206        fts3SegReaderFirstDocid(apSegment[i]);
114207      }
114208      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
114209      while( apSegment[0]->pOffsetList ){
114210        int j;                    /* Number of segments that share a docid */
114211        char *pList;
114212        int nList;
114213        int nByte;
114214        sqlite3_int64 iDocid = apSegment[0]->iDocid;
114215        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
114216        j = 1;
114217        while( j<nMerge
114218            && apSegment[j]->pOffsetList
114219            && apSegment[j]->iDocid==iDocid
114220        ){
114221          fts3SegReaderNextDocid(apSegment[j], 0, 0);
114222          j++;
114223        }
114224
114225        if( isColFilter ){
114226          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
114227        }
114228
114229        if( !isIgnoreEmpty || nList>0 ){
114230          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
114231          if( nDoclist+nByte>nAlloc ){
114232            char *aNew;
114233            nAlloc = nDoclist+nByte*2;
114234            aNew = sqlite3_realloc(aBuffer, nAlloc);
114235            if( !aNew ){
114236              rc = SQLITE_NOMEM;
114237              goto finished;
114238            }
114239            aBuffer = aNew;
114240          }
114241          nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
114242          iPrev = iDocid;
114243          if( isRequirePos ){
114244            memcpy(&aBuffer[nDoclist], pList, nList);
114245            nDoclist += nList;
114246            aBuffer[nDoclist++] = '\0';
114247          }
114248        }
114249
114250        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
114251      }
114252
114253      if( nDoclist>0 ){
114254        rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
114255        if( rc!=SQLITE_OK ) goto finished;
114256      }
114257    }
114258
114259    /* If there is a term specified to filter on, and this is not a prefix
114260    ** search, return now. The callback that corresponds to the required
114261    ** term (if such a term exists in the index) has already been made.
114262    */
114263    if( pFilter->zTerm && !isPrefix ){
114264      goto finished;
114265    }
114266
114267    for(i=0; i<nMerge; i++){
114268      rc = fts3SegReaderNext(apSegment[i]);
114269      if( rc!=SQLITE_OK ) goto finished;
114270    }
114271    fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
114272  }
114273
114274 finished:
114275  sqlite3_free(aBuffer);
114276  return rc;
114277}
114278
114279/*
114280** Merge all level iLevel segments in the database into a single
114281** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
114282** single segment with a level equal to the numerically largest level
114283** currently present in the database.
114284**
114285** If this function is called with iLevel<0, but there is only one
114286** segment in the database, SQLITE_DONE is returned immediately.
114287** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
114288** an SQLite error code is returned.
114289*/
114290static int fts3SegmentMerge(Fts3Table *p, int iLevel){
114291  int i;                          /* Iterator variable */
114292  int rc;                         /* Return code */
114293  int iIdx;                       /* Index of new segment */
114294  int iNewLevel;                  /* Level to create new segment at */
114295  sqlite3_stmt *pStmt = 0;
114296  SegmentWriter *pWriter = 0;
114297  int nSegment = 0;               /* Number of segments being merged */
114298  Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
114299  Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
114300  Fts3SegFilter filter;           /* Segment term filter condition */
114301
114302  if( iLevel<0 ){
114303    /* This call is to merge all segments in the database to a single
114304    ** segment. The level of the new segment is equal to the the numerically
114305    ** greatest segment level currently present in the database. The index
114306    ** of the new segment is always 0.
114307    */
114308    iIdx = 0;
114309    rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
114310    if( rc!=SQLITE_OK ) goto finished;
114311    rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
114312    if( rc!=SQLITE_OK ) goto finished;
114313    nSegment += (pPending!=0);
114314    if( nSegment<=1 ){
114315      return SQLITE_DONE;
114316    }
114317  }else{
114318    /* This call is to merge all segments at level iLevel. Find the next
114319    ** available segment index at level iLevel+1. The call to
114320    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
114321    ** a single iLevel+2 segment if necessary.
114322    */
114323    iNewLevel = iLevel+1;
114324    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
114325    if( rc!=SQLITE_OK ) goto finished;
114326    rc = fts3SegmentCount(p, iLevel, &nSegment);
114327    if( rc!=SQLITE_OK ) goto finished;
114328  }
114329  assert( nSegment>0 );
114330  assert( iNewLevel>=0 );
114331
114332  /* Allocate space for an array of pointers to segment iterators. */
114333  apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
114334  if( !apSegment ){
114335    rc = SQLITE_NOMEM;
114336    goto finished;
114337  }
114338  memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
114339
114340  /* Allocate a Fts3SegReader structure for each segment being merged. A
114341  ** Fts3SegReader stores the state data required to iterate through all
114342  ** entries on all leaves of a single segment.
114343  */
114344  assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
114345  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
114346  if( rc!=SQLITE_OK ) goto finished;
114347  sqlite3_bind_int(pStmt, 1, iLevel);
114348  for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
114349    rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
114350    if( rc!=SQLITE_OK ){
114351      goto finished;
114352    }
114353  }
114354  rc = sqlite3_reset(pStmt);
114355  if( pPending ){
114356    apSegment[i] = pPending;
114357    pPending = 0;
114358  }
114359  pStmt = 0;
114360  if( rc!=SQLITE_OK ) goto finished;
114361
114362  memset(&filter, 0, sizeof(Fts3SegFilter));
114363  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
114364  filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
114365  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
114366      &filter, fts3MergeCallback, (void *)&pWriter
114367  );
114368  if( rc!=SQLITE_OK ) goto finished;
114369
114370  rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
114371  if( rc==SQLITE_OK ){
114372    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
114373  }
114374
114375 finished:
114376  fts3SegWriterFree(pWriter);
114377  if( apSegment ){
114378    for(i=0; i<nSegment; i++){
114379      sqlite3Fts3SegReaderFree(p, apSegment[i]);
114380    }
114381    sqlite3_free(apSegment);
114382  }
114383  sqlite3Fts3SegReaderFree(p, pPending);
114384  sqlite3_reset(pStmt);
114385  return rc;
114386}
114387
114388
114389/*
114390** Flush the contents of pendingTerms to a level 0 segment.
114391*/
114392SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
114393  int rc;                         /* Return Code */
114394  int idx;                        /* Index of new segment created */
114395  SegmentWriter *pWriter = 0;     /* Used to write the segment */
114396  Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
114397
114398  /* Allocate a SegReader object to iterate through the contents of the
114399  ** pending-terms table. If an error occurs, or if there are no terms
114400  ** in the pending-terms table, return immediately.
114401  */
114402  rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
114403  if( rc!=SQLITE_OK || pReader==0 ){
114404    return rc;
114405  }
114406
114407  /* Determine the next index at level 0. If level 0 is already full, this
114408  ** call may merge all existing level 0 segments into a single level 1
114409  ** segment.
114410  */
114411  rc = fts3AllocateSegdirIdx(p, 0, &idx);
114412
114413  /* If no errors have occured, iterate through the contents of the
114414  ** pending-terms hash table using the Fts3SegReader iterator. The callback
114415  ** writes each term (along with its doclist) to the database via the
114416  ** SegmentWriter handle pWriter.
114417  */
114418  if( rc==SQLITE_OK ){
114419    void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
114420    Fts3SegFilter f;              /* SegReaderIterate() parameters */
114421
114422    memset(&f, 0, sizeof(Fts3SegFilter));
114423    f.flags = FTS3_SEGMENT_REQUIRE_POS;
114424    rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
114425  }
114426  assert( pWriter || rc!=SQLITE_OK );
114427
114428  /* If no errors have occured, flush the SegmentWriter object to the
114429  ** database. Then delete the SegmentWriter and Fts3SegReader objects
114430  ** allocated by this function.
114431  */
114432  if( rc==SQLITE_OK ){
114433    rc = fts3SegWriterFlush(p, pWriter, 0, idx);
114434  }
114435  fts3SegWriterFree(pWriter);
114436  sqlite3Fts3SegReaderFree(p, pReader);
114437
114438  if( rc==SQLITE_OK ){
114439    sqlite3Fts3PendingTermsClear(p);
114440  }
114441  return rc;
114442}
114443
114444/*
114445** Encode N integers as varints into a blob.
114446*/
114447static void fts3EncodeIntArray(
114448  int N,             /* The number of integers to encode */
114449  u32 *a,            /* The integer values */
114450  char *zBuf,        /* Write the BLOB here */
114451  int *pNBuf         /* Write number of bytes if zBuf[] used here */
114452){
114453  int i, j;
114454  for(i=j=0; i<N; i++){
114455    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
114456  }
114457  *pNBuf = j;
114458}
114459
114460/*
114461** Decode a blob of varints into N integers
114462*/
114463static void fts3DecodeIntArray(
114464  int N,             /* The number of integers to decode */
114465  u32 *a,            /* Write the integer values */
114466  const char *zBuf,  /* The BLOB containing the varints */
114467  int nBuf           /* size of the BLOB */
114468){
114469  int i, j;
114470  UNUSED_PARAMETER(nBuf);
114471  for(i=j=0; i<N; i++){
114472    sqlite3_int64 x;
114473    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
114474    assert(j<=nBuf);
114475    a[i] = (u32)(x & 0xffffffff);
114476  }
114477}
114478
114479/*
114480** Fill in the document size auxiliary information for the matchinfo
114481** structure.  The auxiliary information is:
114482**
114483**    N     Total number of documents in the full-text index
114484**    a0    Average length of column 0 over the whole index
114485**    n0    Length of column 0 on the matching row
114486**    ...
114487**    aM    Average length of column M over the whole index
114488**    nM    Length of column M on the matching row
114489**
114490** The fts3MatchinfoDocsizeLocal() routine fills in the nX values.
114491** The fts3MatchinfoDocsizeGlobal() routine fills in N and the aX values.
114492*/
114493SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor *pCur, u32 *a){
114494  const char *pBlob;       /* The BLOB holding %_docsize info */
114495  int nBlob;               /* Size of the BLOB */
114496  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
114497  int i, j;                /* Loop counters */
114498  sqlite3_int64 x;         /* Varint value */
114499  int rc;                  /* Result code from subfunctions */
114500  Fts3Table *p;            /* The FTS table */
114501
114502  p = (Fts3Table*)pCur->base.pVtab;
114503  rc = fts3SqlStmt(p, SQL_SELECT_DOCSIZE, &pStmt, 0);
114504  if( rc ){
114505    return rc;
114506  }
114507  sqlite3_bind_int64(pStmt, 1, pCur->iPrevId);
114508  if( sqlite3_step(pStmt)==SQLITE_ROW ){
114509    nBlob = sqlite3_column_bytes(pStmt, 0);
114510    pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
114511    for(i=j=0; i<p->nColumn && j<nBlob; i++){
114512      j = sqlite3Fts3GetVarint(&pBlob[j], &x);
114513      a[2+i*2] = (u32)(x & 0xffffffff);
114514    }
114515  }
114516  sqlite3_reset(pStmt);
114517  return SQLITE_OK;
114518}
114519SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor *pCur, u32 *a){
114520  const char *pBlob;       /* The BLOB holding %_stat info */
114521  int nBlob;               /* Size of the BLOB */
114522  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
114523  int i, j;                /* Loop counters */
114524  sqlite3_int64 x;         /* Varint value */
114525  int nDoc;                /* Number of documents */
114526  int rc;                  /* Result code from subfunctions */
114527  Fts3Table *p;            /* The FTS table */
114528
114529  p = (Fts3Table*)pCur->base.pVtab;
114530  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
114531  if( rc ){
114532    return rc;
114533  }
114534  if( sqlite3_step(pStmt)==SQLITE_ROW ){
114535    nBlob = sqlite3_column_bytes(pStmt, 0);
114536    pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
114537    j = sqlite3Fts3GetVarint(pBlob, &x);
114538    a[0] = nDoc = (u32)(x & 0xffffffff);
114539    for(i=0; i<p->nColumn && j<nBlob; i++){
114540      j = sqlite3Fts3GetVarint(&pBlob[j], &x);
114541      a[1+i*2] = ((u32)(x & 0xffffffff) + nDoc/2)/nDoc;
114542    }
114543  }
114544  sqlite3_reset(pStmt);
114545  return SQLITE_OK;
114546}
114547
114548/*
114549** Insert the sizes (in tokens) for each column of the document
114550** with docid equal to p->iPrevDocid.  The sizes are encoded as
114551** a blob of varints.
114552*/
114553static void fts3InsertDocsize(
114554  int *pRC,         /* Result code */
114555  Fts3Table *p,     /* Table into which to insert */
114556  u32 *aSz          /* Sizes of each column */
114557){
114558  char *pBlob;             /* The BLOB encoding of the document size */
114559  int nBlob;               /* Number of bytes in the BLOB */
114560  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
114561  int rc;                  /* Result code from subfunctions */
114562
114563  if( *pRC ) return;
114564  pBlob = sqlite3_malloc( 10*p->nColumn );
114565  if( pBlob==0 ){
114566    *pRC = SQLITE_NOMEM;
114567    return;
114568  }
114569  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
114570  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
114571  if( rc ){
114572    sqlite3_free(pBlob);
114573    *pRC = rc;
114574    return;
114575  }
114576  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
114577  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
114578  sqlite3_step(pStmt);
114579  *pRC = sqlite3_reset(pStmt);
114580}
114581
114582/*
114583** Update the 0 record of the %_stat table so that it holds a blob
114584** which contains the document count followed by the cumulative
114585** document sizes for all columns.
114586*/
114587static void fts3UpdateDocTotals(
114588  int *pRC,       /* The result code */
114589  Fts3Table *p,   /* Table being updated */
114590  u32 *aSzIns,    /* Size increases */
114591  u32 *aSzDel,    /* Size decreases */
114592  int nChng       /* Change in the number of documents */
114593){
114594  char *pBlob;             /* Storage for BLOB written into %_stat */
114595  int nBlob;               /* Size of BLOB written into %_stat */
114596  u32 *a;                  /* Array of integers that becomes the BLOB */
114597  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
114598  int i;                   /* Loop counter */
114599  int rc;                  /* Result code from subfunctions */
114600
114601  if( *pRC ) return;
114602  a = sqlite3_malloc( (sizeof(u32)+10)*(p->nColumn+1) );
114603  if( a==0 ){
114604    *pRC = SQLITE_NOMEM;
114605    return;
114606  }
114607  pBlob = (char*)&a[p->nColumn+1];
114608  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
114609  if( rc ){
114610    sqlite3_free(a);
114611    *pRC = rc;
114612    return;
114613  }
114614  if( sqlite3_step(pStmt)==SQLITE_ROW ){
114615    fts3DecodeIntArray(p->nColumn+1, a,
114616         sqlite3_column_blob(pStmt, 0),
114617         sqlite3_column_bytes(pStmt, 0));
114618  }else{
114619    memset(a, 0, sizeof(u32)*(p->nColumn+1) );
114620  }
114621  sqlite3_reset(pStmt);
114622  if( nChng<0 && a[0]<(u32)(-nChng) ){
114623    a[0] = 0;
114624  }else{
114625    a[0] += nChng;
114626  }
114627  for(i=0; i<p->nColumn; i++){
114628    u32 x = a[i+1];
114629    if( x+aSzIns[i] < aSzDel[i] ){
114630      x = 0;
114631    }else{
114632      x = x + aSzIns[i] - aSzDel[i];
114633    }
114634    a[i+1] = x;
114635  }
114636  fts3EncodeIntArray(p->nColumn+1, a, pBlob, &nBlob);
114637  rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
114638  if( rc ){
114639    sqlite3_free(a);
114640    *pRC = rc;
114641    return;
114642  }
114643  sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
114644  sqlite3_step(pStmt);
114645  *pRC = sqlite3_reset(pStmt);
114646  sqlite3_free(a);
114647}
114648
114649/*
114650** Handle a 'special' INSERT of the form:
114651**
114652**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
114653**
114654** Argument pVal contains the result of <expr>. Currently the only
114655** meaningful value to insert is the text 'optimize'.
114656*/
114657static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
114658  int rc;                         /* Return Code */
114659  const char *zVal = (const char *)sqlite3_value_text(pVal);
114660  int nVal = sqlite3_value_bytes(pVal);
114661
114662  if( !zVal ){
114663    return SQLITE_NOMEM;
114664  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
114665    rc = fts3SegmentMerge(p, -1);
114666    if( rc==SQLITE_DONE ){
114667      rc = SQLITE_OK;
114668    }else{
114669      sqlite3Fts3PendingTermsClear(p);
114670    }
114671#ifdef SQLITE_TEST
114672  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
114673    p->nNodeSize = atoi(&zVal[9]);
114674    rc = SQLITE_OK;
114675  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
114676    p->nMaxPendingData = atoi(&zVal[11]);
114677    rc = SQLITE_OK;
114678#endif
114679  }else{
114680    rc = SQLITE_ERROR;
114681  }
114682
114683  return rc;
114684}
114685
114686/*
114687** This function does the work for the xUpdate method of FTS3 virtual
114688** tables.
114689*/
114690SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
114691  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
114692  int nArg,                       /* Size of argument array */
114693  sqlite3_value **apVal,          /* Array of arguments */
114694  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
114695){
114696  Fts3Table *p = (Fts3Table *)pVtab;
114697  int rc = SQLITE_OK;             /* Return Code */
114698  int isRemove = 0;               /* True for an UPDATE or DELETE */
114699  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
114700  u32 *aSzIns;                    /* Sizes of inserted documents */
114701  u32 *aSzDel;                    /* Sizes of deleted documents */
114702  int nChng = 0;                  /* Net change in number of documents */
114703
114704
114705  /* Allocate space to hold the change in document sizes */
114706  aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*p->nColumn*2 );
114707  if( aSzIns==0 ) return SQLITE_NOMEM;
114708  aSzDel = &aSzIns[p->nColumn];
114709  memset(aSzIns, 0, sizeof(aSzIns[0])*p->nColumn*2);
114710
114711  /* If this is a DELETE or UPDATE operation, remove the old record. */
114712  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
114713    int isEmpty;
114714    rc = fts3IsEmpty(p, apVal, &isEmpty);
114715    if( rc==SQLITE_OK ){
114716      if( isEmpty ){
114717        /* Deleting this row means the whole table is empty. In this case
114718        ** delete the contents of all three tables and throw away any
114719        ** data in the pendingTerms hash table.
114720        */
114721        rc = fts3DeleteAll(p);
114722      }else{
114723        isRemove = 1;
114724        iRemove = sqlite3_value_int64(apVal[0]);
114725        rc = fts3PendingTermsDocid(p, iRemove);
114726        fts3DeleteTerms(&rc, p, apVal, aSzDel);
114727        fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
114728        if( p->bHasDocsize ){
114729          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
114730          nChng--;
114731        }
114732      }
114733    }
114734  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
114735    sqlite3_free(aSzIns);
114736    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
114737  }
114738
114739  /* If this is an INSERT or UPDATE operation, insert the new record. */
114740  if( nArg>1 && rc==SQLITE_OK ){
114741    rc = fts3InsertData(p, apVal, pRowid);
114742    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
114743      rc = fts3PendingTermsDocid(p, *pRowid);
114744    }
114745    if( rc==SQLITE_OK ){
114746      rc = fts3InsertTerms(p, apVal, aSzIns);
114747    }
114748    if( p->bHasDocsize ){
114749      nChng++;
114750      fts3InsertDocsize(&rc, p, aSzIns);
114751    }
114752  }
114753
114754  if( p->bHasDocsize ){
114755    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
114756  }
114757
114758  sqlite3_free(aSzIns);
114759  return rc;
114760}
114761
114762/*
114763** Flush any data in the pending-terms hash table to disk. If successful,
114764** merge all segments in the database (including the new segment, if
114765** there was any data to flush) into a single segment.
114766*/
114767SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
114768  int rc;
114769  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
114770  if( rc==SQLITE_OK ){
114771    rc = fts3SegmentMerge(p, -1);
114772    if( rc==SQLITE_OK ){
114773      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
114774      if( rc==SQLITE_OK ){
114775        sqlite3Fts3PendingTermsClear(p);
114776      }
114777    }else{
114778      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
114779      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
114780    }
114781  }
114782  return rc;
114783}
114784
114785#endif
114786
114787/************** End of fts3_write.c ******************************************/
114788/************** Begin file fts3_snippet.c ************************************/
114789/*
114790** 2009 Oct 23
114791**
114792** The author disclaims copyright to this source code.  In place of
114793** a legal notice, here is a blessing:
114794**
114795**    May you do good and not evil.
114796**    May you find forgiveness for yourself and forgive others.
114797**    May you share freely, never taking more than you give.
114798**
114799******************************************************************************
114800*/
114801
114802#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114803
114804
114805
114806/*
114807** Used as an fts3ExprIterate() context when loading phrase doclists to
114808** Fts3Expr.aDoclist[]/nDoclist.
114809*/
114810typedef struct LoadDoclistCtx LoadDoclistCtx;
114811struct LoadDoclistCtx {
114812  Fts3Table *pTab;                /* FTS3 Table */
114813  int nPhrase;                    /* Number of phrases seen so far */
114814  int nToken;                     /* Number of tokens seen so far */
114815};
114816
114817/*
114818** The following types are used as part of the implementation of the
114819** fts3BestSnippet() routine.
114820*/
114821typedef struct SnippetIter SnippetIter;
114822typedef struct SnippetPhrase SnippetPhrase;
114823typedef struct SnippetFragment SnippetFragment;
114824
114825struct SnippetIter {
114826  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
114827  int iCol;                       /* Extract snippet from this column */
114828  int nSnippet;                   /* Requested snippet length (in tokens) */
114829  int nPhrase;                    /* Number of phrases in query */
114830  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
114831  int iCurrent;                   /* First token of current snippet */
114832};
114833
114834struct SnippetPhrase {
114835  int nToken;                     /* Number of tokens in phrase */
114836  char *pList;                    /* Pointer to start of phrase position list */
114837  int iHead;                      /* Next value in position list */
114838  char *pHead;                    /* Position list data following iHead */
114839  int iTail;                      /* Next value in trailing position list */
114840  char *pTail;                    /* Position list data following iTail */
114841};
114842
114843struct SnippetFragment {
114844  int iCol;                       /* Column snippet is extracted from */
114845  int iPos;                       /* Index of first token in snippet */
114846  u64 covered;                    /* Mask of query phrases covered */
114847  u64 hlmask;                     /* Mask of snippet terms to highlight */
114848};
114849
114850/*
114851** This type is used as an fts3ExprIterate() context object while
114852** accumulating the data returned by the matchinfo() function.
114853*/
114854typedef struct MatchInfo MatchInfo;
114855struct MatchInfo {
114856  Fts3Cursor *pCursor;            /* FTS3 Cursor */
114857  int nCol;                       /* Number of columns in table */
114858  u32 *aMatchinfo;                /* Pre-allocated buffer */
114859};
114860
114861
114862
114863/*
114864** The snippet() and offsets() functions both return text values. An instance
114865** of the following structure is used to accumulate those values while the
114866** functions are running. See fts3StringAppend() for details.
114867*/
114868typedef struct StrBuffer StrBuffer;
114869struct StrBuffer {
114870  char *z;                        /* Pointer to buffer containing string */
114871  int n;                          /* Length of z in bytes (excl. nul-term) */
114872  int nAlloc;                     /* Allocated size of buffer z in bytes */
114873};
114874
114875
114876/*
114877** This function is used to help iterate through a position-list. A position
114878** list is a list of unique integers, sorted from smallest to largest. Each
114879** element of the list is represented by an FTS3 varint that takes the value
114880** of the difference between the current element and the previous one plus
114881** two. For example, to store the position-list:
114882**
114883**     4 9 113
114884**
114885** the three varints:
114886**
114887**     6 7 106
114888**
114889** are encoded.
114890**
114891** When this function is called, *pp points to the start of an element of
114892** the list. *piPos contains the value of the previous entry in the list.
114893** After it returns, *piPos contains the value of the next element of the
114894** list and *pp is advanced to the following varint.
114895*/
114896static void fts3GetDeltaPosition(char **pp, int *piPos){
114897  int iVal;
114898  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
114899  *piPos += (iVal-2);
114900}
114901
114902/*
114903** Helper function for fts3ExprIterate() (see below).
114904*/
114905static int fts3ExprIterate2(
114906  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
114907  int *piPhrase,                  /* Pointer to phrase counter */
114908  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
114909  void *pCtx                      /* Second argument to pass to callback */
114910){
114911  int rc;                         /* Return code */
114912  int eType = pExpr->eType;       /* Type of expression node pExpr */
114913
114914  if( eType!=FTSQUERY_PHRASE ){
114915    assert( pExpr->pLeft && pExpr->pRight );
114916    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
114917    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
114918      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
114919    }
114920  }else{
114921    rc = x(pExpr, *piPhrase, pCtx);
114922    (*piPhrase)++;
114923  }
114924  return rc;
114925}
114926
114927/*
114928** Iterate through all phrase nodes in an FTS3 query, except those that
114929** are part of a sub-tree that is the right-hand-side of a NOT operator.
114930** For each phrase node found, the supplied callback function is invoked.
114931**
114932** If the callback function returns anything other than SQLITE_OK,
114933** the iteration is abandoned and the error code returned immediately.
114934** Otherwise, SQLITE_OK is returned after a callback has been made for
114935** all eligible phrase nodes.
114936*/
114937static int fts3ExprIterate(
114938  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
114939  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
114940  void *pCtx                      /* Second argument to pass to callback */
114941){
114942  int iPhrase = 0;                /* Variable used as the phrase counter */
114943  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
114944}
114945
114946/*
114947** The argument to this function is always a phrase node. Its doclist
114948** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
114949** to the left of this one in the query tree have already been loaded.
114950**
114951** If this phrase node is part of a series of phrase nodes joined by
114952** NEAR operators (and is not the left-most of said series), then elements are
114953** removed from the phrases doclist consistent with the NEAR restriction. If
114954** required, elements may be removed from the doclists of phrases to the
114955** left of this one that are part of the same series of NEAR operator
114956** connected phrases.
114957**
114958** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
114959*/
114960static int fts3ExprNearTrim(Fts3Expr *pExpr){
114961  int rc = SQLITE_OK;
114962  Fts3Expr *pParent = pExpr->pParent;
114963
114964  assert( pExpr->eType==FTSQUERY_PHRASE );
114965  while( rc==SQLITE_OK
114966   && pParent
114967   && pParent->eType==FTSQUERY_NEAR
114968   && pParent->pRight==pExpr
114969  ){
114970    /* This expression (pExpr) is the right-hand-side of a NEAR operator.
114971    ** Find the expression to the left of the same operator.
114972    */
114973    int nNear = pParent->nNear;
114974    Fts3Expr *pLeft = pParent->pLeft;
114975
114976    if( pLeft->eType!=FTSQUERY_PHRASE ){
114977      assert( pLeft->eType==FTSQUERY_NEAR );
114978      assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
114979      pLeft = pLeft->pRight;
114980    }
114981
114982    rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
114983
114984    pExpr = pLeft;
114985    pParent = pExpr->pParent;
114986  }
114987
114988  return rc;
114989}
114990
114991/*
114992** This is an fts3ExprIterate() callback used while loading the doclists
114993** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
114994** fts3ExprLoadDoclists().
114995*/
114996static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
114997  int rc = SQLITE_OK;
114998  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
114999
115000  UNUSED_PARAMETER(iPhrase);
115001
115002  p->nPhrase++;
115003  p->nToken += pExpr->pPhrase->nToken;
115004
115005  if( pExpr->isLoaded==0 ){
115006    rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
115007    pExpr->isLoaded = 1;
115008    if( rc==SQLITE_OK ){
115009      rc = fts3ExprNearTrim(pExpr);
115010    }
115011  }
115012
115013  return rc;
115014}
115015
115016/*
115017** This is an fts3ExprIterate() callback used while loading the doclists
115018** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
115019** fts3ExprLoadDoclists().
115020*/
115021static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
115022  UNUSED_PARAMETER(iPhrase);
115023  UNUSED_PARAMETER(ctx);
115024  if( pExpr->aDoclist ){
115025    pExpr->pCurrent = pExpr->aDoclist;
115026    pExpr->iCurrent = 0;
115027    pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
115028  }
115029  return SQLITE_OK;
115030}
115031
115032/*
115033** Load the doclists for each phrase in the query associated with FTS3 cursor
115034** pCsr.
115035**
115036** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
115037** phrases in the expression (all phrases except those directly or
115038** indirectly descended from the right-hand-side of a NOT operator). If
115039** pnToken is not NULL, then it is set to the number of tokens in all
115040** matchable phrases of the expression.
115041*/
115042static int fts3ExprLoadDoclists(
115043  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
115044  int *pnPhrase,                  /* OUT: Number of phrases in query */
115045  int *pnToken                    /* OUT: Number of tokens in query */
115046){
115047  int rc;                         /* Return Code */
115048  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
115049  sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
115050  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
115051  if( rc==SQLITE_OK ){
115052    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
115053  }
115054  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
115055  if( pnToken ) *pnToken = sCtx.nToken;
115056  return rc;
115057}
115058
115059/*
115060** Advance the position list iterator specified by the first two
115061** arguments so that it points to the first element with a value greater
115062** than or equal to parameter iNext.
115063*/
115064static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
115065  char *pIter = *ppIter;
115066  if( pIter ){
115067    int iIter = *piIter;
115068
115069    while( iIter<iNext ){
115070      if( 0==(*pIter & 0xFE) ){
115071        iIter = -1;
115072        pIter = 0;
115073        break;
115074      }
115075      fts3GetDeltaPosition(&pIter, &iIter);
115076    }
115077
115078    *piIter = iIter;
115079    *ppIter = pIter;
115080  }
115081}
115082
115083/*
115084** Advance the snippet iterator to the next candidate snippet.
115085*/
115086static int fts3SnippetNextCandidate(SnippetIter *pIter){
115087  int i;                          /* Loop counter */
115088
115089  if( pIter->iCurrent<0 ){
115090    /* The SnippetIter object has just been initialized. The first snippet
115091    ** candidate always starts at offset 0 (even if this candidate has a
115092    ** score of 0.0).
115093    */
115094    pIter->iCurrent = 0;
115095
115096    /* Advance the 'head' iterator of each phrase to the first offset that
115097    ** is greater than or equal to (iNext+nSnippet).
115098    */
115099    for(i=0; i<pIter->nPhrase; i++){
115100      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115101      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
115102    }
115103  }else{
115104    int iStart;
115105    int iEnd = 0x7FFFFFFF;
115106
115107    for(i=0; i<pIter->nPhrase; i++){
115108      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115109      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
115110        iEnd = pPhrase->iHead;
115111      }
115112    }
115113    if( iEnd==0x7FFFFFFF ){
115114      return 1;
115115    }
115116
115117    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
115118    for(i=0; i<pIter->nPhrase; i++){
115119      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115120      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
115121      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
115122    }
115123  }
115124
115125  return 0;
115126}
115127
115128/*
115129** Retrieve information about the current candidate snippet of snippet
115130** iterator pIter.
115131*/
115132static void fts3SnippetDetails(
115133  SnippetIter *pIter,             /* Snippet iterator */
115134  u64 mCovered,                   /* Bitmask of phrases already covered */
115135  int *piToken,                   /* OUT: First token of proposed snippet */
115136  int *piScore,                   /* OUT: "Score" for this snippet */
115137  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
115138  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
115139){
115140  int iStart = pIter->iCurrent;   /* First token of snippet */
115141  int iScore = 0;                 /* Score of this snippet */
115142  int i;                          /* Loop counter */
115143  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
115144  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
115145
115146  for(i=0; i<pIter->nPhrase; i++){
115147    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
115148    if( pPhrase->pTail ){
115149      char *pCsr = pPhrase->pTail;
115150      int iCsr = pPhrase->iTail;
115151
115152      while( iCsr<(iStart+pIter->nSnippet) ){
115153        int j;
115154        u64 mPhrase = (u64)1 << i;
115155        u64 mPos = (u64)1 << (iCsr - iStart);
115156        assert( iCsr>=iStart );
115157        if( (mCover|mCovered)&mPhrase ){
115158          iScore++;
115159        }else{
115160          iScore += 1000;
115161        }
115162        mCover |= mPhrase;
115163
115164        for(j=0; j<pPhrase->nToken; j++){
115165          mHighlight |= (mPos>>j);
115166        }
115167
115168        if( 0==(*pCsr & 0x0FE) ) break;
115169        fts3GetDeltaPosition(&pCsr, &iCsr);
115170      }
115171    }
115172  }
115173
115174  /* Set the output variables before returning. */
115175  *piToken = iStart;
115176  *piScore = iScore;
115177  *pmCover = mCover;
115178  *pmHighlight = mHighlight;
115179}
115180
115181/*
115182** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
115183** Each invocation populates an element of the SnippetIter.aPhrase[] array.
115184*/
115185static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
115186  SnippetIter *p = (SnippetIter *)ctx;
115187  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
115188  char *pCsr;
115189
115190  pPhrase->nToken = pExpr->pPhrase->nToken;
115191
115192  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
115193  if( pCsr ){
115194    int iFirst = 0;
115195    pPhrase->pList = pCsr;
115196    fts3GetDeltaPosition(&pCsr, &iFirst);
115197    pPhrase->pHead = pCsr;
115198    pPhrase->pTail = pCsr;
115199    pPhrase->iHead = iFirst;
115200    pPhrase->iTail = iFirst;
115201  }else{
115202    assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
115203  }
115204
115205  return SQLITE_OK;
115206}
115207
115208/*
115209** Select the fragment of text consisting of nFragment contiguous tokens
115210** from column iCol that represent the "best" snippet. The best snippet
115211** is the snippet with the highest score, where scores are calculated
115212** by adding:
115213**
115214**   (a) +1 point for each occurence of a matchable phrase in the snippet.
115215**
115216**   (b) +1000 points for the first occurence of each matchable phrase in
115217**       the snippet for which the corresponding mCovered bit is not set.
115218**
115219** The selected snippet parameters are stored in structure *pFragment before
115220** returning. The score of the selected snippet is stored in *piScore
115221** before returning.
115222*/
115223static int fts3BestSnippet(
115224  int nSnippet,                   /* Desired snippet length */
115225  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
115226  int iCol,                       /* Index of column to create snippet from */
115227  u64 mCovered,                   /* Mask of phrases already covered */
115228  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
115229  SnippetFragment *pFragment,     /* OUT: Best snippet found */
115230  int *piScore                    /* OUT: Score of snippet pFragment */
115231){
115232  int rc;                         /* Return Code */
115233  int nList;                      /* Number of phrases in expression */
115234  SnippetIter sIter;              /* Iterates through snippet candidates */
115235  int nByte;                      /* Number of bytes of space to allocate */
115236  int iBestScore = -1;            /* Best snippet score found so far */
115237  int i;                          /* Loop counter */
115238
115239  memset(&sIter, 0, sizeof(sIter));
115240
115241  /* Iterate through the phrases in the expression to count them. The same
115242  ** callback makes sure the doclists are loaded for each phrase.
115243  */
115244  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
115245  if( rc!=SQLITE_OK ){
115246    return rc;
115247  }
115248
115249  /* Now that it is known how many phrases there are, allocate and zero
115250  ** the required space using malloc().
115251  */
115252  nByte = sizeof(SnippetPhrase) * nList;
115253  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
115254  if( !sIter.aPhrase ){
115255    return SQLITE_NOMEM;
115256  }
115257  memset(sIter.aPhrase, 0, nByte);
115258
115259  /* Initialize the contents of the SnippetIter object. Then iterate through
115260  ** the set of phrases in the expression to populate the aPhrase[] array.
115261  */
115262  sIter.pCsr = pCsr;
115263  sIter.iCol = iCol;
115264  sIter.nSnippet = nSnippet;
115265  sIter.nPhrase = nList;
115266  sIter.iCurrent = -1;
115267  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
115268
115269  /* Set the *pmSeen output variable. */
115270  for(i=0; i<nList; i++){
115271    if( sIter.aPhrase[i].pHead ){
115272      *pmSeen |= (u64)1 << i;
115273    }
115274  }
115275
115276  /* Loop through all candidate snippets. Store the best snippet in
115277  ** *pFragment. Store its associated 'score' in iBestScore.
115278  */
115279  pFragment->iCol = iCol;
115280  while( !fts3SnippetNextCandidate(&sIter) ){
115281    int iPos;
115282    int iScore;
115283    u64 mCover;
115284    u64 mHighlight;
115285    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
115286    assert( iScore>=0 );
115287    if( iScore>iBestScore ){
115288      pFragment->iPos = iPos;
115289      pFragment->hlmask = mHighlight;
115290      pFragment->covered = mCover;
115291      iBestScore = iScore;
115292    }
115293  }
115294
115295  sqlite3_free(sIter.aPhrase);
115296  *piScore = iBestScore;
115297  return SQLITE_OK;
115298}
115299
115300
115301/*
115302** Append a string to the string-buffer passed as the first argument.
115303**
115304** If nAppend is negative, then the length of the string zAppend is
115305** determined using strlen().
115306*/
115307static int fts3StringAppend(
115308  StrBuffer *pStr,                /* Buffer to append to */
115309  const char *zAppend,            /* Pointer to data to append to buffer */
115310  int nAppend                     /* Size of zAppend in bytes (or -1) */
115311){
115312  if( nAppend<0 ){
115313    nAppend = (int)strlen(zAppend);
115314  }
115315
115316  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
115317  ** to grow the buffer until so that it is big enough to accomadate the
115318  ** appended data.
115319  */
115320  if( pStr->n+nAppend+1>=pStr->nAlloc ){
115321    int nAlloc = pStr->nAlloc+nAppend+100;
115322    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
115323    if( !zNew ){
115324      return SQLITE_NOMEM;
115325    }
115326    pStr->z = zNew;
115327    pStr->nAlloc = nAlloc;
115328  }
115329
115330  /* Append the data to the string buffer. */
115331  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
115332  pStr->n += nAppend;
115333  pStr->z[pStr->n] = '\0';
115334
115335  return SQLITE_OK;
115336}
115337
115338/*
115339** The fts3BestSnippet() function often selects snippets that end with a
115340** query term. That is, the final term of the snippet is always a term
115341** that requires highlighting. For example, if 'X' is a highlighted term
115342** and '.' is a non-highlighted term, BestSnippet() may select:
115343**
115344**     ........X.....X
115345**
115346** This function "shifts" the beginning of the snippet forward in the
115347** document so that there are approximately the same number of
115348** non-highlighted terms to the right of the final highlighted term as there
115349** are to the left of the first highlighted term. For example, to this:
115350**
115351**     ....X.....X....
115352**
115353** This is done as part of extracting the snippet text, not when selecting
115354** the snippet. Snippet selection is done based on doclists only, so there
115355** is no way for fts3BestSnippet() to know whether or not the document
115356** actually contains terms that follow the final highlighted term.
115357*/
115358static int fts3SnippetShift(
115359  Fts3Table *pTab,                /* FTS3 table snippet comes from */
115360  int nSnippet,                   /* Number of tokens desired for snippet */
115361  const char *zDoc,               /* Document text to extract snippet from */
115362  int nDoc,                       /* Size of buffer zDoc in bytes */
115363  int *piPos,                     /* IN/OUT: First token of snippet */
115364  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
115365){
115366  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
115367
115368  if( hlmask ){
115369    int nLeft;                    /* Tokens to the left of first highlight */
115370    int nRight;                   /* Tokens to the right of last highlight */
115371    int nDesired;                 /* Ideal number of tokens to shift forward */
115372
115373    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
115374    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
115375    nDesired = (nLeft-nRight)/2;
115376
115377    /* Ideally, the start of the snippet should be pushed forward in the
115378    ** document nDesired tokens. This block checks if there are actually
115379    ** nDesired tokens to the right of the snippet. If so, *piPos and
115380    ** *pHlMask are updated to shift the snippet nDesired tokens to the
115381    ** right. Otherwise, the snippet is shifted by the number of tokens
115382    ** available.
115383    */
115384    if( nDesired>0 ){
115385      int nShift;                 /* Number of tokens to shift snippet by */
115386      int iCurrent = 0;           /* Token counter */
115387      int rc;                     /* Return Code */
115388      sqlite3_tokenizer_module *pMod;
115389      sqlite3_tokenizer_cursor *pC;
115390      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
115391
115392      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
115393      ** or more tokens in zDoc/nDoc.
115394      */
115395      rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
115396      if( rc!=SQLITE_OK ){
115397        return rc;
115398      }
115399      pC->pTokenizer = pTab->pTokenizer;
115400      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
115401        const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
115402        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
115403      }
115404      pMod->xClose(pC);
115405      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
115406
115407      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
115408      assert( nShift<=nDesired );
115409      if( nShift>0 ){
115410        *piPos += nShift;
115411        *pHlmask = hlmask >> nShift;
115412      }
115413    }
115414  }
115415  return SQLITE_OK;
115416}
115417
115418/*
115419** Extract the snippet text for fragment pFragment from cursor pCsr and
115420** append it to string buffer pOut.
115421*/
115422static int fts3SnippetText(
115423  Fts3Cursor *pCsr,               /* FTS3 Cursor */
115424  SnippetFragment *pFragment,     /* Snippet to extract */
115425  int iFragment,                  /* Fragment number */
115426  int isLast,                     /* True for final fragment in snippet */
115427  int nSnippet,                   /* Number of tokens in extracted snippet */
115428  const char *zOpen,              /* String inserted before highlighted term */
115429  const char *zClose,             /* String inserted after highlighted term */
115430  const char *zEllipsis,          /* String inserted between snippets */
115431  StrBuffer *pOut                 /* Write output here */
115432){
115433  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115434  int rc;                         /* Return code */
115435  const char *zDoc;               /* Document text to extract snippet from */
115436  int nDoc;                       /* Size of zDoc in bytes */
115437  int iCurrent = 0;               /* Current token number of document */
115438  int iEnd = 0;                   /* Byte offset of end of current token */
115439  int isShiftDone = 0;            /* True after snippet is shifted */
115440  int iPos = pFragment->iPos;     /* First token of snippet */
115441  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
115442  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
115443  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
115444  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
115445  const char *ZDUMMY;             /* Dummy argument used with tokenizer */
115446  int DUMMY1;                     /* Dummy argument used with tokenizer */
115447
115448  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
115449  if( zDoc==0 ){
115450    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
115451      return SQLITE_NOMEM;
115452    }
115453    return SQLITE_OK;
115454  }
115455  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
115456
115457  /* Open a token cursor on the document. */
115458  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
115459  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
115460  if( rc!=SQLITE_OK ){
115461    return rc;
115462  }
115463  pC->pTokenizer = pTab->pTokenizer;
115464
115465  while( rc==SQLITE_OK ){
115466    int iBegin;                   /* Offset in zDoc of start of token */
115467    int iFin;                     /* Offset in zDoc of end of token */
115468    int isHighlight;              /* True for highlighted terms */
115469
115470    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
115471    if( rc!=SQLITE_OK ){
115472      if( rc==SQLITE_DONE ){
115473        /* Special case - the last token of the snippet is also the last token
115474        ** of the column. Append any punctuation that occurred between the end
115475        ** of the previous token and the end of the document to the output.
115476        ** Then break out of the loop. */
115477        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
115478      }
115479      break;
115480    }
115481    if( iCurrent<iPos ){ continue; }
115482
115483    if( !isShiftDone ){
115484      int n = nDoc - iBegin;
115485      rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
115486      isShiftDone = 1;
115487
115488      /* Now that the shift has been done, check if the initial "..." are
115489      ** required. They are required if (a) this is not the first fragment,
115490      ** or (b) this fragment does not begin at position 0 of its column.
115491      */
115492      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
115493        rc = fts3StringAppend(pOut, zEllipsis, -1);
115494      }
115495      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
115496    }
115497
115498    if( iCurrent>=(iPos+nSnippet) ){
115499      if( isLast ){
115500        rc = fts3StringAppend(pOut, zEllipsis, -1);
115501      }
115502      break;
115503    }
115504
115505    /* Set isHighlight to true if this term should be highlighted. */
115506    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
115507
115508    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
115509    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
115510    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
115511    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
115512
115513    iEnd = iFin;
115514  }
115515
115516  pMod->xClose(pC);
115517  return rc;
115518}
115519
115520
115521/*
115522** This function is used to count the entries in a column-list (a
115523** delta-encoded list of term offsets within a single column of a single
115524** row). When this function is called, *ppCollist should point to the
115525** beginning of the first varint in the column-list (the varint that
115526** contains the position of the first matching term in the column data).
115527** Before returning, *ppCollist is set to point to the first byte after
115528** the last varint in the column-list (either the 0x00 signifying the end
115529** of the position-list, or the 0x01 that precedes the column number of
115530** the next column in the position-list).
115531**
115532** The number of elements in the column-list is returned.
115533*/
115534static int fts3ColumnlistCount(char **ppCollist){
115535  char *pEnd = *ppCollist;
115536  char c = 0;
115537  int nEntry = 0;
115538
115539  /* A column-list is terminated by either a 0x01 or 0x00. */
115540  while( 0xFE & (*pEnd | c) ){
115541    c = *pEnd++ & 0x80;
115542    if( !c ) nEntry++;
115543  }
115544
115545  *ppCollist = pEnd;
115546  return nEntry;
115547}
115548
115549static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
115550  char *pCsr = *pp;
115551  while( *pCsr ){
115552    int nHit;
115553    sqlite3_int64 iCol = 0;
115554    if( *pCsr==0x01 ){
115555      pCsr++;
115556      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
115557    }
115558    nHit = fts3ColumnlistCount(&pCsr);
115559    assert( nHit>0 );
115560    if( isGlobal ){
115561      aOut[iCol*3+1]++;
115562    }
115563    aOut[iCol*3] += nHit;
115564  }
115565  pCsr++;
115566  *pp = pCsr;
115567}
115568
115569/*
115570** fts3ExprIterate() callback used to collect the "global" matchinfo stats
115571** for a single query. The "global" stats are those elements of the matchinfo
115572** array that are constant for all rows returned by the current query.
115573*/
115574static int fts3ExprGlobalMatchinfoCb(
115575  Fts3Expr *pExpr,                /* Phrase expression node */
115576  int iPhrase,                    /* Phrase number (numbered from zero) */
115577  void *pCtx                      /* Pointer to MatchInfo structure */
115578){
115579  MatchInfo *p = (MatchInfo *)pCtx;
115580  char *pCsr;
115581  char *pEnd;
115582  const int iStart = 2 + (iPhrase * p->nCol * 3) + 1;
115583
115584  assert( pExpr->isLoaded );
115585
115586  /* Fill in the global hit count matrix row for this phrase. */
115587  pCsr = pExpr->aDoclist;
115588  pEnd = &pExpr->aDoclist[pExpr->nDoclist];
115589  while( pCsr<pEnd ){
115590    while( *pCsr++ & 0x80 );      /* Skip past docid. */
115591    fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 1);
115592  }
115593
115594  return SQLITE_OK;
115595}
115596
115597/*
115598** fts3ExprIterate() callback used to collect the "local" matchinfo stats
115599** for a single query. The "local" stats are those elements of the matchinfo
115600** array that are different for each row returned by the query.
115601*/
115602static int fts3ExprLocalMatchinfoCb(
115603  Fts3Expr *pExpr,                /* Phrase expression node */
115604  int iPhrase,                    /* Phrase number */
115605  void *pCtx                      /* Pointer to MatchInfo structure */
115606){
115607  MatchInfo *p = (MatchInfo *)pCtx;
115608
115609  if( pExpr->aDoclist ){
115610    char *pCsr;
115611    int iStart = 2 + (iPhrase * p->nCol * 3);
115612    int i;
115613
115614    for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
115615
115616    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
115617    if( pCsr ){
115618      fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
115619    }
115620  }
115621
115622  return SQLITE_OK;
115623}
115624
115625/*
115626** Populate pCsr->aMatchinfo[] with data for the current row. The
115627** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
115628*/
115629static int fts3GetMatchinfo(Fts3Cursor *pCsr){
115630  MatchInfo sInfo;
115631  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115632  int rc = SQLITE_OK;
115633
115634  sInfo.pCursor = pCsr;
115635  sInfo.nCol = pTab->nColumn;
115636
115637  if( pCsr->aMatchinfo==0 ){
115638    /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
115639    ** matchinfo function has been called for this query. In this case
115640    ** allocate the array used to accumulate the matchinfo data and
115641    ** initialize those elements that are constant for every row.
115642    */
115643    int nPhrase;                  /* Number of phrases */
115644    int nMatchinfo;               /* Number of u32 elements in match-info */
115645
115646    /* Load doclists for each phrase in the query. */
115647    rc = fts3ExprLoadDoclists(pCsr, &nPhrase, 0);
115648    if( rc!=SQLITE_OK ){
115649      return rc;
115650    }
115651    nMatchinfo = 2 + 3*sInfo.nCol*nPhrase;
115652    if( pTab->bHasDocsize ){
115653      nMatchinfo += 1 + 2*pTab->nColumn;
115654    }
115655
115656    sInfo.aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
115657    if( !sInfo.aMatchinfo ){
115658      return SQLITE_NOMEM;
115659    }
115660    memset(sInfo.aMatchinfo, 0, sizeof(u32)*nMatchinfo);
115661
115662
115663    /* First element of match-info is the number of phrases in the query */
115664    sInfo.aMatchinfo[0] = nPhrase;
115665    sInfo.aMatchinfo[1] = sInfo.nCol;
115666    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb,(void*)&sInfo);
115667    if( pTab->bHasDocsize ){
115668      int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
115669      rc = sqlite3Fts3MatchinfoDocsizeGlobal(pCsr, &sInfo.aMatchinfo[ofst]);
115670    }
115671    pCsr->aMatchinfo = sInfo.aMatchinfo;
115672    pCsr->isMatchinfoNeeded = 1;
115673  }
115674
115675  sInfo.aMatchinfo = pCsr->aMatchinfo;
115676  if( rc==SQLITE_OK && pCsr->isMatchinfoNeeded ){
115677    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void*)&sInfo);
115678    if( pTab->bHasDocsize ){
115679      int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
115680      rc = sqlite3Fts3MatchinfoDocsizeLocal(pCsr, &sInfo.aMatchinfo[ofst]);
115681    }
115682    pCsr->isMatchinfoNeeded = 0;
115683  }
115684
115685  return SQLITE_OK;
115686}
115687
115688/*
115689** Implementation of snippet() function.
115690*/
115691SQLITE_PRIVATE void sqlite3Fts3Snippet(
115692  sqlite3_context *pCtx,          /* SQLite function call context */
115693  Fts3Cursor *pCsr,               /* Cursor object */
115694  const char *zStart,             /* Snippet start text - "<b>" */
115695  const char *zEnd,               /* Snippet end text - "</b>" */
115696  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
115697  int iCol,                       /* Extract snippet from this column */
115698  int nToken                      /* Approximate number of tokens in snippet */
115699){
115700  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115701  int rc = SQLITE_OK;
115702  int i;
115703  StrBuffer res = {0, 0, 0};
115704
115705  /* The returned text includes up to four fragments of text extracted from
115706  ** the data in the current row. The first iteration of the for(...) loop
115707  ** below attempts to locate a single fragment of text nToken tokens in
115708  ** size that contains at least one instance of all phrases in the query
115709  ** expression that appear in the current row. If such a fragment of text
115710  ** cannot be found, the second iteration of the loop attempts to locate
115711  ** a pair of fragments, and so on.
115712  */
115713  int nSnippet = 0;               /* Number of fragments in this snippet */
115714  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
115715  int nFToken = -1;               /* Number of tokens in each fragment */
115716
115717  if( !pCsr->pExpr ){
115718    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
115719    return;
115720  }
115721
115722  for(nSnippet=1; 1; nSnippet++){
115723
115724    int iSnip;                    /* Loop counter 0..nSnippet-1 */
115725    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
115726    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
115727
115728    if( nToken>=0 ){
115729      nFToken = (nToken+nSnippet-1) / nSnippet;
115730    }else{
115731      nFToken = -1 * nToken;
115732    }
115733
115734    for(iSnip=0; iSnip<nSnippet; iSnip++){
115735      int iBestScore = -1;        /* Best score of columns checked so far */
115736      int iRead;                  /* Used to iterate through columns */
115737      SnippetFragment *pFragment = &aSnippet[iSnip];
115738
115739      memset(pFragment, 0, sizeof(*pFragment));
115740
115741      /* Loop through all columns of the table being considered for snippets.
115742      ** If the iCol argument to this function was negative, this means all
115743      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
115744      */
115745      for(iRead=0; iRead<pTab->nColumn; iRead++){
115746        SnippetFragment sF;
115747        int iS;
115748        if( iCol>=0 && iRead!=iCol ) continue;
115749
115750        /* Find the best snippet of nFToken tokens in column iRead. */
115751        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
115752        if( rc!=SQLITE_OK ){
115753          goto snippet_out;
115754        }
115755        if( iS>iBestScore ){
115756          *pFragment = sF;
115757          iBestScore = iS;
115758        }
115759      }
115760
115761      mCovered |= pFragment->covered;
115762    }
115763
115764    /* If all query phrases seen by fts3BestSnippet() are present in at least
115765    ** one of the nSnippet snippet fragments, break out of the loop.
115766    */
115767    assert( (mCovered&mSeen)==mCovered );
115768    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
115769  }
115770
115771  assert( nFToken>0 );
115772
115773  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
115774    rc = fts3SnippetText(pCsr, &aSnippet[i],
115775        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
115776    );
115777  }
115778
115779 snippet_out:
115780  if( rc!=SQLITE_OK ){
115781    sqlite3_result_error_code(pCtx, rc);
115782    sqlite3_free(res.z);
115783  }else{
115784    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
115785  }
115786}
115787
115788
115789typedef struct TermOffset TermOffset;
115790typedef struct TermOffsetCtx TermOffsetCtx;
115791
115792struct TermOffset {
115793  char *pList;                    /* Position-list */
115794  int iPos;                       /* Position just read from pList */
115795  int iOff;                       /* Offset of this term from read positions */
115796};
115797
115798struct TermOffsetCtx {
115799  int iCol;                       /* Column of table to populate aTerm for */
115800  int iTerm;
115801  sqlite3_int64 iDocid;
115802  TermOffset *aTerm;
115803};
115804
115805/*
115806** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
115807*/
115808static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
115809  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
115810  int nTerm;                      /* Number of tokens in phrase */
115811  int iTerm;                      /* For looping through nTerm phrase terms */
115812  char *pList;                    /* Pointer to position list for phrase */
115813  int iPos = 0;                   /* First position in position-list */
115814
115815  UNUSED_PARAMETER(iPhrase);
115816  pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
115817  nTerm = pExpr->pPhrase->nToken;
115818  if( pList ){
115819    fts3GetDeltaPosition(&pList, &iPos);
115820    assert( iPos>=0 );
115821  }
115822
115823  for(iTerm=0; iTerm<nTerm; iTerm++){
115824    TermOffset *pT = &p->aTerm[p->iTerm++];
115825    pT->iOff = nTerm-iTerm-1;
115826    pT->pList = pList;
115827    pT->iPos = iPos;
115828  }
115829
115830  return SQLITE_OK;
115831}
115832
115833/*
115834** Implementation of offsets() function.
115835*/
115836SQLITE_PRIVATE void sqlite3Fts3Offsets(
115837  sqlite3_context *pCtx,          /* SQLite function call context */
115838  Fts3Cursor *pCsr                /* Cursor object */
115839){
115840  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115841  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
115842  const char *ZDUMMY;             /* Dummy argument used with xNext() */
115843  int NDUMMY;                     /* Dummy argument used with xNext() */
115844  int rc;                         /* Return Code */
115845  int nToken;                     /* Number of tokens in query */
115846  int iCol;                       /* Column currently being processed */
115847  StrBuffer res = {0, 0, 0};      /* Result string */
115848  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
115849
115850  if( !pCsr->pExpr ){
115851    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
115852    return;
115853  }
115854
115855  memset(&sCtx, 0, sizeof(sCtx));
115856  assert( pCsr->isRequireSeek==0 );
115857
115858  /* Count the number of terms in the query */
115859  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
115860  if( rc!=SQLITE_OK ) goto offsets_out;
115861
115862  /* Allocate the array of TermOffset iterators. */
115863  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
115864  if( 0==sCtx.aTerm ){
115865    rc = SQLITE_NOMEM;
115866    goto offsets_out;
115867  }
115868  sCtx.iDocid = pCsr->iPrevId;
115869
115870  /* Loop through the table columns, appending offset information to
115871  ** string-buffer res for each column.
115872  */
115873  for(iCol=0; iCol<pTab->nColumn; iCol++){
115874    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
115875    int iStart;
115876    int iEnd;
115877    int iCurrent;
115878    const char *zDoc;
115879    int nDoc;
115880
115881    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
115882    ** no way that this operation can fail, so the return code from
115883    ** fts3ExprIterate() can be discarded.
115884    */
115885    sCtx.iCol = iCol;
115886    sCtx.iTerm = 0;
115887    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
115888
115889    /* Retreive the text stored in column iCol. If an SQL NULL is stored
115890    ** in column iCol, jump immediately to the next iteration of the loop.
115891    ** If an OOM occurs while retrieving the data (this can happen if SQLite
115892    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
115893    ** to the caller.
115894    */
115895    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
115896    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
115897    if( zDoc==0 ){
115898      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
115899        continue;
115900      }
115901      rc = SQLITE_NOMEM;
115902      goto offsets_out;
115903    }
115904
115905    /* Initialize a tokenizer iterator to iterate through column iCol. */
115906    rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
115907    if( rc!=SQLITE_OK ) goto offsets_out;
115908    pC->pTokenizer = pTab->pTokenizer;
115909
115910    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
115911    while( rc==SQLITE_OK ){
115912      int i;                      /* Used to loop through terms */
115913      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
115914      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
115915
115916      for(i=0; i<nToken; i++){
115917        TermOffset *pT = &sCtx.aTerm[i];
115918        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
115919          iMinPos = pT->iPos-pT->iOff;
115920          pTerm = pT;
115921        }
115922      }
115923
115924      if( !pTerm ){
115925        /* All offsets for this column have been gathered. */
115926        break;
115927      }else{
115928        assert( iCurrent<=iMinPos );
115929        if( 0==(0xFE&*pTerm->pList) ){
115930          pTerm->pList = 0;
115931        }else{
115932          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
115933        }
115934        while( rc==SQLITE_OK && iCurrent<iMinPos ){
115935          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
115936        }
115937        if( rc==SQLITE_OK ){
115938          char aBuffer[64];
115939          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
115940              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
115941          );
115942          rc = fts3StringAppend(&res, aBuffer, -1);
115943        }else if( rc==SQLITE_DONE ){
115944          rc = SQLITE_CORRUPT;
115945        }
115946      }
115947    }
115948    if( rc==SQLITE_DONE ){
115949      rc = SQLITE_OK;
115950    }
115951
115952    pMod->xClose(pC);
115953    if( rc!=SQLITE_OK ) goto offsets_out;
115954  }
115955
115956 offsets_out:
115957  sqlite3_free(sCtx.aTerm);
115958  assert( rc!=SQLITE_DONE );
115959  if( rc!=SQLITE_OK ){
115960    sqlite3_result_error_code(pCtx,  rc);
115961    sqlite3_free(res.z);
115962  }else{
115963    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
115964  }
115965  return;
115966}
115967
115968/*
115969** Implementation of matchinfo() function.
115970*/
115971SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
115972  int rc;
115973  if( !pCsr->pExpr ){
115974    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
115975    return;
115976  }
115977  rc = fts3GetMatchinfo(pCsr);
115978  if( rc!=SQLITE_OK ){
115979    sqlite3_result_error_code(pContext, rc);
115980  }else{
115981    Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
115982    int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*3);
115983    if( pTab->bHasDocsize ){
115984      n += sizeof(u32)*(1 + 2*pTab->nColumn);
115985    }
115986    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
115987  }
115988}
115989
115990#endif
115991
115992/************** End of fts3_snippet.c ****************************************/
115993/************** Begin file rtree.c *******************************************/
115994/*
115995** 2001 September 15
115996**
115997** The author disclaims copyright to this source code.  In place of
115998** a legal notice, here is a blessing:
115999**
116000**    May you do good and not evil.
116001**    May you find forgiveness for yourself and forgive others.
116002**    May you share freely, never taking more than you give.
116003**
116004*************************************************************************
116005** This file contains code for implementations of the r-tree and r*-tree
116006** algorithms packaged as an SQLite virtual table module.
116007*/
116008
116009#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
116010
116011/*
116012** This file contains an implementation of a couple of different variants
116013** of the r-tree algorithm. See the README file for further details. The
116014** same data-structure is used for all, but the algorithms for insert and
116015** delete operations vary. The variants used are selected at compile time
116016** by defining the following symbols:
116017*/
116018
116019/* Either, both or none of the following may be set to activate
116020** r*tree variant algorithms.
116021*/
116022#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
116023#define VARIANT_RSTARTREE_REINSERT      1
116024
116025/*
116026** Exactly one of the following must be set to 1.
116027*/
116028#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
116029#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
116030#define VARIANT_RSTARTREE_SPLIT         1
116031
116032#define VARIANT_GUTTMAN_SPLIT \
116033        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
116034
116035#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
116036  #define PickNext QuadraticPickNext
116037  #define PickSeeds QuadraticPickSeeds
116038  #define AssignCells splitNodeGuttman
116039#endif
116040#if VARIANT_GUTTMAN_LINEAR_SPLIT
116041  #define PickNext LinearPickNext
116042  #define PickSeeds LinearPickSeeds
116043  #define AssignCells splitNodeGuttman
116044#endif
116045#if VARIANT_RSTARTREE_SPLIT
116046  #define AssignCells splitNodeStartree
116047#endif
116048
116049
116050#ifndef SQLITE_CORE
116051  SQLITE_EXTENSION_INIT1
116052#else
116053#endif
116054
116055
116056#ifndef SQLITE_AMALGAMATION
116057typedef sqlite3_int64 i64;
116058typedef unsigned char u8;
116059typedef unsigned int u32;
116060#endif
116061
116062typedef struct Rtree Rtree;
116063typedef struct RtreeCursor RtreeCursor;
116064typedef struct RtreeNode RtreeNode;
116065typedef struct RtreeCell RtreeCell;
116066typedef struct RtreeConstraint RtreeConstraint;
116067typedef union RtreeCoord RtreeCoord;
116068
116069/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
116070#define RTREE_MAX_DIMENSIONS 5
116071
116072/* Size of hash table Rtree.aHash. This hash table is not expected to
116073** ever contain very many entries, so a fixed number of buckets is
116074** used.
116075*/
116076#define HASHSIZE 128
116077
116078/*
116079** An rtree virtual-table object.
116080*/
116081struct Rtree {
116082  sqlite3_vtab base;
116083  sqlite3 *db;                /* Host database connection */
116084  int iNodeSize;              /* Size in bytes of each node in the node table */
116085  int nDim;                   /* Number of dimensions */
116086  int nBytesPerCell;          /* Bytes consumed per cell */
116087  int iDepth;                 /* Current depth of the r-tree structure */
116088  char *zDb;                  /* Name of database containing r-tree table */
116089  char *zName;                /* Name of r-tree table */
116090  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
116091  int nBusy;                  /* Current number of users of this structure */
116092
116093  /* List of nodes removed during a CondenseTree operation. List is
116094  ** linked together via the pointer normally used for hash chains -
116095  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
116096  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
116097  */
116098  RtreeNode *pDeleted;
116099  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
116100
116101  /* Statements to read/write/delete a record from xxx_node */
116102  sqlite3_stmt *pReadNode;
116103  sqlite3_stmt *pWriteNode;
116104  sqlite3_stmt *pDeleteNode;
116105
116106  /* Statements to read/write/delete a record from xxx_rowid */
116107  sqlite3_stmt *pReadRowid;
116108  sqlite3_stmt *pWriteRowid;
116109  sqlite3_stmt *pDeleteRowid;
116110
116111  /* Statements to read/write/delete a record from xxx_parent */
116112  sqlite3_stmt *pReadParent;
116113  sqlite3_stmt *pWriteParent;
116114  sqlite3_stmt *pDeleteParent;
116115
116116  int eCoordType;
116117};
116118
116119/* Possible values for eCoordType: */
116120#define RTREE_COORD_REAL32 0
116121#define RTREE_COORD_INT32  1
116122
116123/*
116124** The minimum number of cells allowed for a node is a third of the
116125** maximum. In Gutman's notation:
116126**
116127**     m = M/3
116128**
116129** If an R*-tree "Reinsert" operation is required, the same number of
116130** cells are removed from the overfull node and reinserted into the tree.
116131*/
116132#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
116133#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
116134#define RTREE_MAXCELLS 51
116135
116136/*
116137** An rtree cursor object.
116138*/
116139struct RtreeCursor {
116140  sqlite3_vtab_cursor base;
116141  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
116142  int iCell;                        /* Index of current cell in pNode */
116143  int iStrategy;                    /* Copy of idxNum search parameter */
116144  int nConstraint;                  /* Number of entries in aConstraint */
116145  RtreeConstraint *aConstraint;     /* Search constraints. */
116146};
116147
116148union RtreeCoord {
116149  float f;
116150  int i;
116151};
116152
116153/*
116154** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
116155** formatted as a double. This macro assumes that local variable pRtree points
116156** to the Rtree structure associated with the RtreeCoord.
116157*/
116158#define DCOORD(coord) (                           \
116159  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
116160    ((double)coord.f) :                           \
116161    ((double)coord.i)                             \
116162)
116163
116164/*
116165** A search constraint.
116166*/
116167struct RtreeConstraint {
116168  int iCoord;                       /* Index of constrained coordinate */
116169  int op;                           /* Constraining operation */
116170  double rValue;                    /* Constraint value. */
116171};
116172
116173/* Possible values for RtreeConstraint.op */
116174#define RTREE_EQ 0x41
116175#define RTREE_LE 0x42
116176#define RTREE_LT 0x43
116177#define RTREE_GE 0x44
116178#define RTREE_GT 0x45
116179
116180/*
116181** An rtree structure node.
116182**
116183** Data format (RtreeNode.zData):
116184**
116185**   1. If the node is the root node (node 1), then the first 2 bytes
116186**      of the node contain the tree depth as a big-endian integer.
116187**      For non-root nodes, the first 2 bytes are left unused.
116188**
116189**   2. The next 2 bytes contain the number of entries currently
116190**      stored in the node.
116191**
116192**   3. The remainder of the node contains the node entries. Each entry
116193**      consists of a single 8-byte integer followed by an even number
116194**      of 4-byte coordinates. For leaf nodes the integer is the rowid
116195**      of a record. For internal nodes it is the node number of a
116196**      child page.
116197*/
116198struct RtreeNode {
116199  RtreeNode *pParent;               /* Parent node */
116200  i64 iNode;
116201  int nRef;
116202  int isDirty;
116203  u8 *zData;
116204  RtreeNode *pNext;                 /* Next node in this hash chain */
116205};
116206#define NCELL(pNode) readInt16(&(pNode)->zData[2])
116207
116208/*
116209** Structure to store a deserialized rtree record.
116210*/
116211struct RtreeCell {
116212  i64 iRowid;
116213  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
116214};
116215
116216#ifndef MAX
116217# define MAX(x,y) ((x) < (y) ? (y) : (x))
116218#endif
116219#ifndef MIN
116220# define MIN(x,y) ((x) > (y) ? (y) : (x))
116221#endif
116222
116223/*
116224** Functions to deserialize a 16 bit integer, 32 bit real number and
116225** 64 bit integer. The deserialized value is returned.
116226*/
116227static int readInt16(u8 *p){
116228  return (p[0]<<8) + p[1];
116229}
116230static void readCoord(u8 *p, RtreeCoord *pCoord){
116231  u32 i = (
116232    (((u32)p[0]) << 24) +
116233    (((u32)p[1]) << 16) +
116234    (((u32)p[2]) <<  8) +
116235    (((u32)p[3]) <<  0)
116236  );
116237  *(u32 *)pCoord = i;
116238}
116239static i64 readInt64(u8 *p){
116240  return (
116241    (((i64)p[0]) << 56) +
116242    (((i64)p[1]) << 48) +
116243    (((i64)p[2]) << 40) +
116244    (((i64)p[3]) << 32) +
116245    (((i64)p[4]) << 24) +
116246    (((i64)p[5]) << 16) +
116247    (((i64)p[6]) <<  8) +
116248    (((i64)p[7]) <<  0)
116249  );
116250}
116251
116252/*
116253** Functions to serialize a 16 bit integer, 32 bit real number and
116254** 64 bit integer. The value returned is the number of bytes written
116255** to the argument buffer (always 2, 4 and 8 respectively).
116256*/
116257static int writeInt16(u8 *p, int i){
116258  p[0] = (i>> 8)&0xFF;
116259  p[1] = (i>> 0)&0xFF;
116260  return 2;
116261}
116262static int writeCoord(u8 *p, RtreeCoord *pCoord){
116263  u32 i;
116264  assert( sizeof(RtreeCoord)==4 );
116265  assert( sizeof(u32)==4 );
116266  i = *(u32 *)pCoord;
116267  p[0] = (i>>24)&0xFF;
116268  p[1] = (i>>16)&0xFF;
116269  p[2] = (i>> 8)&0xFF;
116270  p[3] = (i>> 0)&0xFF;
116271  return 4;
116272}
116273static int writeInt64(u8 *p, i64 i){
116274  p[0] = (i>>56)&0xFF;
116275  p[1] = (i>>48)&0xFF;
116276  p[2] = (i>>40)&0xFF;
116277  p[3] = (i>>32)&0xFF;
116278  p[4] = (i>>24)&0xFF;
116279  p[5] = (i>>16)&0xFF;
116280  p[6] = (i>> 8)&0xFF;
116281  p[7] = (i>> 0)&0xFF;
116282  return 8;
116283}
116284
116285/*
116286** Increment the reference count of node p.
116287*/
116288static void nodeReference(RtreeNode *p){
116289  if( p ){
116290    p->nRef++;
116291  }
116292}
116293
116294/*
116295** Clear the content of node p (set all bytes to 0x00).
116296*/
116297static void nodeZero(Rtree *pRtree, RtreeNode *p){
116298  if( p ){
116299    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
116300    p->isDirty = 1;
116301  }
116302}
116303
116304/*
116305** Given a node number iNode, return the corresponding key to use
116306** in the Rtree.aHash table.
116307*/
116308static int nodeHash(i64 iNode){
116309  return (
116310    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
116311    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
116312  ) % HASHSIZE;
116313}
116314
116315/*
116316** Search the node hash table for node iNode. If found, return a pointer
116317** to it. Otherwise, return 0.
116318*/
116319static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
116320  RtreeNode *p;
116321  assert( iNode!=0 );
116322  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
116323  return p;
116324}
116325
116326/*
116327** Add node pNode to the node hash table.
116328*/
116329static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
116330  if( pNode ){
116331    int iHash;
116332    assert( pNode->pNext==0 );
116333    iHash = nodeHash(pNode->iNode);
116334    pNode->pNext = pRtree->aHash[iHash];
116335    pRtree->aHash[iHash] = pNode;
116336  }
116337}
116338
116339/*
116340** Remove node pNode from the node hash table.
116341*/
116342static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
116343  RtreeNode **pp;
116344  if( pNode->iNode!=0 ){
116345    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
116346    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
116347    *pp = pNode->pNext;
116348    pNode->pNext = 0;
116349  }
116350}
116351
116352/*
116353** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
116354** indicating that node has not yet been assigned a node number. It is
116355** assigned a node number when nodeWrite() is called to write the
116356** node contents out to the database.
116357*/
116358static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
116359  RtreeNode *pNode;
116360  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
116361  if( pNode ){
116362    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
116363    pNode->zData = (u8 *)&pNode[1];
116364    pNode->nRef = 1;
116365    pNode->pParent = pParent;
116366    pNode->isDirty = 1;
116367    nodeReference(pParent);
116368  }
116369  return pNode;
116370}
116371
116372/*
116373** Obtain a reference to an r-tree node.
116374*/
116375static int
116376nodeAcquire(
116377  Rtree *pRtree,             /* R-tree structure */
116378  i64 iNode,                 /* Node number to load */
116379  RtreeNode *pParent,        /* Either the parent node or NULL */
116380  RtreeNode **ppNode         /* OUT: Acquired node */
116381){
116382  int rc;
116383  RtreeNode *pNode;
116384
116385  /* Check if the requested node is already in the hash table. If so,
116386  ** increase its reference count and return it.
116387  */
116388  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
116389    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
116390    if( pParent && !pNode->pParent ){
116391      nodeReference(pParent);
116392      pNode->pParent = pParent;
116393    }
116394    pNode->nRef++;
116395    *ppNode = pNode;
116396    return SQLITE_OK;
116397  }
116398
116399  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
116400  if( !pNode ){
116401    *ppNode = 0;
116402    return SQLITE_NOMEM;
116403  }
116404  pNode->pParent = pParent;
116405  pNode->zData = (u8 *)&pNode[1];
116406  pNode->nRef = 1;
116407  pNode->iNode = iNode;
116408  pNode->isDirty = 0;
116409  pNode->pNext = 0;
116410
116411  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
116412  rc = sqlite3_step(pRtree->pReadNode);
116413  if( rc==SQLITE_ROW ){
116414    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
116415    assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
116416    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
116417    nodeReference(pParent);
116418  }else{
116419    sqlite3_free(pNode);
116420    pNode = 0;
116421  }
116422
116423  *ppNode = pNode;
116424  rc = sqlite3_reset(pRtree->pReadNode);
116425
116426  if( rc==SQLITE_OK && iNode==1 ){
116427    pRtree->iDepth = readInt16(pNode->zData);
116428  }
116429
116430  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
116431  nodeHashInsert(pRtree, pNode);
116432
116433  return rc;
116434}
116435
116436/*
116437** Overwrite cell iCell of node pNode with the contents of pCell.
116438*/
116439static void nodeOverwriteCell(
116440  Rtree *pRtree,
116441  RtreeNode *pNode,
116442  RtreeCell *pCell,
116443  int iCell
116444){
116445  int ii;
116446  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
116447  p += writeInt64(p, pCell->iRowid);
116448  for(ii=0; ii<(pRtree->nDim*2); ii++){
116449    p += writeCoord(p, &pCell->aCoord[ii]);
116450  }
116451  pNode->isDirty = 1;
116452}
116453
116454/*
116455** Remove cell the cell with index iCell from node pNode.
116456*/
116457static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
116458  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
116459  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
116460  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
116461  memmove(pDst, pSrc, nByte);
116462  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
116463  pNode->isDirty = 1;
116464}
116465
116466/*
116467** Insert the contents of cell pCell into node pNode. If the insert
116468** is successful, return SQLITE_OK.
116469**
116470** If there is not enough free space in pNode, return SQLITE_FULL.
116471*/
116472static int
116473nodeInsertCell(
116474  Rtree *pRtree,
116475  RtreeNode *pNode,
116476  RtreeCell *pCell
116477){
116478  int nCell;                    /* Current number of cells in pNode */
116479  int nMaxCell;                 /* Maximum number of cells for pNode */
116480
116481  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
116482  nCell = NCELL(pNode);
116483
116484  assert(nCell<=nMaxCell);
116485
116486  if( nCell<nMaxCell ){
116487    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
116488    writeInt16(&pNode->zData[2], nCell+1);
116489    pNode->isDirty = 1;
116490  }
116491
116492  return (nCell==nMaxCell);
116493}
116494
116495/*
116496** If the node is dirty, write it out to the database.
116497*/
116498static int
116499nodeWrite(Rtree *pRtree, RtreeNode *pNode){
116500  int rc = SQLITE_OK;
116501  if( pNode->isDirty ){
116502    sqlite3_stmt *p = pRtree->pWriteNode;
116503    if( pNode->iNode ){
116504      sqlite3_bind_int64(p, 1, pNode->iNode);
116505    }else{
116506      sqlite3_bind_null(p, 1);
116507    }
116508    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
116509    sqlite3_step(p);
116510    pNode->isDirty = 0;
116511    rc = sqlite3_reset(p);
116512    if( pNode->iNode==0 && rc==SQLITE_OK ){
116513      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
116514      nodeHashInsert(pRtree, pNode);
116515    }
116516  }
116517  return rc;
116518}
116519
116520/*
116521** Release a reference to a node. If the node is dirty and the reference
116522** count drops to zero, the node data is written to the database.
116523*/
116524static int
116525nodeRelease(Rtree *pRtree, RtreeNode *pNode){
116526  int rc = SQLITE_OK;
116527  if( pNode ){
116528    assert( pNode->nRef>0 );
116529    pNode->nRef--;
116530    if( pNode->nRef==0 ){
116531      if( pNode->iNode==1 ){
116532        pRtree->iDepth = -1;
116533      }
116534      if( pNode->pParent ){
116535        rc = nodeRelease(pRtree, pNode->pParent);
116536      }
116537      if( rc==SQLITE_OK ){
116538        rc = nodeWrite(pRtree, pNode);
116539      }
116540      nodeHashDelete(pRtree, pNode);
116541      sqlite3_free(pNode);
116542    }
116543  }
116544  return rc;
116545}
116546
116547/*
116548** Return the 64-bit integer value associated with cell iCell of
116549** node pNode. If pNode is a leaf node, this is a rowid. If it is
116550** an internal node, then the 64-bit integer is a child page number.
116551*/
116552static i64 nodeGetRowid(
116553  Rtree *pRtree,
116554  RtreeNode *pNode,
116555  int iCell
116556){
116557  assert( iCell<NCELL(pNode) );
116558  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
116559}
116560
116561/*
116562** Return coordinate iCoord from cell iCell in node pNode.
116563*/
116564static void nodeGetCoord(
116565  Rtree *pRtree,
116566  RtreeNode *pNode,
116567  int iCell,
116568  int iCoord,
116569  RtreeCoord *pCoord           /* Space to write result to */
116570){
116571  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
116572}
116573
116574/*
116575** Deserialize cell iCell of node pNode. Populate the structure pointed
116576** to by pCell with the results.
116577*/
116578static void nodeGetCell(
116579  Rtree *pRtree,
116580  RtreeNode *pNode,
116581  int iCell,
116582  RtreeCell *pCell
116583){
116584  int ii;
116585  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
116586  for(ii=0; ii<pRtree->nDim*2; ii++){
116587    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
116588  }
116589}
116590
116591
116592/* Forward declaration for the function that does the work of
116593** the virtual table module xCreate() and xConnect() methods.
116594*/
116595static int rtreeInit(
116596  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
116597);
116598
116599/*
116600** Rtree virtual table module xCreate method.
116601*/
116602static int rtreeCreate(
116603  sqlite3 *db,
116604  void *pAux,
116605  int argc, const char *const*argv,
116606  sqlite3_vtab **ppVtab,
116607  char **pzErr
116608){
116609  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
116610}
116611
116612/*
116613** Rtree virtual table module xConnect method.
116614*/
116615static int rtreeConnect(
116616  sqlite3 *db,
116617  void *pAux,
116618  int argc, const char *const*argv,
116619  sqlite3_vtab **ppVtab,
116620  char **pzErr
116621){
116622  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
116623}
116624
116625/*
116626** Increment the r-tree reference count.
116627*/
116628static void rtreeReference(Rtree *pRtree){
116629  pRtree->nBusy++;
116630}
116631
116632/*
116633** Decrement the r-tree reference count. When the reference count reaches
116634** zero the structure is deleted.
116635*/
116636static void rtreeRelease(Rtree *pRtree){
116637  pRtree->nBusy--;
116638  if( pRtree->nBusy==0 ){
116639    sqlite3_finalize(pRtree->pReadNode);
116640    sqlite3_finalize(pRtree->pWriteNode);
116641    sqlite3_finalize(pRtree->pDeleteNode);
116642    sqlite3_finalize(pRtree->pReadRowid);
116643    sqlite3_finalize(pRtree->pWriteRowid);
116644    sqlite3_finalize(pRtree->pDeleteRowid);
116645    sqlite3_finalize(pRtree->pReadParent);
116646    sqlite3_finalize(pRtree->pWriteParent);
116647    sqlite3_finalize(pRtree->pDeleteParent);
116648    sqlite3_free(pRtree);
116649  }
116650}
116651
116652/*
116653** Rtree virtual table module xDisconnect method.
116654*/
116655static int rtreeDisconnect(sqlite3_vtab *pVtab){
116656  rtreeRelease((Rtree *)pVtab);
116657  return SQLITE_OK;
116658}
116659
116660/*
116661** Rtree virtual table module xDestroy method.
116662*/
116663static int rtreeDestroy(sqlite3_vtab *pVtab){
116664  Rtree *pRtree = (Rtree *)pVtab;
116665  int rc;
116666  char *zCreate = sqlite3_mprintf(
116667    "DROP TABLE '%q'.'%q_node';"
116668    "DROP TABLE '%q'.'%q_rowid';"
116669    "DROP TABLE '%q'.'%q_parent';",
116670    pRtree->zDb, pRtree->zName,
116671    pRtree->zDb, pRtree->zName,
116672    pRtree->zDb, pRtree->zName
116673  );
116674  if( !zCreate ){
116675    rc = SQLITE_NOMEM;
116676  }else{
116677    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
116678    sqlite3_free(zCreate);
116679  }
116680  if( rc==SQLITE_OK ){
116681    rtreeRelease(pRtree);
116682  }
116683
116684  return rc;
116685}
116686
116687/*
116688** Rtree virtual table module xOpen method.
116689*/
116690static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
116691  int rc = SQLITE_NOMEM;
116692  RtreeCursor *pCsr;
116693
116694  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
116695  if( pCsr ){
116696    memset(pCsr, 0, sizeof(RtreeCursor));
116697    pCsr->base.pVtab = pVTab;
116698    rc = SQLITE_OK;
116699  }
116700  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
116701
116702  return rc;
116703}
116704
116705/*
116706** Rtree virtual table module xClose method.
116707*/
116708static int rtreeClose(sqlite3_vtab_cursor *cur){
116709  Rtree *pRtree = (Rtree *)(cur->pVtab);
116710  int rc;
116711  RtreeCursor *pCsr = (RtreeCursor *)cur;
116712  sqlite3_free(pCsr->aConstraint);
116713  rc = nodeRelease(pRtree, pCsr->pNode);
116714  sqlite3_free(pCsr);
116715  return rc;
116716}
116717
116718/*
116719** Rtree virtual table module xEof method.
116720**
116721** Return non-zero if the cursor does not currently point to a valid
116722** record (i.e if the scan has finished), or zero otherwise.
116723*/
116724static int rtreeEof(sqlite3_vtab_cursor *cur){
116725  RtreeCursor *pCsr = (RtreeCursor *)cur;
116726  return (pCsr->pNode==0);
116727}
116728
116729/*
116730** Cursor pCursor currently points to a cell in a non-leaf page.
116731** Return true if the sub-tree headed by the cell is filtered
116732** (excluded) by the constraints in the pCursor->aConstraint[]
116733** array, or false otherwise.
116734*/
116735static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
116736  RtreeCell cell;
116737  int ii;
116738  int bRes = 0;
116739
116740  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
116741  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
116742    RtreeConstraint *p = &pCursor->aConstraint[ii];
116743    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
116744    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
116745
116746    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
116747        || p->op==RTREE_GT || p->op==RTREE_EQ
116748    );
116749
116750    switch( p->op ){
116751      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
116752      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
116753      case RTREE_EQ:
116754        bRes = (p->rValue>cell_max || p->rValue<cell_min);
116755        break;
116756    }
116757  }
116758
116759  return bRes;
116760}
116761
116762/*
116763** Return true if the cell that cursor pCursor currently points to
116764** would be filtered (excluded) by the constraints in the
116765** pCursor->aConstraint[] array, or false otherwise.
116766**
116767** This function assumes that the cell is part of a leaf node.
116768*/
116769static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
116770  RtreeCell cell;
116771  int ii;
116772
116773  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
116774  for(ii=0; ii<pCursor->nConstraint; ii++){
116775    RtreeConstraint *p = &pCursor->aConstraint[ii];
116776    double coord = DCOORD(cell.aCoord[p->iCoord]);
116777    int res;
116778    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
116779        || p->op==RTREE_GT || p->op==RTREE_EQ
116780    );
116781    switch( p->op ){
116782      case RTREE_LE: res = (coord<=p->rValue); break;
116783      case RTREE_LT: res = (coord<p->rValue);  break;
116784      case RTREE_GE: res = (coord>=p->rValue); break;
116785      case RTREE_GT: res = (coord>p->rValue);  break;
116786      case RTREE_EQ: res = (coord==p->rValue); break;
116787    }
116788
116789    if( !res ) return 1;
116790  }
116791
116792  return 0;
116793}
116794
116795/*
116796** Cursor pCursor currently points at a node that heads a sub-tree of
116797** height iHeight (if iHeight==0, then the node is a leaf). Descend
116798** to point to the left-most cell of the sub-tree that matches the
116799** configured constraints.
116800*/
116801static int descendToCell(
116802  Rtree *pRtree,
116803  RtreeCursor *pCursor,
116804  int iHeight,
116805  int *pEof                 /* OUT: Set to true if cannot descend */
116806){
116807  int isEof;
116808  int rc;
116809  int ii;
116810  RtreeNode *pChild;
116811  sqlite3_int64 iRowid;
116812
116813  RtreeNode *pSavedNode = pCursor->pNode;
116814  int iSavedCell = pCursor->iCell;
116815
116816  assert( iHeight>=0 );
116817
116818  if( iHeight==0 ){
116819    isEof = testRtreeEntry(pRtree, pCursor);
116820  }else{
116821    isEof = testRtreeCell(pRtree, pCursor);
116822  }
116823  if( isEof || iHeight==0 ){
116824    *pEof = isEof;
116825    return SQLITE_OK;
116826  }
116827
116828  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
116829  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
116830  if( rc!=SQLITE_OK ){
116831    return rc;
116832  }
116833
116834  nodeRelease(pRtree, pCursor->pNode);
116835  pCursor->pNode = pChild;
116836  isEof = 1;
116837  for(ii=0; isEof && ii<NCELL(pChild); ii++){
116838    pCursor->iCell = ii;
116839    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
116840    if( rc!=SQLITE_OK ){
116841      return rc;
116842    }
116843  }
116844
116845  if( isEof ){
116846    assert( pCursor->pNode==pChild );
116847    nodeReference(pSavedNode);
116848    nodeRelease(pRtree, pChild);
116849    pCursor->pNode = pSavedNode;
116850    pCursor->iCell = iSavedCell;
116851  }
116852
116853  *pEof = isEof;
116854  return SQLITE_OK;
116855}
116856
116857/*
116858** One of the cells in node pNode is guaranteed to have a 64-bit
116859** integer value equal to iRowid. Return the index of this cell.
116860*/
116861static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
116862  int ii;
116863  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
116864    assert( ii<(NCELL(pNode)-1) );
116865  }
116866  return ii;
116867}
116868
116869/*
116870** Return the index of the cell containing a pointer to node pNode
116871** in its parent. If pNode is the root node, return -1.
116872*/
116873static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
116874  RtreeNode *pParent = pNode->pParent;
116875  if( pParent ){
116876    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
116877  }
116878  return -1;
116879}
116880
116881/*
116882** Rtree virtual table module xNext method.
116883*/
116884static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
116885  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
116886  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116887  int rc = SQLITE_OK;
116888
116889  if( pCsr->iStrategy==1 ){
116890    /* This "scan" is a direct lookup by rowid. There is no next entry. */
116891    nodeRelease(pRtree, pCsr->pNode);
116892    pCsr->pNode = 0;
116893  }
116894
116895  else if( pCsr->pNode ){
116896    /* Move to the next entry that matches the configured constraints. */
116897    int iHeight = 0;
116898    while( pCsr->pNode ){
116899      RtreeNode *pNode = pCsr->pNode;
116900      int nCell = NCELL(pNode);
116901      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
116902        int isEof;
116903        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
116904        if( rc!=SQLITE_OK || !isEof ){
116905          return rc;
116906        }
116907      }
116908      pCsr->pNode = pNode->pParent;
116909      pCsr->iCell = nodeParentIndex(pRtree, pNode);
116910      nodeReference(pCsr->pNode);
116911      nodeRelease(pRtree, pNode);
116912      iHeight++;
116913    }
116914  }
116915
116916  return rc;
116917}
116918
116919/*
116920** Rtree virtual table module xRowid method.
116921*/
116922static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
116923  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
116924  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116925
116926  assert(pCsr->pNode);
116927  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
116928
116929  return SQLITE_OK;
116930}
116931
116932/*
116933** Rtree virtual table module xColumn method.
116934*/
116935static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
116936  Rtree *pRtree = (Rtree *)cur->pVtab;
116937  RtreeCursor *pCsr = (RtreeCursor *)cur;
116938
116939  if( i==0 ){
116940    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
116941    sqlite3_result_int64(ctx, iRowid);
116942  }else{
116943    RtreeCoord c;
116944    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
116945    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
116946      sqlite3_result_double(ctx, c.f);
116947    }else{
116948      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
116949      sqlite3_result_int(ctx, c.i);
116950    }
116951  }
116952
116953  return SQLITE_OK;
116954}
116955
116956/*
116957** Use nodeAcquire() to obtain the leaf node containing the record with
116958** rowid iRowid. If successful, set *ppLeaf to point to the node and
116959** return SQLITE_OK. If there is no such record in the table, set
116960** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
116961** to zero and return an SQLite error code.
116962*/
116963static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
116964  int rc;
116965  *ppLeaf = 0;
116966  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
116967  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
116968    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
116969    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
116970    sqlite3_reset(pRtree->pReadRowid);
116971  }else{
116972    rc = sqlite3_reset(pRtree->pReadRowid);
116973  }
116974  return rc;
116975}
116976
116977
116978/*
116979** Rtree virtual table module xFilter method.
116980*/
116981static int rtreeFilter(
116982  sqlite3_vtab_cursor *pVtabCursor,
116983  int idxNum, const char *idxStr,
116984  int argc, sqlite3_value **argv
116985){
116986  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
116987  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116988
116989  RtreeNode *pRoot = 0;
116990  int ii;
116991  int rc = SQLITE_OK;
116992
116993  rtreeReference(pRtree);
116994
116995  sqlite3_free(pCsr->aConstraint);
116996  pCsr->aConstraint = 0;
116997  pCsr->iStrategy = idxNum;
116998
116999  if( idxNum==1 ){
117000    /* Special case - lookup by rowid. */
117001    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
117002    i64 iRowid = sqlite3_value_int64(argv[0]);
117003    rc = findLeafNode(pRtree, iRowid, &pLeaf);
117004    pCsr->pNode = pLeaf;
117005    if( pLeaf && rc==SQLITE_OK ){
117006      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
117007    }
117008  }else{
117009    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
117010    ** with the configured constraints.
117011    */
117012    if( argc>0 ){
117013      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
117014      pCsr->nConstraint = argc;
117015      if( !pCsr->aConstraint ){
117016        rc = SQLITE_NOMEM;
117017      }else{
117018        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
117019        for(ii=0; ii<argc; ii++){
117020          RtreeConstraint *p = &pCsr->aConstraint[ii];
117021          p->op = idxStr[ii*2];
117022          p->iCoord = idxStr[ii*2+1]-'a';
117023          p->rValue = sqlite3_value_double(argv[ii]);
117024        }
117025      }
117026    }
117027
117028    if( rc==SQLITE_OK ){
117029      pCsr->pNode = 0;
117030      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
117031    }
117032    if( rc==SQLITE_OK ){
117033      int isEof = 1;
117034      int nCell = NCELL(pRoot);
117035      pCsr->pNode = pRoot;
117036      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
117037        assert( pCsr->pNode==pRoot );
117038        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
117039        if( !isEof ){
117040          break;
117041        }
117042      }
117043      if( rc==SQLITE_OK && isEof ){
117044        assert( pCsr->pNode==pRoot );
117045        nodeRelease(pRtree, pRoot);
117046        pCsr->pNode = 0;
117047      }
117048      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
117049    }
117050  }
117051
117052  rtreeRelease(pRtree);
117053  return rc;
117054}
117055
117056/*
117057** Rtree virtual table module xBestIndex method. There are three
117058** table scan strategies to choose from (in order from most to
117059** least desirable):
117060**
117061**   idxNum     idxStr        Strategy
117062**   ------------------------------------------------
117063**     1        Unused        Direct lookup by rowid.
117064**     2        See below     R-tree query or full-table scan.
117065**   ------------------------------------------------
117066**
117067** If strategy 1 is used, then idxStr is not meaningful. If strategy
117068** 2 is used, idxStr is formatted to contain 2 bytes for each
117069** constraint used. The first two bytes of idxStr correspond to
117070** the constraint in sqlite3_index_info.aConstraintUsage[] with
117071** (argvIndex==1) etc.
117072**
117073** The first of each pair of bytes in idxStr identifies the constraint
117074** operator as follows:
117075**
117076**   Operator    Byte Value
117077**   ----------------------
117078**      =        0x41 ('A')
117079**     <=        0x42 ('B')
117080**      <        0x43 ('C')
117081**     >=        0x44 ('D')
117082**      >        0x45 ('E')
117083**   ----------------------
117084**
117085** The second of each pair of bytes identifies the coordinate column
117086** to which the constraint applies. The leftmost coordinate column
117087** is 'a', the second from the left 'b' etc.
117088*/
117089static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
117090  int rc = SQLITE_OK;
117091  int ii, cCol;
117092
117093  int iIdx = 0;
117094  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
117095  memset(zIdxStr, 0, sizeof(zIdxStr));
117096
117097  assert( pIdxInfo->idxStr==0 );
117098  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
117099    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
117100
117101    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
117102      /* We have an equality constraint on the rowid. Use strategy 1. */
117103      int jj;
117104      for(jj=0; jj<ii; jj++){
117105        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
117106        pIdxInfo->aConstraintUsage[jj].omit = 0;
117107      }
117108      pIdxInfo->idxNum = 1;
117109      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
117110      pIdxInfo->aConstraintUsage[jj].omit = 1;
117111
117112      /* This strategy involves a two rowid lookups on an B-Tree structures
117113      ** and then a linear search of an R-Tree node. This should be
117114      ** considered almost as quick as a direct rowid lookup (for which
117115      ** sqlite uses an internal cost of 0.0).
117116      */
117117      pIdxInfo->estimatedCost = 10.0;
117118      return SQLITE_OK;
117119    }
117120
117121    if( p->usable && p->iColumn>0 ){
117122      u8 op = 0;
117123      switch( p->op ){
117124        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
117125        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
117126        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
117127        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
117128        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
117129      }
117130      if( op ){
117131        /* Make sure this particular constraint has not been used before.
117132        ** If it has been used before, ignore it.
117133        **
117134        ** A <= or < can be used if there is a prior >= or >.
117135        ** A >= or > can be used if there is a prior < or <=.
117136        ** A <= or < is disqualified if there is a prior <=, <, or ==.
117137        ** A >= or > is disqualified if there is a prior >=, >, or ==.
117138        ** A == is disqualifed if there is any prior constraint.
117139        */
117140        int j, opmsk;
117141        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
117142        assert( compatible[RTREE_EQ & 7]==0 );
117143        assert( compatible[RTREE_LT & 7]==1 );
117144        assert( compatible[RTREE_LE & 7]==1 );
117145        assert( compatible[RTREE_GT & 7]==2 );
117146        assert( compatible[RTREE_GE & 7]==2 );
117147        cCol = p->iColumn - 1 + 'a';
117148        opmsk = compatible[op & 7];
117149        for(j=0; j<iIdx; j+=2){
117150          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
117151            op = 0;
117152            break;
117153          }
117154        }
117155      }
117156      if( op ){
117157        assert( iIdx<sizeof(zIdxStr)-1 );
117158        zIdxStr[iIdx++] = op;
117159        zIdxStr[iIdx++] = cCol;
117160        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
117161        pIdxInfo->aConstraintUsage[ii].omit = 1;
117162      }
117163    }
117164  }
117165
117166  pIdxInfo->idxNum = 2;
117167  pIdxInfo->needToFreeIdxStr = 1;
117168  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
117169    return SQLITE_NOMEM;
117170  }
117171  assert( iIdx>=0 );
117172  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
117173  return rc;
117174}
117175
117176/*
117177** Return the N-dimensional volumn of the cell stored in *p.
117178*/
117179static float cellArea(Rtree *pRtree, RtreeCell *p){
117180  float area = 1.0;
117181  int ii;
117182  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117183    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
117184  }
117185  return area;
117186}
117187
117188/*
117189** Return the margin length of cell p. The margin length is the sum
117190** of the objects size in each dimension.
117191*/
117192static float cellMargin(Rtree *pRtree, RtreeCell *p){
117193  float margin = 0.0;
117194  int ii;
117195  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117196    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
117197  }
117198  return margin;
117199}
117200
117201/*
117202** Store the union of cells p1 and p2 in p1.
117203*/
117204static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
117205  int ii;
117206  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
117207    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117208      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
117209      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
117210    }
117211  }else{
117212    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117213      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
117214      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
117215    }
117216  }
117217}
117218
117219/*
117220** Return true if the area covered by p2 is a subset of the area covered
117221** by p1. False otherwise.
117222*/
117223static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
117224  int ii;
117225  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
117226  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
117227    RtreeCoord *a1 = &p1->aCoord[ii];
117228    RtreeCoord *a2 = &p2->aCoord[ii];
117229    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
117230     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
117231    ){
117232      return 0;
117233    }
117234  }
117235  return 1;
117236}
117237
117238/*
117239** Return the amount cell p would grow by if it were unioned with pCell.
117240*/
117241static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
117242  float area;
117243  RtreeCell cell;
117244  memcpy(&cell, p, sizeof(RtreeCell));
117245  area = cellArea(pRtree, &cell);
117246  cellUnion(pRtree, &cell, pCell);
117247  return (cellArea(pRtree, &cell)-area);
117248}
117249
117250#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
117251static float cellOverlap(
117252  Rtree *pRtree,
117253  RtreeCell *p,
117254  RtreeCell *aCell,
117255  int nCell,
117256  int iExclude
117257){
117258  int ii;
117259  float overlap = 0.0;
117260  for(ii=0; ii<nCell; ii++){
117261    if( ii!=iExclude ){
117262      int jj;
117263      float o = 1.0;
117264      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
117265        double x1;
117266        double x2;
117267
117268        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
117269        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
117270
117271        if( x2<x1 ){
117272          o = 0.0;
117273          break;
117274        }else{
117275          o = o * (x2-x1);
117276        }
117277      }
117278      overlap += o;
117279    }
117280  }
117281  return overlap;
117282}
117283#endif
117284
117285#if VARIANT_RSTARTREE_CHOOSESUBTREE
117286static float cellOverlapEnlargement(
117287  Rtree *pRtree,
117288  RtreeCell *p,
117289  RtreeCell *pInsert,
117290  RtreeCell *aCell,
117291  int nCell,
117292  int iExclude
117293){
117294  float before;
117295  float after;
117296  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
117297  cellUnion(pRtree, p, pInsert);
117298  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
117299  return after-before;
117300}
117301#endif
117302
117303
117304/*
117305** This function implements the ChooseLeaf algorithm from Gutman[84].
117306** ChooseSubTree in r*tree terminology.
117307*/
117308static int ChooseLeaf(
117309  Rtree *pRtree,               /* Rtree table */
117310  RtreeCell *pCell,            /* Cell to insert into rtree */
117311  int iHeight,                 /* Height of sub-tree rooted at pCell */
117312  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
117313){
117314  int rc;
117315  int ii;
117316  RtreeNode *pNode;
117317  rc = nodeAcquire(pRtree, 1, 0, &pNode);
117318
117319  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
117320    int iCell;
117321    sqlite3_int64 iBest;
117322
117323    float fMinGrowth;
117324    float fMinArea;
117325    float fMinOverlap;
117326
117327    int nCell = NCELL(pNode);
117328    RtreeCell cell;
117329    RtreeNode *pChild;
117330
117331    RtreeCell *aCell = 0;
117332
117333#if VARIANT_RSTARTREE_CHOOSESUBTREE
117334    if( ii==(pRtree->iDepth-1) ){
117335      int jj;
117336      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
117337      if( !aCell ){
117338        rc = SQLITE_NOMEM;
117339        nodeRelease(pRtree, pNode);
117340        pNode = 0;
117341        continue;
117342      }
117343      for(jj=0; jj<nCell; jj++){
117344        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
117345      }
117346    }
117347#endif
117348
117349    /* Select the child node which will be enlarged the least if pCell
117350    ** is inserted into it. Resolve ties by choosing the entry with
117351    ** the smallest area.
117352    */
117353    for(iCell=0; iCell<nCell; iCell++){
117354      float growth;
117355      float area;
117356      float overlap = 0.0;
117357      nodeGetCell(pRtree, pNode, iCell, &cell);
117358      growth = cellGrowth(pRtree, &cell, pCell);
117359      area = cellArea(pRtree, &cell);
117360#if VARIANT_RSTARTREE_CHOOSESUBTREE
117361      if( ii==(pRtree->iDepth-1) ){
117362        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
117363      }
117364#endif
117365      if( (iCell==0)
117366       || (overlap<fMinOverlap)
117367       || (overlap==fMinOverlap && growth<fMinGrowth)
117368       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
117369      ){
117370        fMinOverlap = overlap;
117371        fMinGrowth = growth;
117372        fMinArea = area;
117373        iBest = cell.iRowid;
117374      }
117375    }
117376
117377    sqlite3_free(aCell);
117378    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
117379    nodeRelease(pRtree, pNode);
117380    pNode = pChild;
117381  }
117382
117383  *ppLeaf = pNode;
117384  return rc;
117385}
117386
117387/*
117388** A cell with the same content as pCell has just been inserted into
117389** the node pNode. This function updates the bounding box cells in
117390** all ancestor elements.
117391*/
117392static void AdjustTree(
117393  Rtree *pRtree,                    /* Rtree table */
117394  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
117395  RtreeCell *pCell                  /* This cell was just inserted */
117396){
117397  RtreeNode *p = pNode;
117398  while( p->pParent ){
117399    RtreeCell cell;
117400    RtreeNode *pParent = p->pParent;
117401    int iCell = nodeParentIndex(pRtree, p);
117402
117403    nodeGetCell(pRtree, pParent, iCell, &cell);
117404    if( !cellContains(pRtree, &cell, pCell) ){
117405      cellUnion(pRtree, &cell, pCell);
117406      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
117407    }
117408
117409    p = pParent;
117410  }
117411}
117412
117413/*
117414** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
117415*/
117416static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
117417  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
117418  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
117419  sqlite3_step(pRtree->pWriteRowid);
117420  return sqlite3_reset(pRtree->pWriteRowid);
117421}
117422
117423/*
117424** Write mapping (iNode->iPar) to the <rtree>_parent table.
117425*/
117426static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
117427  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
117428  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
117429  sqlite3_step(pRtree->pWriteParent);
117430  return sqlite3_reset(pRtree->pWriteParent);
117431}
117432
117433static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
117434
117435#if VARIANT_GUTTMAN_LINEAR_SPLIT
117436/*
117437** Implementation of the linear variant of the PickNext() function from
117438** Guttman[84].
117439*/
117440static RtreeCell *LinearPickNext(
117441  Rtree *pRtree,
117442  RtreeCell *aCell,
117443  int nCell,
117444  RtreeCell *pLeftBox,
117445  RtreeCell *pRightBox,
117446  int *aiUsed
117447){
117448  int ii;
117449  for(ii=0; aiUsed[ii]; ii++);
117450  aiUsed[ii] = 1;
117451  return &aCell[ii];
117452}
117453
117454/*
117455** Implementation of the linear variant of the PickSeeds() function from
117456** Guttman[84].
117457*/
117458static void LinearPickSeeds(
117459  Rtree *pRtree,
117460  RtreeCell *aCell,
117461  int nCell,
117462  int *piLeftSeed,
117463  int *piRightSeed
117464){
117465  int i;
117466  int iLeftSeed = 0;
117467  int iRightSeed = 1;
117468  float maxNormalInnerWidth = 0.0;
117469
117470  /* Pick two "seed" cells from the array of cells. The algorithm used
117471  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
117472  ** indices of the two seed cells in the array are stored in local
117473  ** variables iLeftSeek and iRightSeed.
117474  */
117475  for(i=0; i<pRtree->nDim; i++){
117476    float x1 = DCOORD(aCell[0].aCoord[i*2]);
117477    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
117478    float x3 = x1;
117479    float x4 = x2;
117480    int jj;
117481
117482    int iCellLeft = 0;
117483    int iCellRight = 0;
117484
117485    for(jj=1; jj<nCell; jj++){
117486      float left = DCOORD(aCell[jj].aCoord[i*2]);
117487      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
117488
117489      if( left<x1 ) x1 = left;
117490      if( right>x4 ) x4 = right;
117491      if( left>x3 ){
117492        x3 = left;
117493        iCellRight = jj;
117494      }
117495      if( right<x2 ){
117496        x2 = right;
117497        iCellLeft = jj;
117498      }
117499    }
117500
117501    if( x4!=x1 ){
117502      float normalwidth = (x3 - x2) / (x4 - x1);
117503      if( normalwidth>maxNormalInnerWidth ){
117504        iLeftSeed = iCellLeft;
117505        iRightSeed = iCellRight;
117506      }
117507    }
117508  }
117509
117510  *piLeftSeed = iLeftSeed;
117511  *piRightSeed = iRightSeed;
117512}
117513#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
117514
117515#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
117516/*
117517** Implementation of the quadratic variant of the PickNext() function from
117518** Guttman[84].
117519*/
117520static RtreeCell *QuadraticPickNext(
117521  Rtree *pRtree,
117522  RtreeCell *aCell,
117523  int nCell,
117524  RtreeCell *pLeftBox,
117525  RtreeCell *pRightBox,
117526  int *aiUsed
117527){
117528  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
117529
117530  int iSelect = -1;
117531  float fDiff;
117532  int ii;
117533  for(ii=0; ii<nCell; ii++){
117534    if( aiUsed[ii]==0 ){
117535      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
117536      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
117537      float diff = FABS(right-left);
117538      if( iSelect<0 || diff>fDiff ){
117539        fDiff = diff;
117540        iSelect = ii;
117541      }
117542    }
117543  }
117544  aiUsed[iSelect] = 1;
117545  return &aCell[iSelect];
117546}
117547
117548/*
117549** Implementation of the quadratic variant of the PickSeeds() function from
117550** Guttman[84].
117551*/
117552static void QuadraticPickSeeds(
117553  Rtree *pRtree,
117554  RtreeCell *aCell,
117555  int nCell,
117556  int *piLeftSeed,
117557  int *piRightSeed
117558){
117559  int ii;
117560  int jj;
117561
117562  int iLeftSeed = 0;
117563  int iRightSeed = 1;
117564  float fWaste = 0.0;
117565
117566  for(ii=0; ii<nCell; ii++){
117567    for(jj=ii+1; jj<nCell; jj++){
117568      float right = cellArea(pRtree, &aCell[jj]);
117569      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
117570      float waste = growth - right;
117571
117572      if( waste>fWaste ){
117573        iLeftSeed = ii;
117574        iRightSeed = jj;
117575        fWaste = waste;
117576      }
117577    }
117578  }
117579
117580  *piLeftSeed = iLeftSeed;
117581  *piRightSeed = iRightSeed;
117582}
117583#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
117584
117585/*
117586** Arguments aIdx, aDistance and aSpare all point to arrays of size
117587** nIdx. The aIdx array contains the set of integers from 0 to
117588** (nIdx-1) in no particular order. This function sorts the values
117589** in aIdx according to the indexed values in aDistance. For
117590** example, assuming the inputs:
117591**
117592**   aIdx      = { 0,   1,   2,   3 }
117593**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
117594**
117595** this function sets the aIdx array to contain:
117596**
117597**   aIdx      = { 0,   1,   2,   3 }
117598**
117599** The aSpare array is used as temporary working space by the
117600** sorting algorithm.
117601*/
117602static void SortByDistance(
117603  int *aIdx,
117604  int nIdx,
117605  float *aDistance,
117606  int *aSpare
117607){
117608  if( nIdx>1 ){
117609    int iLeft = 0;
117610    int iRight = 0;
117611
117612    int nLeft = nIdx/2;
117613    int nRight = nIdx-nLeft;
117614    int *aLeft = aIdx;
117615    int *aRight = &aIdx[nLeft];
117616
117617    SortByDistance(aLeft, nLeft, aDistance, aSpare);
117618    SortByDistance(aRight, nRight, aDistance, aSpare);
117619
117620    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
117621    aLeft = aSpare;
117622
117623    while( iLeft<nLeft || iRight<nRight ){
117624      if( iLeft==nLeft ){
117625        aIdx[iLeft+iRight] = aRight[iRight];
117626        iRight++;
117627      }else if( iRight==nRight ){
117628        aIdx[iLeft+iRight] = aLeft[iLeft];
117629        iLeft++;
117630      }else{
117631        float fLeft = aDistance[aLeft[iLeft]];
117632        float fRight = aDistance[aRight[iRight]];
117633        if( fLeft<fRight ){
117634          aIdx[iLeft+iRight] = aLeft[iLeft];
117635          iLeft++;
117636        }else{
117637          aIdx[iLeft+iRight] = aRight[iRight];
117638          iRight++;
117639        }
117640      }
117641    }
117642
117643#if 0
117644    /* Check that the sort worked */
117645    {
117646      int jj;
117647      for(jj=1; jj<nIdx; jj++){
117648        float left = aDistance[aIdx[jj-1]];
117649        float right = aDistance[aIdx[jj]];
117650        assert( left<=right );
117651      }
117652    }
117653#endif
117654  }
117655}
117656
117657/*
117658** Arguments aIdx, aCell and aSpare all point to arrays of size
117659** nIdx. The aIdx array contains the set of integers from 0 to
117660** (nIdx-1) in no particular order. This function sorts the values
117661** in aIdx according to dimension iDim of the cells in aCell. The
117662** minimum value of dimension iDim is considered first, the
117663** maximum used to break ties.
117664**
117665** The aSpare array is used as temporary working space by the
117666** sorting algorithm.
117667*/
117668static void SortByDimension(
117669  Rtree *pRtree,
117670  int *aIdx,
117671  int nIdx,
117672  int iDim,
117673  RtreeCell *aCell,
117674  int *aSpare
117675){
117676  if( nIdx>1 ){
117677
117678    int iLeft = 0;
117679    int iRight = 0;
117680
117681    int nLeft = nIdx/2;
117682    int nRight = nIdx-nLeft;
117683    int *aLeft = aIdx;
117684    int *aRight = &aIdx[nLeft];
117685
117686    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
117687    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
117688
117689    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
117690    aLeft = aSpare;
117691    while( iLeft<nLeft || iRight<nRight ){
117692      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
117693      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
117694      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
117695      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
117696      if( (iLeft!=nLeft) && ((iRight==nRight)
117697       || (xleft1<xright1)
117698       || (xleft1==xright1 && xleft2<xright2)
117699      )){
117700        aIdx[iLeft+iRight] = aLeft[iLeft];
117701        iLeft++;
117702      }else{
117703        aIdx[iLeft+iRight] = aRight[iRight];
117704        iRight++;
117705      }
117706    }
117707
117708#if 0
117709    /* Check that the sort worked */
117710    {
117711      int jj;
117712      for(jj=1; jj<nIdx; jj++){
117713        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
117714        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
117715        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
117716        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
117717        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
117718      }
117719    }
117720#endif
117721  }
117722}
117723
117724#if VARIANT_RSTARTREE_SPLIT
117725/*
117726** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
117727*/
117728static int splitNodeStartree(
117729  Rtree *pRtree,
117730  RtreeCell *aCell,
117731  int nCell,
117732  RtreeNode *pLeft,
117733  RtreeNode *pRight,
117734  RtreeCell *pBboxLeft,
117735  RtreeCell *pBboxRight
117736){
117737  int **aaSorted;
117738  int *aSpare;
117739  int ii;
117740
117741  int iBestDim;
117742  int iBestSplit;
117743  float fBestMargin;
117744
117745  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
117746
117747  aaSorted = (int **)sqlite3_malloc(nByte);
117748  if( !aaSorted ){
117749    return SQLITE_NOMEM;
117750  }
117751
117752  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
117753  memset(aaSorted, 0, nByte);
117754  for(ii=0; ii<pRtree->nDim; ii++){
117755    int jj;
117756    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
117757    for(jj=0; jj<nCell; jj++){
117758      aaSorted[ii][jj] = jj;
117759    }
117760    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
117761  }
117762
117763  for(ii=0; ii<pRtree->nDim; ii++){
117764    float margin = 0.0;
117765    float fBestOverlap;
117766    float fBestArea;
117767    int iBestLeft;
117768    int nLeft;
117769
117770    for(
117771      nLeft=RTREE_MINCELLS(pRtree);
117772      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
117773      nLeft++
117774    ){
117775      RtreeCell left;
117776      RtreeCell right;
117777      int kk;
117778      float overlap;
117779      float area;
117780
117781      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
117782      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
117783      for(kk=1; kk<(nCell-1); kk++){
117784        if( kk<nLeft ){
117785          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
117786        }else{
117787          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
117788        }
117789      }
117790      margin += cellMargin(pRtree, &left);
117791      margin += cellMargin(pRtree, &right);
117792      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
117793      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
117794      if( (nLeft==RTREE_MINCELLS(pRtree))
117795       || (overlap<fBestOverlap)
117796       || (overlap==fBestOverlap && area<fBestArea)
117797      ){
117798        iBestLeft = nLeft;
117799        fBestOverlap = overlap;
117800        fBestArea = area;
117801      }
117802    }
117803
117804    if( ii==0 || margin<fBestMargin ){
117805      iBestDim = ii;
117806      fBestMargin = margin;
117807      iBestSplit = iBestLeft;
117808    }
117809  }
117810
117811  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
117812  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
117813  for(ii=0; ii<nCell; ii++){
117814    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
117815    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
117816    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
117817    nodeInsertCell(pRtree, pTarget, pCell);
117818    cellUnion(pRtree, pBbox, pCell);
117819  }
117820
117821  sqlite3_free(aaSorted);
117822  return SQLITE_OK;
117823}
117824#endif
117825
117826#if VARIANT_GUTTMAN_SPLIT
117827/*
117828** Implementation of the regular R-tree SplitNode from Guttman[1984].
117829*/
117830static int splitNodeGuttman(
117831  Rtree *pRtree,
117832  RtreeCell *aCell,
117833  int nCell,
117834  RtreeNode *pLeft,
117835  RtreeNode *pRight,
117836  RtreeCell *pBboxLeft,
117837  RtreeCell *pBboxRight
117838){
117839  int iLeftSeed = 0;
117840  int iRightSeed = 1;
117841  int *aiUsed;
117842  int i;
117843
117844  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
117845  if( !aiUsed ){
117846    return SQLITE_NOMEM;
117847  }
117848  memset(aiUsed, 0, sizeof(int)*nCell);
117849
117850  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
117851
117852  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
117853  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
117854  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
117855  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
117856  aiUsed[iLeftSeed] = 1;
117857  aiUsed[iRightSeed] = 1;
117858
117859  for(i=nCell-2; i>0; i--){
117860    RtreeCell *pNext;
117861    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
117862    float diff =
117863      cellGrowth(pRtree, pBboxLeft, pNext) -
117864      cellGrowth(pRtree, pBboxRight, pNext)
117865    ;
117866    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
117867     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
117868    ){
117869      nodeInsertCell(pRtree, pRight, pNext);
117870      cellUnion(pRtree, pBboxRight, pNext);
117871    }else{
117872      nodeInsertCell(pRtree, pLeft, pNext);
117873      cellUnion(pRtree, pBboxLeft, pNext);
117874    }
117875  }
117876
117877  sqlite3_free(aiUsed);
117878  return SQLITE_OK;
117879}
117880#endif
117881
117882static int updateMapping(
117883  Rtree *pRtree,
117884  i64 iRowid,
117885  RtreeNode *pNode,
117886  int iHeight
117887){
117888  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
117889  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
117890  if( iHeight>0 ){
117891    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
117892    if( pChild ){
117893      nodeRelease(pRtree, pChild->pParent);
117894      nodeReference(pNode);
117895      pChild->pParent = pNode;
117896    }
117897  }
117898  return xSetMapping(pRtree, iRowid, pNode->iNode);
117899}
117900
117901static int SplitNode(
117902  Rtree *pRtree,
117903  RtreeNode *pNode,
117904  RtreeCell *pCell,
117905  int iHeight
117906){
117907  int i;
117908  int newCellIsRight = 0;
117909
117910  int rc = SQLITE_OK;
117911  int nCell = NCELL(pNode);
117912  RtreeCell *aCell;
117913  int *aiUsed;
117914
117915  RtreeNode *pLeft = 0;
117916  RtreeNode *pRight = 0;
117917
117918  RtreeCell leftbbox;
117919  RtreeCell rightbbox;
117920
117921  /* Allocate an array and populate it with a copy of pCell and
117922  ** all cells from node pLeft. Then zero the original node.
117923  */
117924  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
117925  if( !aCell ){
117926    rc = SQLITE_NOMEM;
117927    goto splitnode_out;
117928  }
117929  aiUsed = (int *)&aCell[nCell+1];
117930  memset(aiUsed, 0, sizeof(int)*(nCell+1));
117931  for(i=0; i<nCell; i++){
117932    nodeGetCell(pRtree, pNode, i, &aCell[i]);
117933  }
117934  nodeZero(pRtree, pNode);
117935  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
117936  nCell++;
117937
117938  if( pNode->iNode==1 ){
117939    pRight = nodeNew(pRtree, pNode, 1);
117940    pLeft = nodeNew(pRtree, pNode, 1);
117941    pRtree->iDepth++;
117942    pNode->isDirty = 1;
117943    writeInt16(pNode->zData, pRtree->iDepth);
117944  }else{
117945    pLeft = pNode;
117946    pRight = nodeNew(pRtree, pLeft->pParent, 1);
117947    nodeReference(pLeft);
117948  }
117949
117950  if( !pLeft || !pRight ){
117951    rc = SQLITE_NOMEM;
117952    goto splitnode_out;
117953  }
117954
117955  memset(pLeft->zData, 0, pRtree->iNodeSize);
117956  memset(pRight->zData, 0, pRtree->iNodeSize);
117957
117958  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
117959  if( rc!=SQLITE_OK ){
117960    goto splitnode_out;
117961  }
117962
117963  /* Ensure both child nodes have node numbers assigned to them. */
117964  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
117965   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
117966  ){
117967    goto splitnode_out;
117968  }
117969
117970  rightbbox.iRowid = pRight->iNode;
117971  leftbbox.iRowid = pLeft->iNode;
117972
117973  if( pNode->iNode==1 ){
117974    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
117975    if( rc!=SQLITE_OK ){
117976      goto splitnode_out;
117977    }
117978  }else{
117979    RtreeNode *pParent = pLeft->pParent;
117980    int iCell = nodeParentIndex(pRtree, pLeft);
117981    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
117982    AdjustTree(pRtree, pParent, &leftbbox);
117983  }
117984  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
117985    goto splitnode_out;
117986  }
117987
117988  for(i=0; i<NCELL(pRight); i++){
117989    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
117990    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
117991    if( iRowid==pCell->iRowid ){
117992      newCellIsRight = 1;
117993    }
117994    if( rc!=SQLITE_OK ){
117995      goto splitnode_out;
117996    }
117997  }
117998  if( pNode->iNode==1 ){
117999    for(i=0; i<NCELL(pLeft); i++){
118000      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
118001      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
118002      if( rc!=SQLITE_OK ){
118003        goto splitnode_out;
118004      }
118005    }
118006  }else if( newCellIsRight==0 ){
118007    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
118008  }
118009
118010  if( rc==SQLITE_OK ){
118011    rc = nodeRelease(pRtree, pRight);
118012    pRight = 0;
118013  }
118014  if( rc==SQLITE_OK ){
118015    rc = nodeRelease(pRtree, pLeft);
118016    pLeft = 0;
118017  }
118018
118019splitnode_out:
118020  nodeRelease(pRtree, pRight);
118021  nodeRelease(pRtree, pLeft);
118022  sqlite3_free(aCell);
118023  return rc;
118024}
118025
118026static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
118027  int rc = SQLITE_OK;
118028  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
118029    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
118030    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
118031      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
118032      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
118033    }else{
118034      rc = SQLITE_ERROR;
118035    }
118036    sqlite3_reset(pRtree->pReadParent);
118037    if( rc==SQLITE_OK ){
118038      rc = fixLeafParent(pRtree, pLeaf->pParent);
118039    }
118040  }
118041  return rc;
118042}
118043
118044static int deleteCell(Rtree *, RtreeNode *, int, int);
118045
118046static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
118047  int rc;
118048  RtreeNode *pParent;
118049  int iCell;
118050
118051  assert( pNode->nRef==1 );
118052
118053  /* Remove the entry in the parent cell. */
118054  iCell = nodeParentIndex(pRtree, pNode);
118055  pParent = pNode->pParent;
118056  pNode->pParent = 0;
118057  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
118058   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
118059  ){
118060    return rc;
118061  }
118062
118063  /* Remove the xxx_node entry. */
118064  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
118065  sqlite3_step(pRtree->pDeleteNode);
118066  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
118067    return rc;
118068  }
118069
118070  /* Remove the xxx_parent entry. */
118071  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
118072  sqlite3_step(pRtree->pDeleteParent);
118073  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
118074    return rc;
118075  }
118076
118077  /* Remove the node from the in-memory hash table and link it into
118078  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
118079  */
118080  nodeHashDelete(pRtree, pNode);
118081  pNode->iNode = iHeight;
118082  pNode->pNext = pRtree->pDeleted;
118083  pNode->nRef++;
118084  pRtree->pDeleted = pNode;
118085
118086  return SQLITE_OK;
118087}
118088
118089static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
118090  RtreeNode *pParent = pNode->pParent;
118091  if( pParent ){
118092    int ii;
118093    int nCell = NCELL(pNode);
118094    RtreeCell box;                            /* Bounding box for pNode */
118095    nodeGetCell(pRtree, pNode, 0, &box);
118096    for(ii=1; ii<nCell; ii++){
118097      RtreeCell cell;
118098      nodeGetCell(pRtree, pNode, ii, &cell);
118099      cellUnion(pRtree, &box, &cell);
118100    }
118101    box.iRowid = pNode->iNode;
118102    ii = nodeParentIndex(pRtree, pNode);
118103    nodeOverwriteCell(pRtree, pParent, &box, ii);
118104    fixBoundingBox(pRtree, pParent);
118105  }
118106}
118107
118108/*
118109** Delete the cell at index iCell of node pNode. After removing the
118110** cell, adjust the r-tree data structure if required.
118111*/
118112static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
118113  int rc;
118114
118115  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
118116    return rc;
118117  }
118118
118119  /* Remove the cell from the node. This call just moves bytes around
118120  ** the in-memory node image, so it cannot fail.
118121  */
118122  nodeDeleteCell(pRtree, pNode, iCell);
118123
118124  /* If the node is not the tree root and now has less than the minimum
118125  ** number of cells, remove it from the tree. Otherwise, update the
118126  ** cell in the parent node so that it tightly contains the updated
118127  ** node.
118128  */
118129  if( pNode->iNode!=1 ){
118130    RtreeNode *pParent = pNode->pParent;
118131    if( (pParent->iNode!=1 || NCELL(pParent)!=1)
118132     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
118133    ){
118134      rc = removeNode(pRtree, pNode, iHeight);
118135    }else{
118136      fixBoundingBox(pRtree, pNode);
118137    }
118138  }
118139
118140  return rc;
118141}
118142
118143static int Reinsert(
118144  Rtree *pRtree,
118145  RtreeNode *pNode,
118146  RtreeCell *pCell,
118147  int iHeight
118148){
118149  int *aOrder;
118150  int *aSpare;
118151  RtreeCell *aCell;
118152  float *aDistance;
118153  int nCell;
118154  float aCenterCoord[RTREE_MAX_DIMENSIONS];
118155  int iDim;
118156  int ii;
118157  int rc = SQLITE_OK;
118158
118159  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
118160
118161  nCell = NCELL(pNode)+1;
118162
118163  /* Allocate the buffers used by this operation. The allocation is
118164  ** relinquished before this function returns.
118165  */
118166  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
118167    sizeof(RtreeCell) +         /* aCell array */
118168    sizeof(int)       +         /* aOrder array */
118169    sizeof(int)       +         /* aSpare array */
118170    sizeof(float)               /* aDistance array */
118171  ));
118172  if( !aCell ){
118173    return SQLITE_NOMEM;
118174  }
118175  aOrder    = (int *)&aCell[nCell];
118176  aSpare    = (int *)&aOrder[nCell];
118177  aDistance = (float *)&aSpare[nCell];
118178
118179  for(ii=0; ii<nCell; ii++){
118180    if( ii==(nCell-1) ){
118181      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
118182    }else{
118183      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
118184    }
118185    aOrder[ii] = ii;
118186    for(iDim=0; iDim<pRtree->nDim; iDim++){
118187      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
118188      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
118189    }
118190  }
118191  for(iDim=0; iDim<pRtree->nDim; iDim++){
118192    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
118193  }
118194
118195  for(ii=0; ii<nCell; ii++){
118196    aDistance[ii] = 0.0;
118197    for(iDim=0; iDim<pRtree->nDim; iDim++){
118198      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
118199          DCOORD(aCell[ii].aCoord[iDim*2]);
118200      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
118201    }
118202  }
118203
118204  SortByDistance(aOrder, nCell, aDistance, aSpare);
118205  nodeZero(pRtree, pNode);
118206
118207  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
118208    RtreeCell *p = &aCell[aOrder[ii]];
118209    nodeInsertCell(pRtree, pNode, p);
118210    if( p->iRowid==pCell->iRowid ){
118211      if( iHeight==0 ){
118212        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
118213      }else{
118214        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
118215      }
118216    }
118217  }
118218  if( rc==SQLITE_OK ){
118219    fixBoundingBox(pRtree, pNode);
118220  }
118221  for(; rc==SQLITE_OK && ii<nCell; ii++){
118222    /* Find a node to store this cell in. pNode->iNode currently contains
118223    ** the height of the sub-tree headed by the cell.
118224    */
118225    RtreeNode *pInsert;
118226    RtreeCell *p = &aCell[aOrder[ii]];
118227    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
118228    if( rc==SQLITE_OK ){
118229      int rc2;
118230      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
118231      rc2 = nodeRelease(pRtree, pInsert);
118232      if( rc==SQLITE_OK ){
118233        rc = rc2;
118234      }
118235    }
118236  }
118237
118238  sqlite3_free(aCell);
118239  return rc;
118240}
118241
118242/*
118243** Insert cell pCell into node pNode. Node pNode is the head of a
118244** subtree iHeight high (leaf nodes have iHeight==0).
118245*/
118246static int rtreeInsertCell(
118247  Rtree *pRtree,
118248  RtreeNode *pNode,
118249  RtreeCell *pCell,
118250  int iHeight
118251){
118252  int rc = SQLITE_OK;
118253  if( iHeight>0 ){
118254    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
118255    if( pChild ){
118256      nodeRelease(pRtree, pChild->pParent);
118257      nodeReference(pNode);
118258      pChild->pParent = pNode;
118259    }
118260  }
118261  if( nodeInsertCell(pRtree, pNode, pCell) ){
118262#if VARIANT_RSTARTREE_REINSERT
118263    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
118264      rc = SplitNode(pRtree, pNode, pCell, iHeight);
118265    }else{
118266      pRtree->iReinsertHeight = iHeight;
118267      rc = Reinsert(pRtree, pNode, pCell, iHeight);
118268    }
118269#else
118270    rc = SplitNode(pRtree, pNode, pCell, iHeight);
118271#endif
118272  }else{
118273    AdjustTree(pRtree, pNode, pCell);
118274    if( iHeight==0 ){
118275      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
118276    }else{
118277      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
118278    }
118279  }
118280  return rc;
118281}
118282
118283static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
118284  int ii;
118285  int rc = SQLITE_OK;
118286  int nCell = NCELL(pNode);
118287
118288  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
118289    RtreeNode *pInsert;
118290    RtreeCell cell;
118291    nodeGetCell(pRtree, pNode, ii, &cell);
118292
118293    /* Find a node to store this cell in. pNode->iNode currently contains
118294    ** the height of the sub-tree headed by the cell.
118295    */
118296    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
118297    if( rc==SQLITE_OK ){
118298      int rc2;
118299      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
118300      rc2 = nodeRelease(pRtree, pInsert);
118301      if( rc==SQLITE_OK ){
118302        rc = rc2;
118303      }
118304    }
118305  }
118306  return rc;
118307}
118308
118309/*
118310** Select a currently unused rowid for a new r-tree record.
118311*/
118312static int newRowid(Rtree *pRtree, i64 *piRowid){
118313  int rc;
118314  sqlite3_bind_null(pRtree->pWriteRowid, 1);
118315  sqlite3_bind_null(pRtree->pWriteRowid, 2);
118316  sqlite3_step(pRtree->pWriteRowid);
118317  rc = sqlite3_reset(pRtree->pWriteRowid);
118318  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
118319  return rc;
118320}
118321
118322#ifndef NDEBUG
118323static int hashIsEmpty(Rtree *pRtree){
118324  int ii;
118325  for(ii=0; ii<HASHSIZE; ii++){
118326    assert( !pRtree->aHash[ii] );
118327  }
118328  return 1;
118329}
118330#endif
118331
118332/*
118333** The xUpdate method for rtree module virtual tables.
118334*/
118335static int rtreeUpdate(
118336  sqlite3_vtab *pVtab,
118337  int nData,
118338  sqlite3_value **azData,
118339  sqlite_int64 *pRowid
118340){
118341  Rtree *pRtree = (Rtree *)pVtab;
118342  int rc = SQLITE_OK;
118343
118344  rtreeReference(pRtree);
118345
118346  assert(nData>=1);
118347  assert(hashIsEmpty(pRtree));
118348
118349  /* If azData[0] is not an SQL NULL value, it is the rowid of a
118350  ** record to delete from the r-tree table. The following block does
118351  ** just that.
118352  */
118353  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
118354    i64 iDelete;                /* The rowid to delete */
118355    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
118356    int iCell;                  /* Index of iDelete cell in pLeaf */
118357    RtreeNode *pRoot;
118358
118359    /* Obtain a reference to the root node to initialise Rtree.iDepth */
118360    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
118361
118362    /* Obtain a reference to the leaf node that contains the entry
118363    ** about to be deleted.
118364    */
118365    if( rc==SQLITE_OK ){
118366      iDelete = sqlite3_value_int64(azData[0]);
118367      rc = findLeafNode(pRtree, iDelete, &pLeaf);
118368    }
118369
118370    /* Delete the cell in question from the leaf node. */
118371    if( rc==SQLITE_OK ){
118372      int rc2;
118373      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
118374      rc = deleteCell(pRtree, pLeaf, iCell, 0);
118375      rc2 = nodeRelease(pRtree, pLeaf);
118376      if( rc==SQLITE_OK ){
118377        rc = rc2;
118378      }
118379    }
118380
118381    /* Delete the corresponding entry in the <rtree>_rowid table. */
118382    if( rc==SQLITE_OK ){
118383      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
118384      sqlite3_step(pRtree->pDeleteRowid);
118385      rc = sqlite3_reset(pRtree->pDeleteRowid);
118386    }
118387
118388    /* Check if the root node now has exactly one child. If so, remove
118389    ** it, schedule the contents of the child for reinsertion and
118390    ** reduce the tree height by one.
118391    **
118392    ** This is equivalent to copying the contents of the child into
118393    ** the root node (the operation that Gutman's paper says to perform
118394    ** in this scenario).
118395    */
118396    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
118397      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
118398        RtreeNode *pChild;
118399        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
118400        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
118401        if( rc==SQLITE_OK ){
118402          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
118403        }
118404        if( rc==SQLITE_OK ){
118405          pRtree->iDepth--;
118406          writeInt16(pRoot->zData, pRtree->iDepth);
118407          pRoot->isDirty = 1;
118408        }
118409      }
118410    }
118411
118412    /* Re-insert the contents of any underfull nodes removed from the tree. */
118413    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
118414      if( rc==SQLITE_OK ){
118415        rc = reinsertNodeContent(pRtree, pLeaf);
118416      }
118417      pRtree->pDeleted = pLeaf->pNext;
118418      sqlite3_free(pLeaf);
118419    }
118420
118421    /* Release the reference to the root node. */
118422    if( rc==SQLITE_OK ){
118423      rc = nodeRelease(pRtree, pRoot);
118424    }else{
118425      nodeRelease(pRtree, pRoot);
118426    }
118427  }
118428
118429  /* If the azData[] array contains more than one element, elements
118430  ** (azData[2]..azData[argc-1]) contain a new record to insert into
118431  ** the r-tree structure.
118432  */
118433  if( rc==SQLITE_OK && nData>1 ){
118434    /* Insert a new record into the r-tree */
118435    RtreeCell cell;
118436    int ii;
118437    RtreeNode *pLeaf;
118438
118439    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
118440    assert( nData==(pRtree->nDim*2 + 3) );
118441    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
118442      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118443        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
118444        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
118445        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
118446          rc = SQLITE_CONSTRAINT;
118447          goto constraint;
118448        }
118449      }
118450    }else{
118451      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
118452        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
118453        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
118454        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
118455          rc = SQLITE_CONSTRAINT;
118456          goto constraint;
118457        }
118458      }
118459    }
118460
118461    /* Figure out the rowid of the new row. */
118462    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
118463      rc = newRowid(pRtree, &cell.iRowid);
118464    }else{
118465      cell.iRowid = sqlite3_value_int64(azData[2]);
118466      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
118467      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
118468        sqlite3_reset(pRtree->pReadRowid);
118469        rc = SQLITE_CONSTRAINT;
118470        goto constraint;
118471      }
118472      rc = sqlite3_reset(pRtree->pReadRowid);
118473    }
118474    *pRowid = cell.iRowid;
118475
118476    if( rc==SQLITE_OK ){
118477      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
118478    }
118479    if( rc==SQLITE_OK ){
118480      int rc2;
118481      pRtree->iReinsertHeight = -1;
118482      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
118483      rc2 = nodeRelease(pRtree, pLeaf);
118484      if( rc==SQLITE_OK ){
118485        rc = rc2;
118486      }
118487    }
118488  }
118489
118490constraint:
118491  rtreeRelease(pRtree);
118492  return rc;
118493}
118494
118495/*
118496** The xRename method for rtree module virtual tables.
118497*/
118498static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
118499  Rtree *pRtree = (Rtree *)pVtab;
118500  int rc = SQLITE_NOMEM;
118501  char *zSql = sqlite3_mprintf(
118502    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
118503    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
118504    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
118505    , pRtree->zDb, pRtree->zName, zNewName
118506    , pRtree->zDb, pRtree->zName, zNewName
118507    , pRtree->zDb, pRtree->zName, zNewName
118508  );
118509  if( zSql ){
118510    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
118511    sqlite3_free(zSql);
118512  }
118513  return rc;
118514}
118515
118516static sqlite3_module rtreeModule = {
118517  0,                         /* iVersion */
118518  rtreeCreate,                /* xCreate - create a table */
118519  rtreeConnect,               /* xConnect - connect to an existing table */
118520  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
118521  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
118522  rtreeDestroy,               /* xDestroy - Drop a table */
118523  rtreeOpen,                  /* xOpen - open a cursor */
118524  rtreeClose,                 /* xClose - close a cursor */
118525  rtreeFilter,                /* xFilter - configure scan constraints */
118526  rtreeNext,                  /* xNext - advance a cursor */
118527  rtreeEof,                   /* xEof */
118528  rtreeColumn,                /* xColumn - read data */
118529  rtreeRowid,                 /* xRowid - read data */
118530  rtreeUpdate,                /* xUpdate - write data */
118531  0,                          /* xBegin - begin transaction */
118532  0,                          /* xSync - sync transaction */
118533  0,                          /* xCommit - commit transaction */
118534  0,                          /* xRollback - rollback transaction */
118535  0,                          /* xFindFunction - function overloading */
118536  rtreeRename                 /* xRename - rename the table */
118537};
118538
118539static int rtreeSqlInit(
118540  Rtree *pRtree,
118541  sqlite3 *db,
118542  const char *zDb,
118543  const char *zPrefix,
118544  int isCreate
118545){
118546  int rc = SQLITE_OK;
118547
118548  #define N_STATEMENT 9
118549  static const char *azSql[N_STATEMENT] = {
118550    /* Read and write the xxx_node table */
118551    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
118552    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
118553    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
118554
118555    /* Read and write the xxx_rowid table */
118556    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
118557    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
118558    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
118559
118560    /* Read and write the xxx_parent table */
118561    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
118562    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
118563    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
118564  };
118565  sqlite3_stmt **appStmt[N_STATEMENT];
118566  int i;
118567
118568  pRtree->db = db;
118569
118570  if( isCreate ){
118571    char *zCreate = sqlite3_mprintf(
118572"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
118573"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
118574"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
118575"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
118576      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
118577    );
118578    if( !zCreate ){
118579      return SQLITE_NOMEM;
118580    }
118581    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
118582    sqlite3_free(zCreate);
118583    if( rc!=SQLITE_OK ){
118584      return rc;
118585    }
118586  }
118587
118588  appStmt[0] = &pRtree->pReadNode;
118589  appStmt[1] = &pRtree->pWriteNode;
118590  appStmt[2] = &pRtree->pDeleteNode;
118591  appStmt[3] = &pRtree->pReadRowid;
118592  appStmt[4] = &pRtree->pWriteRowid;
118593  appStmt[5] = &pRtree->pDeleteRowid;
118594  appStmt[6] = &pRtree->pReadParent;
118595  appStmt[7] = &pRtree->pWriteParent;
118596  appStmt[8] = &pRtree->pDeleteParent;
118597
118598  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
118599    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
118600    if( zSql ){
118601      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
118602    }else{
118603      rc = SQLITE_NOMEM;
118604    }
118605    sqlite3_free(zSql);
118606  }
118607
118608  return rc;
118609}
118610
118611/*
118612** The second argument to this function contains the text of an SQL statement
118613** that returns a single integer value. The statement is compiled and executed
118614** using database connection db. If successful, the integer value returned
118615** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
118616** code is returned and the value of *piVal after returning is not defined.
118617*/
118618static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
118619  int rc = SQLITE_NOMEM;
118620  if( zSql ){
118621    sqlite3_stmt *pStmt = 0;
118622    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
118623    if( rc==SQLITE_OK ){
118624      if( SQLITE_ROW==sqlite3_step(pStmt) ){
118625        *piVal = sqlite3_column_int(pStmt, 0);
118626      }
118627      rc = sqlite3_finalize(pStmt);
118628    }
118629  }
118630  return rc;
118631}
118632
118633/*
118634** This function is called from within the xConnect() or xCreate() method to
118635** determine the node-size used by the rtree table being created or connected
118636** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
118637** Otherwise, an SQLite error code is returned.
118638**
118639** If this function is being called as part of an xConnect(), then the rtree
118640** table already exists. In this case the node-size is determined by inspecting
118641** the root node of the tree.
118642**
118643** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
118644** This ensures that each node is stored on a single database page. If the
118645** database page-size is so large that more than RTREE_MAXCELLS entries
118646** would fit in a single node, use a smaller node-size.
118647*/
118648static int getNodeSize(
118649  sqlite3 *db,                    /* Database handle */
118650  Rtree *pRtree,                  /* Rtree handle */
118651  int isCreate                    /* True for xCreate, false for xConnect */
118652){
118653  int rc;
118654  char *zSql;
118655  if( isCreate ){
118656    int iPageSize;
118657    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
118658    rc = getIntFromStmt(db, zSql, &iPageSize);
118659    if( rc==SQLITE_OK ){
118660      pRtree->iNodeSize = iPageSize-64;
118661      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
118662        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
118663      }
118664    }
118665  }else{
118666    zSql = sqlite3_mprintf(
118667        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
118668        pRtree->zDb, pRtree->zName
118669    );
118670    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
118671  }
118672
118673  sqlite3_free(zSql);
118674  return rc;
118675}
118676
118677/*
118678** This function is the implementation of both the xConnect and xCreate
118679** methods of the r-tree virtual table.
118680**
118681**   argv[0]   -> module name
118682**   argv[1]   -> database name
118683**   argv[2]   -> table name
118684**   argv[...] -> column names...
118685*/
118686static int rtreeInit(
118687  sqlite3 *db,                        /* Database connection */
118688  void *pAux,                         /* One of the RTREE_COORD_* constants */
118689  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
118690  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
118691  char **pzErr,                       /* OUT: Error message, if any */
118692  int isCreate                        /* True for xCreate, false for xConnect */
118693){
118694  int rc = SQLITE_OK;
118695  Rtree *pRtree;
118696  int nDb;              /* Length of string argv[1] */
118697  int nName;            /* Length of string argv[2] */
118698  int eCoordType = (int)pAux;
118699
118700  const char *aErrMsg[] = {
118701    0,                                                    /* 0 */
118702    "Wrong number of columns for an rtree table",         /* 1 */
118703    "Too few columns for an rtree table",                 /* 2 */
118704    "Too many columns for an rtree table"                 /* 3 */
118705  };
118706
118707  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
118708  if( aErrMsg[iErr] ){
118709    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
118710    return SQLITE_ERROR;
118711  }
118712
118713  /* Allocate the sqlite3_vtab structure */
118714  nDb = strlen(argv[1]);
118715  nName = strlen(argv[2]);
118716  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
118717  if( !pRtree ){
118718    return SQLITE_NOMEM;
118719  }
118720  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
118721  pRtree->nBusy = 1;
118722  pRtree->base.pModule = &rtreeModule;
118723  pRtree->zDb = (char *)&pRtree[1];
118724  pRtree->zName = &pRtree->zDb[nDb+1];
118725  pRtree->nDim = (argc-4)/2;
118726  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
118727  pRtree->eCoordType = eCoordType;
118728  memcpy(pRtree->zDb, argv[1], nDb);
118729  memcpy(pRtree->zName, argv[2], nName);
118730
118731  /* Figure out the node size to use. */
118732  rc = getNodeSize(db, pRtree, isCreate);
118733
118734  /* Create/Connect to the underlying relational database schema. If
118735  ** that is successful, call sqlite3_declare_vtab() to configure
118736  ** the r-tree table schema.
118737  */
118738  if( rc==SQLITE_OK ){
118739    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
118740      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
118741    }else{
118742      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
118743      char *zTmp;
118744      int ii;
118745      for(ii=4; zSql && ii<argc; ii++){
118746        zTmp = zSql;
118747        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
118748        sqlite3_free(zTmp);
118749      }
118750      if( zSql ){
118751        zTmp = zSql;
118752        zSql = sqlite3_mprintf("%s);", zTmp);
118753        sqlite3_free(zTmp);
118754      }
118755      if( !zSql ){
118756        rc = SQLITE_NOMEM;
118757      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
118758        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
118759      }
118760      sqlite3_free(zSql);
118761    }
118762  }
118763
118764  if( rc==SQLITE_OK ){
118765    *ppVtab = (sqlite3_vtab *)pRtree;
118766  }else{
118767    rtreeRelease(pRtree);
118768  }
118769  return rc;
118770}
118771
118772
118773/*
118774** Implementation of a scalar function that decodes r-tree nodes to
118775** human readable strings. This can be used for debugging and analysis.
118776**
118777** The scalar function takes two arguments, a blob of data containing
118778** an r-tree node, and the number of dimensions the r-tree indexes.
118779** For a two-dimensional r-tree structure called "rt", to deserialize
118780** all nodes, a statement like:
118781**
118782**   SELECT rtreenode(2, data) FROM rt_node;
118783**
118784** The human readable string takes the form of a Tcl list with one
118785** entry for each cell in the r-tree node. Each entry is itself a
118786** list, containing the 8-byte rowid/pageno followed by the
118787** <num-dimension>*2 coordinates.
118788*/
118789static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
118790  char *zText = 0;
118791  RtreeNode node;
118792  Rtree tree;
118793  int ii;
118794
118795  memset(&node, 0, sizeof(RtreeNode));
118796  memset(&tree, 0, sizeof(Rtree));
118797  tree.nDim = sqlite3_value_int(apArg[0]);
118798  tree.nBytesPerCell = 8 + 8 * tree.nDim;
118799  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
118800
118801  for(ii=0; ii<NCELL(&node); ii++){
118802    char zCell[512];
118803    int nCell = 0;
118804    RtreeCell cell;
118805    int jj;
118806
118807    nodeGetCell(&tree, &node, ii, &cell);
118808    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
118809    nCell = strlen(zCell);
118810    for(jj=0; jj<tree.nDim*2; jj++){
118811      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
118812      nCell = strlen(zCell);
118813    }
118814
118815    if( zText ){
118816      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
118817      sqlite3_free(zText);
118818      zText = zTextNew;
118819    }else{
118820      zText = sqlite3_mprintf("{%s}", zCell);
118821    }
118822  }
118823
118824  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
118825}
118826
118827static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
118828  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
118829   || sqlite3_value_bytes(apArg[0])<2
118830  ){
118831    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
118832  }else{
118833    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
118834    sqlite3_result_int(ctx, readInt16(zBlob));
118835  }
118836}
118837
118838/*
118839** Register the r-tree module with database handle db. This creates the
118840** virtual table module "rtree" and the debugging/analysis scalar
118841** function "rtreenode".
118842*/
118843SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
118844  int rc = SQLITE_OK;
118845
118846  if( rc==SQLITE_OK ){
118847    int utf8 = SQLITE_UTF8;
118848    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
118849  }
118850  if( rc==SQLITE_OK ){
118851    int utf8 = SQLITE_UTF8;
118852    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
118853  }
118854  if( rc==SQLITE_OK ){
118855    void *c = (void *)RTREE_COORD_REAL32;
118856    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
118857  }
118858  if( rc==SQLITE_OK ){
118859    void *c = (void *)RTREE_COORD_INT32;
118860    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
118861  }
118862
118863  return rc;
118864}
118865
118866#if !SQLITE_CORE
118867SQLITE_API int sqlite3_extension_init(
118868  sqlite3 *db,
118869  char **pzErrMsg,
118870  const sqlite3_api_routines *pApi
118871){
118872  SQLITE_EXTENSION_INIT2(pApi)
118873  return sqlite3RtreeInit(db);
118874}
118875#endif
118876
118877#endif
118878
118879/************** End of rtree.c ***********************************************/
118880/************** Begin file icu.c *********************************************/
118881/*
118882** 2007 May 6
118883**
118884** The author disclaims copyright to this source code.  In place of
118885** a legal notice, here is a blessing:
118886**
118887**    May you do good and not evil.
118888**    May you find forgiveness for yourself and forgive others.
118889**    May you share freely, never taking more than you give.
118890**
118891*************************************************************************
118892** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
118893**
118894** This file implements an integration between the ICU library
118895** ("International Components for Unicode", an open-source library
118896** for handling unicode data) and SQLite. The integration uses
118897** ICU to provide the following to SQLite:
118898**
118899**   * An implementation of the SQL regexp() function (and hence REGEXP
118900**     operator) using the ICU uregex_XX() APIs.
118901**
118902**   * Implementations of the SQL scalar upper() and lower() functions
118903**     for case mapping.
118904**
118905**   * Integration of ICU and SQLite collation seqences.
118906**
118907**   * An implementation of the LIKE operator that uses ICU to
118908**     provide case-independent matching.
118909*/
118910
118911#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
118912
118913/* Include ICU headers */
118914#include <unicode/utypes.h>
118915#include <unicode/uregex.h>
118916#include <unicode/ustring.h>
118917#include <unicode/ucol.h>
118918
118919
118920#ifndef SQLITE_CORE
118921  SQLITE_EXTENSION_INIT1
118922#else
118923#endif
118924
118925/*
118926** Maximum length (in bytes) of the pattern in a LIKE or GLOB
118927** operator.
118928*/
118929#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
118930# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
118931#endif
118932
118933/*
118934** Version of sqlite3_free() that is always a function, never a macro.
118935*/
118936static void xFree(void *p){
118937  sqlite3_free(p);
118938}
118939
118940/*
118941** Compare two UTF-8 strings for equality where the first string is
118942** a "LIKE" expression. Return true (1) if they are the same and
118943** false (0) if they are different.
118944*/
118945static int icuLikeCompare(
118946  const uint8_t *zPattern,   /* LIKE pattern */
118947  const uint8_t *zString,    /* The UTF-8 string to compare against */
118948  const UChar32 uEsc         /* The escape character */
118949){
118950  static const int MATCH_ONE = (UChar32)'_';
118951  static const int MATCH_ALL = (UChar32)'%';
118952
118953  int iPattern = 0;       /* Current byte index in zPattern */
118954  int iString = 0;        /* Current byte index in zString */
118955
118956  int prevEscape = 0;     /* True if the previous character was uEsc */
118957
118958  while( zPattern[iPattern]!=0 ){
118959
118960    /* Read (and consume) the next character from the input pattern. */
118961    UChar32 uPattern;
118962    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
118963    assert(uPattern!=0);
118964
118965    /* There are now 4 possibilities:
118966    **
118967    **     1. uPattern is an unescaped match-all character "%",
118968    **     2. uPattern is an unescaped match-one character "_",
118969    **     3. uPattern is an unescaped escape character, or
118970    **     4. uPattern is to be handled as an ordinary character
118971    */
118972    if( !prevEscape && uPattern==MATCH_ALL ){
118973      /* Case 1. */
118974      uint8_t c;
118975
118976      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
118977      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
118978      ** test string.
118979      */
118980      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
118981        if( c==MATCH_ONE ){
118982          if( zString[iString]==0 ) return 0;
118983          U8_FWD_1_UNSAFE(zString, iString);
118984        }
118985        iPattern++;
118986      }
118987
118988      if( zPattern[iPattern]==0 ) return 1;
118989
118990      while( zString[iString] ){
118991        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
118992          return 1;
118993        }
118994        U8_FWD_1_UNSAFE(zString, iString);
118995      }
118996      return 0;
118997
118998    }else if( !prevEscape && uPattern==MATCH_ONE ){
118999      /* Case 2. */
119000      if( zString[iString]==0 ) return 0;
119001      U8_FWD_1_UNSAFE(zString, iString);
119002
119003    }else if( !prevEscape && uPattern==uEsc){
119004      /* Case 3. */
119005      prevEscape = 1;
119006
119007    }else{
119008      /* Case 4. */
119009      UChar32 uString;
119010      U8_NEXT_UNSAFE(zString, iString, uString);
119011      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
119012      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
119013      if( uString!=uPattern ){
119014        return 0;
119015      }
119016      prevEscape = 0;
119017    }
119018  }
119019
119020  return zString[iString]==0;
119021}
119022
119023/*
119024** Implementation of the like() SQL function.  This function implements
119025** the build-in LIKE operator.  The first argument to the function is the
119026** pattern and the second argument is the string.  So, the SQL statements:
119027**
119028**       A LIKE B
119029**
119030** is implemented as like(B, A). If there is an escape character E,
119031**
119032**       A LIKE B ESCAPE E
119033**
119034** is mapped to like(B, A, E).
119035*/
119036static void icuLikeFunc(
119037  sqlite3_context *context,
119038  int argc,
119039  sqlite3_value **argv
119040){
119041  const unsigned char *zA = sqlite3_value_text(argv[0]);
119042  const unsigned char *zB = sqlite3_value_text(argv[1]);
119043  UChar32 uEsc = 0;
119044
119045  /* Limit the length of the LIKE or GLOB pattern to avoid problems
119046  ** of deep recursion and N*N behavior in patternCompare().
119047  */
119048  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
119049    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
119050    return;
119051  }
119052
119053
119054  if( argc==3 ){
119055    /* The escape character string must consist of a single UTF-8 character.
119056    ** Otherwise, return an error.
119057    */
119058    int nE= sqlite3_value_bytes(argv[2]);
119059    const unsigned char *zE = sqlite3_value_text(argv[2]);
119060    int i = 0;
119061    if( zE==0 ) return;
119062    U8_NEXT(zE, i, nE, uEsc);
119063    if( i!=nE){
119064      sqlite3_result_error(context,
119065          "ESCAPE expression must be a single character", -1);
119066      return;
119067    }
119068  }
119069
119070  if( zA && zB ){
119071    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
119072  }
119073}
119074
119075/*
119076** This function is called when an ICU function called from within
119077** the implementation of an SQL scalar function returns an error.
119078**
119079** The scalar function context passed as the first argument is
119080** loaded with an error message based on the following two args.
119081*/
119082static void icuFunctionError(
119083  sqlite3_context *pCtx,       /* SQLite scalar function context */
119084  const char *zName,           /* Name of ICU function that failed */
119085  UErrorCode e                 /* Error code returned by ICU function */
119086){
119087  char zBuf[128];
119088  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
119089  zBuf[127] = '\0';
119090  sqlite3_result_error(pCtx, zBuf, -1);
119091}
119092
119093/*
119094** Function to delete compiled regexp objects. Registered as
119095** a destructor function with sqlite3_set_auxdata().
119096*/
119097static void icuRegexpDelete(void *p){
119098  URegularExpression *pExpr = (URegularExpression *)p;
119099  uregex_close(pExpr);
119100}
119101
119102/*
119103** Implementation of SQLite REGEXP operator. This scalar function takes
119104** two arguments. The first is a regular expression pattern to compile
119105** the second is a string to match against that pattern. If either
119106** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
119107** is 1 if the string matches the pattern, or 0 otherwise.
119108**
119109** SQLite maps the regexp() function to the regexp() operator such
119110** that the following two are equivalent:
119111**
119112**     zString REGEXP zPattern
119113**     regexp(zPattern, zString)
119114**
119115** Uses the following ICU regexp APIs:
119116**
119117**     uregex_open()
119118**     uregex_matches()
119119**     uregex_close()
119120*/
119121static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
119122  UErrorCode status = U_ZERO_ERROR;
119123  URegularExpression *pExpr;
119124  UBool res;
119125  const UChar *zString = sqlite3_value_text16(apArg[1]);
119126
119127  /* If the left hand side of the regexp operator is NULL,
119128  ** then the result is also NULL.
119129  */
119130  if( !zString ){
119131    return;
119132  }
119133
119134  pExpr = sqlite3_get_auxdata(p, 0);
119135  if( !pExpr ){
119136    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
119137    if( !zPattern ){
119138      return;
119139    }
119140    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
119141
119142    if( U_SUCCESS(status) ){
119143      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
119144    }else{
119145      assert(!pExpr);
119146      icuFunctionError(p, "uregex_open", status);
119147      return;
119148    }
119149  }
119150
119151  /* Configure the text that the regular expression operates on. */
119152  uregex_setText(pExpr, zString, -1, &status);
119153  if( !U_SUCCESS(status) ){
119154    icuFunctionError(p, "uregex_setText", status);
119155    return;
119156  }
119157
119158  /* Attempt the match */
119159  res = uregex_matches(pExpr, 0, &status);
119160  if( !U_SUCCESS(status) ){
119161    icuFunctionError(p, "uregex_matches", status);
119162    return;
119163  }
119164
119165  /* Set the text that the regular expression operates on to a NULL
119166  ** pointer. This is not really necessary, but it is tidier than
119167  ** leaving the regular expression object configured with an invalid
119168  ** pointer after this function returns.
119169  */
119170  uregex_setText(pExpr, 0, 0, &status);
119171
119172  /* Return 1 or 0. */
119173  sqlite3_result_int(p, res ? 1 : 0);
119174}
119175
119176/*
119177** Implementations of scalar functions for case mapping - upper() and
119178** lower(). Function upper() converts its input to upper-case (ABC).
119179** Function lower() converts to lower-case (abc).
119180**
119181** ICU provides two types of case mapping, "general" case mapping and
119182** "language specific". Refer to ICU documentation for the differences
119183** between the two.
119184**
119185** To utilise "general" case mapping, the upper() or lower() scalar
119186** functions are invoked with one argument:
119187**
119188**     upper('ABC') -> 'abc'
119189**     lower('abc') -> 'ABC'
119190**
119191** To access ICU "language specific" case mapping, upper() or lower()
119192** should be invoked with two arguments. The second argument is the name
119193** of the locale to use. Passing an empty string ("") or SQL NULL value
119194** as the second argument is the same as invoking the 1 argument version
119195** of upper() or lower().
119196**
119197**     lower('I', 'en_us') -> 'i'
119198**     lower('I', 'tr_tr') -> '��' (small dotless i)
119199**
119200** http://www.icu-project.org/userguide/posix.html#case_mappings
119201*/
119202static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
119203  const UChar *zInput;
119204  UChar *zOutput;
119205  int nInput;
119206  int nOutput;
119207
119208  UErrorCode status = U_ZERO_ERROR;
119209  const char *zLocale = 0;
119210
119211  assert(nArg==1 || nArg==2);
119212  if( nArg==2 ){
119213    zLocale = (const char *)sqlite3_value_text(apArg[1]);
119214  }
119215
119216  zInput = sqlite3_value_text16(apArg[0]);
119217  if( !zInput ){
119218    return;
119219  }
119220  nInput = sqlite3_value_bytes16(apArg[0]);
119221
119222  nOutput = nInput * 2 + 2;
119223  zOutput = sqlite3_malloc(nOutput);
119224  if( !zOutput ){
119225    return;
119226  }
119227
119228  if( sqlite3_user_data(p) ){
119229    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
119230  }else{
119231    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
119232  }
119233
119234  if( !U_SUCCESS(status) ){
119235    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
119236    return;
119237  }
119238
119239  sqlite3_result_text16(p, zOutput, -1, xFree);
119240}
119241
119242/*
119243** Collation sequence destructor function. The pCtx argument points to
119244** a UCollator structure previously allocated using ucol_open().
119245*/
119246static void icuCollationDel(void *pCtx){
119247  UCollator *p = (UCollator *)pCtx;
119248  ucol_close(p);
119249}
119250
119251/*
119252** Collation sequence comparison function. The pCtx argument points to
119253** a UCollator structure previously allocated using ucol_open().
119254*/
119255static int icuCollationColl(
119256  void *pCtx,
119257  int nLeft,
119258  const void *zLeft,
119259  int nRight,
119260  const void *zRight
119261){
119262  UCollationResult res;
119263  UCollator *p = (UCollator *)pCtx;
119264  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
119265  switch( res ){
119266    case UCOL_LESS:    return -1;
119267    case UCOL_GREATER: return +1;
119268    case UCOL_EQUAL:   return 0;
119269  }
119270  assert(!"Unexpected return value from ucol_strcoll()");
119271  return 0;
119272}
119273
119274/*
119275** Implementation of the scalar function icu_load_collation().
119276**
119277** This scalar function is used to add ICU collation based collation
119278** types to an SQLite database connection. It is intended to be called
119279** as follows:
119280**
119281**     SELECT icu_load_collation(<locale>, <collation-name>);
119282**
119283** Where <locale> is a string containing an ICU locale identifier (i.e.
119284** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
119285** collation sequence to create.
119286*/
119287static void icuLoadCollation(
119288  sqlite3_context *p,
119289  int nArg,
119290  sqlite3_value **apArg
119291){
119292  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
119293  UErrorCode status = U_ZERO_ERROR;
119294  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
119295  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
119296  UCollator *pUCollator;    /* ICU library collation object */
119297  int rc;                   /* Return code from sqlite3_create_collation_x() */
119298
119299  assert(nArg==2);
119300  zLocale = (const char *)sqlite3_value_text(apArg[0]);
119301  zName = (const char *)sqlite3_value_text(apArg[1]);
119302
119303  if( !zLocale || !zName ){
119304    return;
119305  }
119306
119307  pUCollator = ucol_open(zLocale, &status);
119308  if( !U_SUCCESS(status) ){
119309    icuFunctionError(p, "ucol_open", status);
119310    return;
119311  }
119312  assert(p);
119313
119314  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
119315      icuCollationColl, icuCollationDel
119316  );
119317  if( rc!=SQLITE_OK ){
119318    ucol_close(pUCollator);
119319    sqlite3_result_error(p, "Error registering collation function", -1);
119320  }
119321}
119322
119323/*
119324** Register the ICU extension functions with database db.
119325*/
119326SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
119327  struct IcuScalar {
119328    const char *zName;                        /* Function name */
119329    int nArg;                                 /* Number of arguments */
119330    int enc;                                  /* Optimal text encoding */
119331    void *pContext;                           /* sqlite3_user_data() context */
119332    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
119333  } scalars[] = {
119334    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
119335
119336    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
119337    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
119338    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
119339    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
119340
119341    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
119342    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
119343    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
119344    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
119345
119346    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
119347    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
119348
119349    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
119350  };
119351
119352  int rc = SQLITE_OK;
119353  int i;
119354
119355  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
119356    struct IcuScalar *p = &scalars[i];
119357    rc = sqlite3_create_function(
119358        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
119359    );
119360  }
119361
119362  return rc;
119363}
119364
119365#if !SQLITE_CORE
119366SQLITE_API int sqlite3_extension_init(
119367  sqlite3 *db,
119368  char **pzErrMsg,
119369  const sqlite3_api_routines *pApi
119370){
119371  SQLITE_EXTENSION_INIT2(pApi)
119372  return sqlite3IcuInit(db);
119373}
119374#endif
119375
119376#endif
119377
119378/************** End of icu.c *************************************************/
119379/************** Begin file fts3_icu.c ****************************************/
119380/*
119381** 2007 June 22
119382**
119383** The author disclaims copyright to this source code.  In place of
119384** a legal notice, here is a blessing:
119385**
119386**    May you do good and not evil.
119387**    May you find forgiveness for yourself and forgive others.
119388**    May you share freely, never taking more than you give.
119389**
119390*************************************************************************
119391** This file implements a tokenizer for fts3 based on the ICU library.
119392**
119393** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
119394*/
119395
119396#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119397#ifdef SQLITE_ENABLE_ICU
119398
119399
119400#include <unicode/ubrk.h>
119401#include <unicode/utf16.h>
119402
119403typedef struct IcuTokenizer IcuTokenizer;
119404typedef struct IcuCursor IcuCursor;
119405
119406struct IcuTokenizer {
119407  sqlite3_tokenizer base;
119408  char *zLocale;
119409};
119410
119411struct IcuCursor {
119412  sqlite3_tokenizer_cursor base;
119413
119414  UBreakIterator *pIter;      /* ICU break-iterator object */
119415  int nChar;                  /* Number of UChar elements in pInput */
119416  UChar *aChar;               /* Copy of input using utf-16 encoding */
119417  int *aOffset;               /* Offsets of each character in utf-8 input */
119418
119419  int nBuffer;
119420  char *zBuffer;
119421
119422  int iToken;
119423};
119424
119425/*
119426** Create a new tokenizer instance.
119427*/
119428static int icuCreate(
119429  int argc,                            /* Number of entries in argv[] */
119430  const char * const *argv,            /* Tokenizer creation arguments */
119431  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
119432){
119433  IcuTokenizer *p;
119434  int n = 0;
119435
119436  if( argc>0 ){
119437    n = strlen(argv[0])+1;
119438  }
119439  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
119440  if( !p ){
119441    return SQLITE_NOMEM;
119442  }
119443  memset(p, 0, sizeof(IcuTokenizer));
119444
119445  if( n ){
119446    p->zLocale = (char *)&p[1];
119447    memcpy(p->zLocale, argv[0], n);
119448  }
119449
119450  *ppTokenizer = (sqlite3_tokenizer *)p;
119451
119452  return SQLITE_OK;
119453}
119454
119455/*
119456** Destroy a tokenizer
119457*/
119458static int icuDestroy(sqlite3_tokenizer *pTokenizer){
119459  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
119460  sqlite3_free(p);
119461  return SQLITE_OK;
119462}
119463
119464/*
119465** Prepare to begin tokenizing a particular string.  The input
119466** string to be tokenized is pInput[0..nBytes-1].  A cursor
119467** used to incrementally tokenize this string is returned in
119468** *ppCursor.
119469*/
119470static int icuOpen(
119471  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
119472  const char *zInput,                    /* Input string */
119473  int nInput,                            /* Length of zInput in bytes */
119474  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
119475){
119476  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
119477  IcuCursor *pCsr;
119478
119479  const int32_t opt = U_FOLD_CASE_DEFAULT;
119480  UErrorCode status = U_ZERO_ERROR;
119481  int nChar;
119482
119483  UChar32 c;
119484  int iInput = 0;
119485  int iOut = 0;
119486
119487  *ppCursor = 0;
119488
119489  if( nInput<0 ){
119490    nInput = strlen(zInput);
119491  }
119492  nChar = nInput+1;
119493  pCsr = (IcuCursor *)sqlite3_malloc(
119494      sizeof(IcuCursor) +                /* IcuCursor */
119495      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
119496      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
119497  );
119498  if( !pCsr ){
119499    return SQLITE_NOMEM;
119500  }
119501  memset(pCsr, 0, sizeof(IcuCursor));
119502  pCsr->aChar = (UChar *)&pCsr[1];
119503  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
119504
119505  pCsr->aOffset[iOut] = iInput;
119506  U8_NEXT(zInput, iInput, nInput, c);
119507  while( c>0 ){
119508    int isError = 0;
119509    c = u_foldCase(c, opt);
119510    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
119511    if( isError ){
119512      sqlite3_free(pCsr);
119513      return SQLITE_ERROR;
119514    }
119515    pCsr->aOffset[iOut] = iInput;
119516
119517    if( iInput<nInput ){
119518      U8_NEXT(zInput, iInput, nInput, c);
119519    }else{
119520      c = 0;
119521    }
119522  }
119523
119524  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
119525  if( !U_SUCCESS(status) ){
119526    sqlite3_free(pCsr);
119527    return SQLITE_ERROR;
119528  }
119529  pCsr->nChar = iOut;
119530
119531  ubrk_first(pCsr->pIter);
119532  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
119533  return SQLITE_OK;
119534}
119535
119536/*
119537** Close a tokenization cursor previously opened by a call to icuOpen().
119538*/
119539static int icuClose(sqlite3_tokenizer_cursor *pCursor){
119540  IcuCursor *pCsr = (IcuCursor *)pCursor;
119541  ubrk_close(pCsr->pIter);
119542  sqlite3_free(pCsr->zBuffer);
119543  sqlite3_free(pCsr);
119544  return SQLITE_OK;
119545}
119546
119547/*
119548** Extract the next token from a tokenization cursor.
119549*/
119550static int icuNext(
119551  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
119552  const char **ppToken,               /* OUT: *ppToken is the token text */
119553  int *pnBytes,                       /* OUT: Number of bytes in token */
119554  int *piStartOffset,                 /* OUT: Starting offset of token */
119555  int *piEndOffset,                   /* OUT: Ending offset of token */
119556  int *piPosition                     /* OUT: Position integer of token */
119557){
119558  IcuCursor *pCsr = (IcuCursor *)pCursor;
119559
119560  int iStart = 0;
119561  int iEnd = 0;
119562  int nByte = 0;
119563
119564  while( iStart==iEnd ){
119565    UChar32 c;
119566
119567    iStart = ubrk_current(pCsr->pIter);
119568    iEnd = ubrk_next(pCsr->pIter);
119569    if( iEnd==UBRK_DONE ){
119570      return SQLITE_DONE;
119571    }
119572
119573    while( iStart<iEnd ){
119574      int iWhite = iStart;
119575      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
119576      if( u_isspace(c) ){
119577        iStart = iWhite;
119578      }else{
119579        break;
119580      }
119581    }
119582    assert(iStart<=iEnd);
119583  }
119584
119585  do {
119586    UErrorCode status = U_ZERO_ERROR;
119587    if( nByte ){
119588      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
119589      if( !zNew ){
119590        return SQLITE_NOMEM;
119591      }
119592      pCsr->zBuffer = zNew;
119593      pCsr->nBuffer = nByte;
119594    }
119595
119596    u_strToUTF8(
119597        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
119598        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
119599        &status                                  /* Output success/failure */
119600    );
119601  } while( nByte>pCsr->nBuffer );
119602
119603  *ppToken = pCsr->zBuffer;
119604  *pnBytes = nByte;
119605  *piStartOffset = pCsr->aOffset[iStart];
119606  *piEndOffset = pCsr->aOffset[iEnd];
119607  *piPosition = pCsr->iToken++;
119608
119609  return SQLITE_OK;
119610}
119611
119612/*
119613** The set of routines that implement the simple tokenizer
119614*/
119615static const sqlite3_tokenizer_module icuTokenizerModule = {
119616  0,                           /* iVersion */
119617  icuCreate,                   /* xCreate  */
119618  icuDestroy,                  /* xCreate  */
119619  icuOpen,                     /* xOpen    */
119620  icuClose,                    /* xClose   */
119621  icuNext,                     /* xNext    */
119622};
119623
119624/*
119625** Set *ppModule to point at the implementation of the ICU tokenizer.
119626*/
119627SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
119628  sqlite3_tokenizer_module const**ppModule
119629){
119630  *ppModule = &icuTokenizerModule;
119631}
119632
119633#endif /* defined(SQLITE_ENABLE_ICU) */
119634#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119635
119636/************** End of fts3_icu.c ********************************************/
119637